@hashgraphonline/conversational-agent 0.1.209 → 0.1.210
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/conversational-agent-cli.js +30 -0
- package/cli/readme.md +181 -0
- package/dist/cjs/base-agent.d.ts +3 -1
- package/dist/cjs/conversational-agent.d.ts +14 -22
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +5 -3
- package/dist/cjs/langchain-agent.d.ts +6 -3
- package/dist/cjs/memory/SmartMemoryManager.d.ts +7 -1
- package/dist/cjs/memory/TokenCounter.d.ts +1 -1
- package/dist/cjs/plugins/hbar/AirdropToolWrapper.d.ts +43 -0
- package/dist/{types/plugins/hbar-transfer/HbarTransferPlugin.d.ts → cjs/plugins/hbar/HbarPlugin.d.ts} +2 -1
- package/dist/{types/plugins/hbar-transfer → cjs/plugins/hbar}/TransferHbarTool.d.ts +1 -1
- package/dist/cjs/plugins/hbar/index.d.ts +3 -0
- package/dist/cjs/plugins/index.d.ts +2 -1
- package/dist/cjs/services/EntityResolver.d.ts +26 -0
- package/dist/cjs/tools/EntityResolverTool.d.ts +104 -0
- package/dist/cjs/types/inscription.d.ts +37 -0
- package/dist/esm/index.js +8 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index12.js +1 -4
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index13.js +0 -1
- package/dist/esm/index13.js.map +1 -1
- package/dist/esm/index14.js +2 -7
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +31 -69
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +126 -39
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +148 -13
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +44 -146
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +100 -6
- package/dist/esm/index19.js.map +1 -1
- package/dist/esm/index20.js +20 -174
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +7 -151
- package/dist/esm/index21.js.map +1 -1
- package/dist/esm/index22.js +154 -45
- package/dist/esm/index22.js.map +1 -1
- package/dist/esm/index23.js +149 -24
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +56 -83
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +24 -236
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index26.js +95 -0
- package/dist/esm/index26.js.map +1 -0
- package/dist/esm/index27.js +242 -0
- package/dist/esm/index27.js.map +1 -0
- package/dist/esm/index5.js +32 -19
- package/dist/esm/index5.js.map +1 -1
- package/dist/esm/index6.js +156 -195
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index7.js +2 -2
- package/dist/esm/index7.js.map +1 -1
- package/dist/esm/index8.js +80 -48
- package/dist/esm/index8.js.map +1 -1
- package/dist/types/base-agent.d.ts +3 -1
- package/dist/types/conversational-agent.d.ts +14 -22
- package/dist/types/index.d.ts +5 -3
- package/dist/types/langchain-agent.d.ts +6 -3
- package/dist/types/memory/SmartMemoryManager.d.ts +7 -1
- package/dist/types/memory/TokenCounter.d.ts +1 -1
- package/dist/types/plugins/hbar/AirdropToolWrapper.d.ts +43 -0
- package/dist/{cjs/plugins/hbar-transfer/HbarTransferPlugin.d.ts → types/plugins/hbar/HbarPlugin.d.ts} +2 -1
- package/dist/{cjs/plugins/hbar-transfer → types/plugins/hbar}/TransferHbarTool.d.ts +1 -1
- package/dist/types/plugins/hbar/index.d.ts +3 -0
- package/dist/types/plugins/index.d.ts +2 -1
- package/dist/types/services/EntityResolver.d.ts +26 -0
- package/dist/types/tools/EntityResolverTool.d.ts +104 -0
- package/dist/types/types/inscription.d.ts +37 -0
- package/package.json +13 -4
- package/src/base-agent.ts +14 -9
- package/src/config/system-message.ts +11 -2
- package/src/context/ReferenceContextManager.ts +1 -1
- package/src/conversational-agent.ts +221 -254
- package/src/index.ts +17 -3
- package/src/langchain-agent.ts +130 -78
- package/src/mcp/ContentProcessor.ts +0 -2
- package/src/mcp/adapters/langchain.ts +0 -1
- package/src/memory/ContentStorage.ts +0 -5
- package/src/memory/MemoryWindow.ts +0 -1
- package/src/memory/ReferenceIdGenerator.ts +4 -4
- package/src/memory/SmartMemoryManager.ts +53 -92
- package/src/memory/TokenCounter.ts +4 -7
- package/src/plugins/hbar/AirdropToolWrapper.ts +157 -0
- package/src/plugins/hbar/HbarPlugin.ts +86 -0
- package/src/plugins/{hbar-transfer → hbar}/TransferHbarTool.ts +3 -3
- package/src/plugins/hbar/index.ts +3 -0
- package/src/plugins/index.ts +2 -1
- package/src/services/EntityResolver.ts +135 -0
- package/src/tools/EntityResolverTool.ts +170 -0
- package/src/types/inscription.ts +40 -0
- package/dist/cjs/plugins/hbar-transfer/index.d.ts +0 -1
- package/dist/types/plugins/hbar-transfer/index.d.ts +0 -1
- package/src/plugins/hbar-transfer/HbarTransferPlugin.ts +0 -66
- package/src/plugins/hbar-transfer/index.ts +0 -1
- /package/dist/cjs/plugins/{hbar-transfer → hbar}/AccountBuilder.d.ts +0 -0
- /package/dist/cjs/plugins/{hbar-transfer → hbar}/types.d.ts +0 -0
- /package/dist/types/plugins/{hbar-transfer → hbar}/AccountBuilder.d.ts +0 -0
- /package/dist/types/plugins/{hbar-transfer → hbar}/types.d.ts +0 -0
- /package/src/plugins/{hbar-transfer → hbar}/AccountBuilder.ts +0 -0
- /package/src/plugins/{hbar-transfer → hbar}/types.ts +0 -0
package/dist/esm/index14.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;A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AAQ,MAAA;AAAA,MACN,KAAK;AACH,gBAAQ,cAAc,KAAK,MAAM;AACjC,YAAI,QAAQ,cAAc,SAAS,YAAY;AAC7C,kBAAQ,cAAc,MAAA;AAAA,QACxB;AACA;AAAA,MACF,KAAK;AACH,gBAAQ,gBAAgB,KAAK,MAAM;AACnC,YAAI,QAAQ,gBAAgB,SAAS,YAAY;AAC/C,kBAAQ,gBAAgB,MAAA;AAAA,QAC1B;AACA;AAAA,MACF,KAAK;AACH,gBAAQ,aAAa,KAAK,MAAM;AAChC,YAAI,QAAQ,aAAa,SAAS,YAAY;AAC5C,kBAAQ,aAAa,MAAA;AAAA,QACvB;AACA;AAAA,IAAA;AAAA,EAEN;AAAA,EAEQ,iBAAiB,OAAyB;AAChD,QAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,WAAO,MAAM,OAAO,CAAC,KAAK,SAAS,MAAM,MAAM,CAAC,IAAI,MAAM;AAAA,EAC5D;AAAA,EAEQ,6BAAmC;AACzC,SAAK,eAAe,YAAY,YAAY;AAC1C,UAAI;AACF,cAAM,KAAK,eAAA;AAAA,MACb,SAAS,OAAO;AACd,gBAAQ,MAAM,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
|
+
{"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 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 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 \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 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 }\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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,gBAAgB,MAAA;AAAA,QAC1B;AACA;AAAA,MACF,KAAK;AACH,gBAAQ,aAAa,KAAK,MAAM;AAChC,YAAI,QAAQ,aAAa,SAAS,YAAY;AAC5C,kBAAQ,aAAa,MAAA;AAAA,QACvB;AACA;AAAA,IAAA;AAAA,EAEN;AAAA,EAEQ,iBAAiB,OAAyB;AAChD,QAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,WAAO,MAAM,OAAO,CAAC,KAAK,SAAS,MAAM,MAAM,CAAC,IAAI,MAAM;AAAA,EAC5D;AAAA,EAEQ,6BAAmC;AACzC,SAAK,eAAe,YAAY,YAAY;AAC1C,UAAI;AACF,cAAM,KAAK,eAAA;AAAA,MACb,SAAS,OAAO;AAAA,MAChB;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;AA7xBE,gBAAuB,sBAAsB;AAhBxC,IAAM,iBAAN;"}
|
package/dist/esm/index15.js
CHANGED
|
@@ -6,13 +6,20 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
6
6
|
constructor(config = {}) {
|
|
7
7
|
this.config = { ..._SmartMemoryManager.DEFAULT_CONFIG, ...config };
|
|
8
8
|
this.tokenCounter = new TokenCounter(this.config.modelName);
|
|
9
|
-
this.
|
|
9
|
+
this._contentStorage = new ContentStorage(this.config.storageLimit);
|
|
10
10
|
this.memoryWindow = new MemoryWindow(
|
|
11
11
|
this.config.maxTokens,
|
|
12
12
|
this.config.reserveTokens,
|
|
13
13
|
this.tokenCounter
|
|
14
14
|
);
|
|
15
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Get the content storage instance for file/content reference operations
|
|
18
|
+
* @returns ContentStorage instance
|
|
19
|
+
*/
|
|
20
|
+
get contentStorage() {
|
|
21
|
+
return this._contentStorage;
|
|
22
|
+
}
|
|
16
23
|
/**
|
|
17
24
|
* Add a message to the active memory window
|
|
18
25
|
* Automatically handles pruning and storage of displaced messages
|
|
@@ -21,7 +28,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
21
28
|
addMessage(message) {
|
|
22
29
|
const result = this.memoryWindow.addMessage(message);
|
|
23
30
|
if (result.prunedMessages.length > 0) {
|
|
24
|
-
this.
|
|
31
|
+
this._contentStorage.storeMessages(result.prunedMessages);
|
|
25
32
|
}
|
|
26
33
|
}
|
|
27
34
|
/**
|
|
@@ -38,7 +45,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
38
45
|
clear(clearStorage = false) {
|
|
39
46
|
this.memoryWindow.clear();
|
|
40
47
|
if (clearStorage) {
|
|
41
|
-
this.
|
|
48
|
+
this._contentStorage.clear();
|
|
42
49
|
}
|
|
43
50
|
}
|
|
44
51
|
/**
|
|
@@ -62,7 +69,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
62
69
|
* @returns Array of matching messages from history
|
|
63
70
|
*/
|
|
64
71
|
searchHistory(query, options = {}) {
|
|
65
|
-
return this.
|
|
72
|
+
return this._contentStorage.searchMessages(query, options);
|
|
66
73
|
}
|
|
67
74
|
/**
|
|
68
75
|
* Get recent messages from storage history
|
|
@@ -70,7 +77,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
70
77
|
* @returns Array of recent messages from storage
|
|
71
78
|
*/
|
|
72
79
|
getRecentHistory(count) {
|
|
73
|
-
return this.
|
|
80
|
+
return this._contentStorage.getRecentMessages(count);
|
|
74
81
|
}
|
|
75
82
|
/**
|
|
76
83
|
* Check if a message can be added without exceeding limits
|
|
@@ -100,7 +107,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
100
107
|
* @returns Storage usage statistics
|
|
101
108
|
*/
|
|
102
109
|
getStorageStats() {
|
|
103
|
-
return this.
|
|
110
|
+
return this._contentStorage.getStorageStats();
|
|
104
111
|
}
|
|
105
112
|
/**
|
|
106
113
|
* Get combined statistics for both active memory and storage
|
|
@@ -130,7 +137,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
130
137
|
);
|
|
131
138
|
}
|
|
132
139
|
if (newConfig.storageLimit !== void 0) {
|
|
133
|
-
this.
|
|
140
|
+
this._contentStorage.updateStorageLimit(this.config.storageLimit);
|
|
134
141
|
}
|
|
135
142
|
}
|
|
136
143
|
/**
|
|
@@ -147,7 +154,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
147
154
|
* @returns Messages within the specified time range
|
|
148
155
|
*/
|
|
149
156
|
getHistoryFromTimeRange(startTime, endTime) {
|
|
150
|
-
return this.
|
|
157
|
+
return this._contentStorage.getMessagesFromTimeRange(startTime, endTime);
|
|
151
158
|
}
|
|
152
159
|
/**
|
|
153
160
|
* Get messages from storage by message type
|
|
@@ -156,7 +163,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
156
163
|
* @returns Messages of the specified type
|
|
157
164
|
*/
|
|
158
165
|
getHistoryByType(messageType, limit) {
|
|
159
|
-
return this.
|
|
166
|
+
return this._contentStorage.getMessagesByType(messageType, limit);
|
|
160
167
|
}
|
|
161
168
|
/**
|
|
162
169
|
* Get recent messages from storage within the last N minutes
|
|
@@ -164,7 +171,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
164
171
|
* @returns Messages from the last N minutes
|
|
165
172
|
*/
|
|
166
173
|
getRecentHistoryByTime(minutes) {
|
|
167
|
-
return this.
|
|
174
|
+
return this._contentStorage.getRecentMessagesByTime(minutes);
|
|
168
175
|
}
|
|
169
176
|
/**
|
|
170
177
|
* Export the current state for persistence or analysis
|
|
@@ -180,7 +187,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
180
187
|
systemPrompt: this.memoryWindow.getSystemPrompt(),
|
|
181
188
|
memoryStats: this.getMemoryStats(),
|
|
182
189
|
storageStats: this.getStorageStats(),
|
|
183
|
-
storedMessages: this.
|
|
190
|
+
storedMessages: this._contentStorage.exportMessages()
|
|
184
191
|
};
|
|
185
192
|
}
|
|
186
193
|
/**
|
|
@@ -223,24 +230,12 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
223
230
|
storeEntityAssociation(entityId, entityName, entityType, transactionId) {
|
|
224
231
|
try {
|
|
225
232
|
if (!entityId || typeof entityId !== "string" || entityId.trim().length === 0) {
|
|
226
|
-
console.warn(
|
|
227
|
-
"[SmartMemoryManager] Invalid entityId provided:",
|
|
228
|
-
entityId
|
|
229
|
-
);
|
|
230
233
|
return;
|
|
231
234
|
}
|
|
232
235
|
if (!entityName || typeof entityName !== "string" || entityName.trim().length === 0) {
|
|
233
|
-
console.warn(
|
|
234
|
-
"[SmartMemoryManager] Invalid entityName provided:",
|
|
235
|
-
entityName
|
|
236
|
-
);
|
|
237
236
|
return;
|
|
238
237
|
}
|
|
239
238
|
if (!entityType || typeof entityType !== "string" || entityType.trim().length === 0) {
|
|
240
|
-
console.warn(
|
|
241
|
-
"[SmartMemoryManager] Invalid entityType provided:",
|
|
242
|
-
entityType
|
|
243
|
-
);
|
|
244
239
|
return;
|
|
245
240
|
}
|
|
246
241
|
const sanitizedEntityId = entityId.trim();
|
|
@@ -251,6 +246,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
251
246
|
entityName: sanitizedEntityName,
|
|
252
247
|
entityType: sanitizedEntityType,
|
|
253
248
|
createdAt: /* @__PURE__ */ new Date(),
|
|
249
|
+
isEntityAssociation: true,
|
|
254
250
|
...transactionId !== void 0 && transactionId !== null && transactionId.trim() !== "" ? { transactionId: transactionId.trim() } : {}
|
|
255
251
|
};
|
|
256
252
|
const content = JSON.stringify(association);
|
|
@@ -266,15 +262,8 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
266
262
|
isEntityAssociation: true
|
|
267
263
|
}
|
|
268
264
|
};
|
|
269
|
-
this.
|
|
270
|
-
console.debug(
|
|
271
|
-
`[SmartMemoryManager] Stored entity association: ${sanitizedEntityName} (${sanitizedEntityType}) -> ${sanitizedEntityId}`
|
|
272
|
-
);
|
|
265
|
+
this._contentStorage.storeMessages([entityMessage]);
|
|
273
266
|
} catch (_error) {
|
|
274
|
-
console.error(
|
|
275
|
-
"[SmartMemoryManager] Failed to store entity association:",
|
|
276
|
-
_error
|
|
277
|
-
);
|
|
278
267
|
}
|
|
279
268
|
}
|
|
280
269
|
/**
|
|
@@ -286,10 +275,6 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
286
275
|
resolveEntityReference(query, options = {}) {
|
|
287
276
|
try {
|
|
288
277
|
if (!query || typeof query !== "string") {
|
|
289
|
-
console.warn(
|
|
290
|
-
"[SmartMemoryManager] Invalid query provided for entity resolution:",
|
|
291
|
-
query
|
|
292
|
-
);
|
|
293
278
|
return [];
|
|
294
279
|
}
|
|
295
280
|
const sanitizedQuery = query.trim();
|
|
@@ -297,14 +282,11 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
297
282
|
return [];
|
|
298
283
|
}
|
|
299
284
|
if (sanitizedQuery.length > 200) {
|
|
300
|
-
console.warn(
|
|
301
|
-
"[SmartMemoryManager] Query too long, truncating:",
|
|
302
|
-
sanitizedQuery.length
|
|
303
|
-
);
|
|
304
285
|
}
|
|
305
286
|
const { entityType, limit = 10, fuzzyMatch = true } = options;
|
|
306
287
|
const safeLimit = Math.max(1, Math.min(limit || 10, 100));
|
|
307
|
-
const
|
|
288
|
+
const isEntityIdQuery = /^0\.0\.\d+$/.test(sanitizedQuery);
|
|
289
|
+
const searchResults = this._contentStorage.searchMessages(
|
|
308
290
|
sanitizedQuery.substring(0, 200),
|
|
309
291
|
{
|
|
310
292
|
caseSensitive: false,
|
|
@@ -321,6 +303,11 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
321
303
|
if (entityType && parsed.entityType !== entityType) {
|
|
322
304
|
continue;
|
|
323
305
|
}
|
|
306
|
+
if (isEntityIdQuery) {
|
|
307
|
+
if (parsed.entityId !== sanitizedQuery) {
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
324
311
|
associations.push(parsed);
|
|
325
312
|
}
|
|
326
313
|
}
|
|
@@ -328,7 +315,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
328
315
|
continue;
|
|
329
316
|
}
|
|
330
317
|
}
|
|
331
|
-
if (fuzzyMatch && associations.length === 0) {
|
|
318
|
+
if (fuzzyMatch && associations.length === 0 && !isEntityIdQuery) {
|
|
332
319
|
const fuzzyQueries = [
|
|
333
320
|
query.toLowerCase(),
|
|
334
321
|
`token`,
|
|
@@ -337,7 +324,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
337
324
|
].filter(Boolean);
|
|
338
325
|
for (const fuzzyQuery of fuzzyQueries) {
|
|
339
326
|
if (fuzzyQuery === query.toLowerCase()) continue;
|
|
340
|
-
const fuzzyResults = this.
|
|
327
|
+
const fuzzyResults = this._contentStorage.searchMessages(fuzzyQuery, {
|
|
341
328
|
caseSensitive: false,
|
|
342
329
|
limit
|
|
343
330
|
});
|
|
@@ -365,18 +352,8 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
365
352
|
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
366
353
|
);
|
|
367
354
|
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
355
|
return results;
|
|
375
356
|
} catch (_error) {
|
|
376
|
-
console.error(
|
|
377
|
-
"[SmartMemoryManager] Failed to resolve entity reference:",
|
|
378
|
-
_error
|
|
379
|
-
);
|
|
380
357
|
return [];
|
|
381
358
|
}
|
|
382
359
|
}
|
|
@@ -389,15 +366,11 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
389
366
|
try {
|
|
390
367
|
const sanitizedEntityType = entityType ? entityType.trim().toLowerCase() : void 0;
|
|
391
368
|
if (entityType && (!sanitizedEntityType || sanitizedEntityType.length === 0)) {
|
|
392
|
-
console.warn(
|
|
393
|
-
"[SmartMemoryManager] Invalid entityType filter provided:",
|
|
394
|
-
entityType
|
|
395
|
-
);
|
|
396
369
|
return [];
|
|
397
370
|
}
|
|
398
371
|
const SEARCH_ANY_ENTITY = "entityId";
|
|
399
372
|
const searchQuery = sanitizedEntityType || SEARCH_ANY_ENTITY;
|
|
400
|
-
const searchResults = this.
|
|
373
|
+
const searchResults = this._contentStorage.searchMessages(searchQuery, {
|
|
401
374
|
caseSensitive: false,
|
|
402
375
|
limit: 100
|
|
403
376
|
});
|
|
@@ -418,10 +391,6 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
418
391
|
}
|
|
419
392
|
}
|
|
420
393
|
} catch (_parseError) {
|
|
421
|
-
console.debug(
|
|
422
|
-
"[SmartMemoryManager] Skipped malformed association data:",
|
|
423
|
-
_parseError
|
|
424
|
-
);
|
|
425
394
|
continue;
|
|
426
395
|
}
|
|
427
396
|
}
|
|
@@ -433,15 +402,8 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
433
402
|
const bTime = getTime(b.createdAt);
|
|
434
403
|
return bTime - aTime;
|
|
435
404
|
});
|
|
436
|
-
console.debug(
|
|
437
|
-
`[SmartMemoryManager] Retrieved ${results.length} entity associations${sanitizedEntityType ? ` of type '${sanitizedEntityType}'` : ""}`
|
|
438
|
-
);
|
|
439
405
|
return results;
|
|
440
406
|
} catch (_error) {
|
|
441
|
-
console.error(
|
|
442
|
-
"[SmartMemoryManager] Failed to get entity associations:",
|
|
443
|
-
_error
|
|
444
|
-
);
|
|
445
407
|
return [];
|
|
446
408
|
}
|
|
447
409
|
}
|
|
@@ -450,7 +412,7 @@ const _SmartMemoryManager = class _SmartMemoryManager {
|
|
|
450
412
|
*/
|
|
451
413
|
dispose() {
|
|
452
414
|
this.memoryWindow.dispose();
|
|
453
|
-
this.
|
|
415
|
+
this._contentStorage.dispose();
|
|
454
416
|
this.tokenCounter.dispose();
|
|
455
417
|
}
|
|
456
418
|
};
|
package/dist/esm/index15.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;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D;AAAA,MAAA;AAGF,aAAO;AAAA,IACT,SAAS,QAAQ;AACf,cAAQ;AAAA,QACN;AAAA,QACA;AAAA,MAAA;AAEF,aAAO,CAAA;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UAAgB;AACd,SAAK,aAAa,QAAA;AAClB,SAAK,eAAe,QAAA;AACpB,SAAK,aAAa,QAAA;AAAA,EACpB;AACF;AAxlBE,oBAAwB,iBAA8C;AAAA,EACpE,WAAW;AAAA,EACX,eAAe;AAAA,EACf,WAAW;AAAA,EACX,cAAc;AAAA;AAVX,IAAM,qBAAN;"}
|
|
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/**\n * TODO: investigate using chroma / rag for long term memory\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);\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 * Get the content storage instance for file/content reference operations\n * @returns ContentStorage instance\n */\n get contentStorage(): ContentStorage {\n return this._contentStorage;\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 * 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 * 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 return;\n }\n\n if (\n !entityName ||\n typeof entityName !== 'string' ||\n entityName.trim().length === 0\n ) {\n return;\n }\n\n if (\n !entityType ||\n typeof entityType !== 'string' ||\n entityType.trim().length === 0\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 & { isEntityAssociation: boolean } =\n {\n entityId: sanitizedEntityId,\n entityName: sanitizedEntityName,\n entityType: sanitizedEntityType,\n createdAt: new Date(),\n isEntityAssociation: true,\n ...(transactionId !== undefined &&\n transactionId !== null &&\n 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 BaseMessage]);\n } catch (_error) {}\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 return [];\n }\n\n const sanitizedQuery = query.trim();\n if (sanitizedQuery.length === 0) {\n return [];\n }\n\n if (sanitizedQuery.length > 200) {\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 isEntityIdQuery = /^0\\.0\\.\\d+$/.test(sanitizedQuery);\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 if (isEntityIdQuery) {\n if (parsed.entityId !== sanitizedQuery) {\n continue;\n }\n }\n\n associations.push(parsed as EntityAssociation);\n }\n }\n } catch {\n continue;\n }\n }\n\n if (fuzzyMatch && associations.length === 0 && !isEntityIdQuery) {\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 return results;\n } catch (_error) {\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 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 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 return results;\n } catch (_error) {\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;AAQ5B,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,SAAS;AAC1D,SAAK,kBAAkB,IAAI,eAAe,KAAK,OAAO,YAAY;AAClE,SAAK,eAAe,IAAI;AAAA,MACtB,KAAK,OAAO;AAAA,MACZ,KAAK,OAAO;AAAA,MACZ,KAAK;AAAA,IAAA;AAAA,EAET;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,iBAAiC;AACnC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,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