@hashgraphonline/conversational-agent 0.1.221 → 0.2.0

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.
@@ -3,8 +3,8 @@ import { extractRenderConfigs, generateFieldOrdering } from "@hashgraphonline/st
3
3
  import { Logger } from "@hashgraphonline/standards-sdk";
4
4
  import { fieldTypeRegistry } from "./index12.js";
5
5
  import { fieldGuidanceRegistry } from "./index13.js";
6
- import "./index37.js";
7
- import { FIELD_PRIORITIES } from "./index38.js";
6
+ import "./index38.js";
7
+ import { FIELD_PRIORITIES } from "./index39.js";
8
8
  function isZodObjectSchema(schema) {
9
9
  return typeof schema === "object" && schema !== null && "shape" in schema;
10
10
  }
@@ -1,5 +1,5 @@
1
1
  import { ReferenceIdGenerator } from "./index22.js";
2
- import { DEFAULT_CONTENT_REFERENCE_CONFIG, ContentReferenceError } from "./index39.js";
2
+ import { DEFAULT_CONTENT_REFERENCE_CONFIG, ContentReferenceError } from "./index37.js";
3
3
  const _ContentStorage = class _ContentStorage {
4
4
  constructor(maxStorage = _ContentStorage.DEFAULT_MAX_STORAGE, referenceConfig) {
5
5
  this.messages = [];
@@ -207,7 +207,7 @@ const _ContentStorage = class _ContentStorage {
207
207
  */
208
208
  exportMessages() {
209
209
  return this.messages.map((stored) => ({
210
- content: stored.message.content,
210
+ content: typeof stored.message.content === "string" ? stored.message.content : JSON.stringify(stored.message.content),
211
211
  type: stored.message._getType(),
212
212
  storedAt: stored.storedAt.toISOString(),
213
213
  id: stored.id
@@ -1 +1 @@
1
- {"version":3,"file":"index21.js","sources":["../../src/memory/content-storage.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport { ReferenceIdGenerator } from './reference-id-generator';\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 = {\n ...DEFAULT_CONTENT_REFERENCE_CONFIG,\n ...referenceConfig,\n };\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.slice(startIndex).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 { caseSensitive = false, limit, useRegex = false } = 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 {\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(\n (stored) => 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 =\n 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(): { maxStorage: number; currentUsage: number; utilizationPercentage: number } {\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(): Array<{ content: string; type: string; storedAt: string; id: string }> {\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 * 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)\n ? content.length\n : 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 * Special case: Image files are ALWAYS stored as references regardless of size\n * because they need special handling for inscription tools\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)\n ? content\n : Buffer.from(content, 'utf8');\n\n const isImageFile = this.isImageContent(\n metadata.mimeType,\n metadata.fileName\n );\n\n if (!isImageFile && !this.shouldUseReference(buffer)) {\n return null;\n }\n\n const storeMetadata: Omit<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n > = {\n contentType:\n metadata.contentType ||\n 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<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n >\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(\n content,\n fullMetadata.contentType\n );\n\n const referenceMetadata: Pick<\n ContentMetadata,\n 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'\n > = {\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: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\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(\n referenceId: ReferenceId\n ): 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: [\n 'Check the reference ID format',\n 'Ensure the reference ID is complete',\n ],\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: [\n 'Verify the reference ID',\n 'Check if the content has expired',\n 'Request fresh content',\n ],\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: [\n 'Request fresh content',\n 'Use alternative content source',\n ],\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:\n storedContent.state === 'expired' ? 'expired' : 'corrupted',\n suggestedActions: [\n 'Request fresh content',\n 'Check reference validity',\n ],\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: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\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(\n this.referenceStats.performanceMetrics.creationTimes\n ),\n averageResolutionTimeMs: this.calculateAverage(\n this.referenceStats.performanceMetrics.resolutionTimes\n ),\n averageCleanupTimeMs: this.calculateAverage(\n this.referenceStats.performanceMetrics.cleanupTimes\n ),\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 =\n 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(\n aContent.metadata.source\n ).priority;\n const bPriority = this.getCleanupPolicy(\n bContent.metadata.source\n ).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(\n `Failed to cleanup ${referenceId}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\n }\n }\n\n if (this.contentStore.size > this.referenceConfig.maxReferences) {\n const sortedByAge = Array.from(this.contentStore.entries()).sort(\n ([, a], [, b]) =>\n a.metadata.lastAccessedAt.getTime() -\n b.metadata.lastAccessedAt.getTime()\n );\n\n const excessCount =\n 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(\n `Failed to cleanup excess reference ${referenceId}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\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: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`;\n errors.push(errorMessage);\n\n return { cleanedUp, errors };\n }\n }\n\n /**\n * Get reference configuration for debugging\n */\n getReferenceConfig(): ContentReferenceConfig {\n return { ...this.referenceConfig };\n }\n\n private async enforceReferenceStorageLimits(): Promise<void> {\n if (this.contentStore.size >= this.referenceConfig.maxReferences) {\n await this.performCleanup();\n }\n\n if (\n this.referenceStats.totalStorageBytes >=\n this.referenceConfig.maxTotalStorageBytes\n ) {\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): { maxAgeMs: number; priority: number } {\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(\n 'utf8',\n 0,\n Math.min(content.length, 1000)\n );\n if (contentStr.startsWith('{') || contentStr.startsWith('[')) return 'json';\n if (contentStr.includes('<html>') || contentStr.includes('<!DOCTYPE'))\n return 'html';\n if (contentStr.includes('#') && contentStr.includes('\\n'))\n return 'markdown';\n\n return 'text';\n }\n\n private createContentPreview(\n content: Buffer,\n contentType: ContentType\n ): string {\n const maxLength = 200;\n let preview = content.toString(\n 'utf8',\n 0,\n Math.min(content.length, maxLength * 2)\n );\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 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 =\n this.referenceStats.totalStorageBytes /\n this.referenceStats.activeReferences;\n }\n\n this.referenceStats.storageUtilization =\n (this.referenceStats.totalStorageBytes /\n this.referenceConfig.maxTotalStorageBytes) *\n 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 /**\n * Check if content is an image file based on MIME type or filename\n */\n private isImageContent(mimeType?: string, fileName?: string): boolean {\n if (mimeType && mimeType.startsWith('image/')) {\n return true;\n }\n\n if (fileName) {\n const lowerFileName = fileName.toLowerCase();\n const imageExtensions = [\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.bmp',\n '.webp',\n '.svg',\n '.tiff',\n '.ico',\n ];\n return imageExtensions.some((ext) => lowerFileName.endsWith(ext));\n }\n\n return false;\n }\n\n private recordPerformanceMetric(\n type: 'creation' | 'resolution' | 'cleanup',\n timeMs: number\n ): 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 {}\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}\n"],"names":[],"mappings":";;AAuFO,MAAM,kBAAN,MAAM,gBAAgD;AAAA,EAkB3D,YACE,aAAqB,gBAAe,qBACpC,iBACA;AApBF,SAAQ,W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AAQ,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,QAAQ;AAAA,MAAC;AAAA,IACX,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;AAj5BE,gBAAuB,sBAAsB;AAhBxC,IAAM,iBAAN;"}
1
+ {"version":3,"file":"index21.js","sources":["../../src/memory/content-storage.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport { ReferenceIdGenerator } from './reference-id-generator';\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 = {\n ...DEFAULT_CONTENT_REFERENCE_CONFIG,\n ...referenceConfig,\n };\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.slice(startIndex).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 { caseSensitive = false, limit, useRegex = false } = 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 {\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(\n (stored) => 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 =\n 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(): { maxStorage: number; currentUsage: number; utilizationPercentage: number } {\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(): Array<{ content: string; type: string; storedAt: string; id: string }> {\n return this.messages.map((stored) => ({\n content: typeof stored.message.content === 'string' \n ? stored.message.content \n : JSON.stringify(stored.message.content),\n type: stored.message._getType(),\n storedAt: stored.storedAt.toISOString(),\n id: stored.id,\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)\n ? content.length\n : 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 * Special case: Image files are ALWAYS stored as references regardless of size\n * because they need special handling for inscription tools\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)\n ? content\n : Buffer.from(content, 'utf8');\n\n const isImageFile = this.isImageContent(\n metadata.mimeType,\n metadata.fileName\n );\n\n if (!isImageFile && !this.shouldUseReference(buffer)) {\n return null;\n }\n\n const storeMetadata: Omit<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n > = {\n contentType:\n metadata.contentType ||\n 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<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n >\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(\n content,\n fullMetadata.contentType\n );\n\n const referenceMetadata: Pick<\n ContentMetadata,\n 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'\n > = {\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: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\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(\n referenceId: ReferenceId\n ): 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: [\n 'Check the reference ID format',\n 'Ensure the reference ID is complete',\n ],\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: [\n 'Verify the reference ID',\n 'Check if the content has expired',\n 'Request fresh content',\n ],\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: [\n 'Request fresh content',\n 'Use alternative content source',\n ],\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:\n storedContent.state === 'expired' ? 'expired' : 'corrupted',\n suggestedActions: [\n 'Request fresh content',\n 'Check reference validity',\n ],\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: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`,\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(\n this.referenceStats.performanceMetrics.creationTimes\n ),\n averageResolutionTimeMs: this.calculateAverage(\n this.referenceStats.performanceMetrics.resolutionTimes\n ),\n averageCleanupTimeMs: this.calculateAverage(\n this.referenceStats.performanceMetrics.cleanupTimes\n ),\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 =\n 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(\n aContent.metadata.source\n ).priority;\n const bPriority = this.getCleanupPolicy(\n bContent.metadata.source\n ).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(\n `Failed to cleanup ${referenceId}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\n }\n }\n\n if (this.contentStore.size > this.referenceConfig.maxReferences) {\n const sortedByAge = Array.from(this.contentStore.entries()).sort(\n ([, a], [, b]) =>\n a.metadata.lastAccessedAt.getTime() -\n b.metadata.lastAccessedAt.getTime()\n );\n\n const excessCount =\n 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(\n `Failed to cleanup excess reference ${referenceId}: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`\n );\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: ${\n error instanceof Error ? error.message : 'Unknown error'\n }`;\n errors.push(errorMessage);\n\n return { cleanedUp, errors };\n }\n }\n\n /**\n * Get reference configuration for debugging\n */\n getReferenceConfig(): ContentReferenceConfig {\n return { ...this.referenceConfig };\n }\n\n private async enforceReferenceStorageLimits(): Promise<void> {\n if (this.contentStore.size >= this.referenceConfig.maxReferences) {\n await this.performCleanup();\n }\n\n if (\n this.referenceStats.totalStorageBytes >=\n this.referenceConfig.maxTotalStorageBytes\n ) {\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): { maxAgeMs: number; priority: number } {\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(\n 'utf8',\n 0,\n Math.min(content.length, 1000)\n );\n if (contentStr.startsWith('{') || contentStr.startsWith('[')) return 'json';\n if (contentStr.includes('<html>') || contentStr.includes('<!DOCTYPE'))\n return 'html';\n if (contentStr.includes('#') && contentStr.includes('\\n'))\n return 'markdown';\n\n return 'text';\n }\n\n private createContentPreview(\n content: Buffer,\n contentType: ContentType\n ): string {\n const maxLength = 200;\n let preview = content.toString(\n 'utf8',\n 0,\n Math.min(content.length, maxLength * 2)\n );\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 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 =\n this.referenceStats.totalStorageBytes /\n this.referenceStats.activeReferences;\n }\n\n this.referenceStats.storageUtilization =\n (this.referenceStats.totalStorageBytes /\n this.referenceConfig.maxTotalStorageBytes) *\n 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 /**\n * Check if content is an image file based on MIME type or filename\n */\n private isImageContent(mimeType?: string, fileName?: string): boolean {\n if (mimeType && mimeType.startsWith('image/')) {\n return true;\n }\n\n if (fileName) {\n const lowerFileName = fileName.toLowerCase();\n const imageExtensions = [\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.bmp',\n '.webp',\n '.svg',\n '.tiff',\n '.ico',\n ];\n return imageExtensions.some((ext) => lowerFileName.endsWith(ext));\n }\n\n return false;\n }\n\n private recordPerformanceMetric(\n type: 'creation' | 'resolution' | 'cleanup',\n timeMs: number\n ): 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 {}\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}\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,kBA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,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,QAAQ;AAAA,MAAC;AAAA,IACX,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;AAn5BE,gBAAuB,sBAAsB;AAhBxC,IAAM,iBAAN;"}
@@ -1,6 +1,6 @@
1
1
  import { ChatOpenAI } from "@langchain/openai";
2
2
  import { Logger } from "@hashgraphonline/standards-sdk";
3
- import { ENTITY_PATTERNS } from "./index37.js";
3
+ import { ENTITY_PATTERNS } from "./index38.js";
4
4
  import "hedera-agent-kit";
5
5
  import "@hashgraphonline/standards-agent-kit";
6
6
  import "./index34.js";
@@ -78,6 +78,10 @@ class FormatConverterRegistry {
78
78
  async detectFormat(entity, context) {
79
79
  const networkType = context.networkType || "testnet";
80
80
  const mirrorNode = new HederaMirrorNode(networkType, this.logger);
81
+ mirrorNode.configureRetry({
82
+ maxRetries: 3,
83
+ maxDelayMs: 1e3
84
+ });
81
85
  const checks = await Promise.allSettled([
82
86
  mirrorNode.getAccountBalance(entity).then((result) => result !== null ? EntityFormat.ACCOUNT_ID : null).catch(() => null),
83
87
  mirrorNode.getTokenInfo(entity).then((result) => result !== null ? EntityFormat.TOKEN_ID : null).catch(() => null),
@@ -1 +1 @@
1
- {"version":3,"file":"index25.js","sources":["../../src/services/formatters/format-converter-registry.ts"],"sourcesContent":["import { EntityFormat, FormatConverter, ConversionContext } from './types';\nimport {\n HederaMirrorNode,\n Logger,\n NetworkType,\n} from '@hashgraphonline/standards-sdk';\n\ninterface CacheEntry {\n format: EntityFormat;\n timestamp: number;\n ttl: number;\n}\n\n/**\n * Registry for format converters that handles entity transformation\n */\nexport class FormatConverterRegistry {\n private converters = new Map<string, FormatConverter<unknown, unknown>>();\n private entityTypeCache = new Map<string, CacheEntry>();\n private logger = new Logger({ module: 'FormatConverterRegistry' });\n private defaultCacheTTL = 5 * 60 * 1000;\n\n /**\n * Register a format converter\n */\n register<TSource, TTarget>(\n converter: FormatConverter<TSource, TTarget>\n ): void {\n const key = `${converter.sourceFormat}→${converter.targetFormat}`;\n this.converters.set(key, converter as FormatConverter<unknown, unknown>);\n }\n\n /**\n * Find a converter for the given source and target formats\n */\n findConverter(\n source: EntityFormat,\n target: EntityFormat\n ): FormatConverter<unknown, unknown> | null {\n const key = `${source}→${target}`;\n return this.converters.get(key) || null;\n }\n\n /**\n * Convert an entity to the target format\n */\n async convertEntity(\n entity: string,\n target: EntityFormat,\n context: ConversionContext\n ): Promise<string> {\n const sourceFormat = await this.detectFormatWithFallback(entity, context);\n if (sourceFormat === target) {\n return entity;\n }\n\n const converter = this.findConverter(sourceFormat, target);\n if (!converter) {\n throw new Error(`No converter found for ${sourceFormat} → ${target}`);\n }\n\n if (!converter.canConvert(entity, context)) {\n throw new Error(`Converter cannot handle entity: ${entity}`);\n }\n\n const result = await converter.convert(entity, context);\n return result as string;\n }\n\n /**\n * Detect the format of an entity string with API-based verification and fallback\n */\n private async detectFormatWithFallback(\n entity: string,\n context?: ConversionContext\n ): Promise<EntityFormat> {\n if (entity.startsWith('hcs://')) {\n return EntityFormat.HRL;\n }\n\n if (/^0\\.0\\.\\d+$/.test(entity)) {\n const cached = this.getCachedFormat(entity);\n if (cached) {\n return cached;\n }\n\n try {\n const detected = await this.detectFormat(entity, context || {});\n if (detected !== EntityFormat.ANY) {\n this.setCachedFormat(entity, detected);\n return detected;\n }\n } catch (error) {\n this.logger.warn(\n `Entity detection failed for ${entity}, using fallback: ${\n (error as Error).message\n }`\n );\n }\n\n return EntityFormat.ANY;\n }\n\n return EntityFormat.ANY;\n }\n\n /**\n * Public helper: detect entity format (ACCOUNT_ID, TOKEN_ID, TOPIC_ID, HRL, or ANY)\n */\n async detectEntityFormat(\n entity: string,\n context?: ConversionContext\n ): Promise<EntityFormat> {\n return this.detectFormatWithFallback(entity, context);\n }\n\n /**\n * Detect entity format via Hedera Mirror Node API calls\n */\n private async detectFormat(\n entity: string,\n context: ConversionContext\n ): Promise<EntityFormat> {\n const networkType = (context.networkType as NetworkType) || 'testnet';\n const mirrorNode = new HederaMirrorNode(networkType, this.logger);\n\n const checks = await Promise.allSettled([\n mirrorNode\n .getAccountBalance(entity)\n .then((result) => (result !== null ? EntityFormat.ACCOUNT_ID : null))\n .catch(() => null),\n\n mirrorNode\n .getTokenInfo(entity)\n .then((result) => (result !== null ? EntityFormat.TOKEN_ID : null))\n .catch(() => null),\n\n mirrorNode\n .getTopicInfo(entity)\n .then((result) => (result !== null ? EntityFormat.TOPIC_ID : null))\n .catch(() => null),\n\n mirrorNode\n .getContract(entity)\n .then((result) => (result !== null ? EntityFormat.CONTRACT_ID : null))\n .catch(() => null),\n ]);\n\n const successful = checks.find(\n (result) => result.status === 'fulfilled' && result.value !== null\n );\n\n return successful && successful.status === 'fulfilled'\n ? (successful.value as EntityFormat)\n : EntityFormat.ANY;\n }\n\n /**\n * Get cached entity format if valid\n */\n private getCachedFormat(entity: string): EntityFormat | null {\n const entry = this.entityTypeCache.get(entity);\n if (!entry || this.isCacheExpired(entry)) {\n this.entityTypeCache.delete(entity);\n return null;\n }\n return entry.format;\n }\n\n /**\n * Set cached entity format\n */\n private setCachedFormat(entity: string, format: EntityFormat): void {\n this.entityTypeCache.set(entity, {\n format,\n timestamp: Date.now(),\n ttl: this.defaultCacheTTL,\n });\n }\n\n /**\n * Check if cache entry is expired\n */\n private isCacheExpired(entry: CacheEntry): boolean {\n return Date.now() - entry.timestamp > entry.ttl;\n }\n\n /**\n * Get all registered converters\n */\n getRegisteredConverters(): Array<{\n source: EntityFormat;\n target: EntityFormat;\n }> {\n return Array.from(this.converters.keys()).map((key) => {\n const [source, target] = key.split('→');\n return {\n source: source as EntityFormat,\n target: target as EntityFormat,\n };\n });\n }\n\n /**\n * Check if a converter exists for the given formats\n */\n hasConverter(source: EntityFormat, target: EntityFormat): boolean {\n return this.findConverter(source, target) !== null;\n }\n\n /**\n * Clear all registered converters\n */\n clear(): void {\n this.converters.clear();\n }\n\n /**\n * Clear entity type cache\n */\n clearCache(): void {\n this.entityTypeCache.clear();\n }\n}\n"],"names":[],"mappings":";;AAgBO,MAAM,wBAAwB;AAAA,EAA9B,cAAA;AACL,SAAQ,iCAAiB,IAAA;AACzB,SAAQ,sCAAsB,IAAA;AAC9B,SAAQ,SAAS,IAAI,OAAO,EAAE,QAAQ,2BAA2B;AACjE,SAAQ,kBAAkB,IAAI,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAKnC,SACE,WACM;AACN,UAAM,MAAM,GAAG,UAAU,YAAY,IAAI,UAAU,YAAY;AAC/D,SAAK,WAAW,IAAI,KAAK,SAA8C;AAAA,EACzE;AAAA;AAAA;AAAA;AAAA,EAKA,cACE,QACA,QAC0C;AAC1C,UAAM,MAAM,GAAG,MAAM,IAAI,MAAM;AAC/B,WAAO,KAAK,WAAW,IAAI,GAAG,KAAK;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cACJ,QACA,QACA,SACiB;AACjB,UAAM,eAAe,MAAM,KAAK,y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AACrD,YAAM,CAAC,QAAQ,MAAM,IAAI,IAAI,MAAM,GAAG;AACtC,aAAO;AAAA,QACL;AAAA,QACA;AAAA,MAAA;AAAA,IAEJ,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,QAAsB,QAA+B;AAChE,WAAO,KAAK,cAAc,QAAQ,MAAM,MAAM;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,WAAW,MAAA;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKA,aAAmB;AACjB,SAAK,gBAAgB,MAAA;AAAA,EACvB;AACF;"}
1
+ {"version":3,"file":"index25.js","sources":["../../src/services/formatters/format-converter-registry.ts"],"sourcesContent":["import { EntityFormat, FormatConverter, ConversionContext } from './types';\nimport {\n HederaMirrorNode,\n Logger,\n NetworkType,\n} from '@hashgraphonline/standards-sdk';\n\ninterface CacheEntry {\n format: EntityFormat;\n timestamp: number;\n ttl: number;\n}\n\n/**\n * Registry for format converters that handles entity transformation\n */\nexport class FormatConverterRegistry {\n private converters = new Map<string, FormatConverter<unknown, unknown>>();\n private entityTypeCache = new Map<string, CacheEntry>();\n private logger = new Logger({ module: 'FormatConverterRegistry' });\n private defaultCacheTTL = 5 * 60 * 1000;\n\n /**\n * Register a format converter\n */\n register<TSource, TTarget>(\n converter: FormatConverter<TSource, TTarget>\n ): void {\n const key = `${converter.sourceFormat}→${converter.targetFormat}`;\n this.converters.set(key, converter as FormatConverter<unknown, unknown>);\n }\n\n /**\n * Find a converter for the given source and target formats\n */\n findConverter(\n source: EntityFormat,\n target: EntityFormat\n ): FormatConverter<unknown, unknown> | null {\n const key = `${source}→${target}`;\n return this.converters.get(key) || null;\n }\n\n /**\n * Convert an entity to the target format\n */\n async convertEntity(\n entity: string,\n target: EntityFormat,\n context: ConversionContext\n ): Promise<string> {\n const sourceFormat = await this.detectFormatWithFallback(entity, context);\n if (sourceFormat === target) {\n return entity;\n }\n\n const converter = this.findConverter(sourceFormat, target);\n if (!converter) {\n throw new Error(`No converter found for ${sourceFormat} → ${target}`);\n }\n\n if (!converter.canConvert(entity, context)) {\n throw new Error(`Converter cannot handle entity: ${entity}`);\n }\n\n const result = await converter.convert(entity, context);\n return result as string;\n }\n\n /**\n * Detect the format of an entity string with API-based verification and fallback\n */\n private async detectFormatWithFallback(\n entity: string,\n context?: ConversionContext\n ): Promise<EntityFormat> {\n if (entity.startsWith('hcs://')) {\n return EntityFormat.HRL;\n }\n\n if (/^0\\.0\\.\\d+$/.test(entity)) {\n const cached = this.getCachedFormat(entity);\n if (cached) {\n return cached;\n }\n\n try {\n const detected = await this.detectFormat(entity, context || {});\n if (detected !== EntityFormat.ANY) {\n this.setCachedFormat(entity, detected);\n return detected;\n }\n } catch (error) {\n this.logger.warn(\n `Entity detection failed for ${entity}, using fallback: ${\n (error as Error).message\n }`\n );\n }\n\n return EntityFormat.ANY;\n }\n\n return EntityFormat.ANY;\n }\n\n /**\n * Public helper: detect entity format (ACCOUNT_ID, TOKEN_ID, TOPIC_ID, HRL, or ANY)\n */\n async detectEntityFormat(\n entity: string,\n context?: ConversionContext\n ): Promise<EntityFormat> {\n return this.detectFormatWithFallback(entity, context);\n }\n\n /**\n * Detect entity format via Hedera Mirror Node API calls\n */\n private async detectFormat(\n entity: string,\n context: ConversionContext\n ): Promise<EntityFormat> {\n const networkType = (context.networkType as NetworkType) || 'testnet';\n const mirrorNode = new HederaMirrorNode(networkType, this.logger);\n\n mirrorNode.configureRetry({\n maxRetries: 3,\n maxDelayMs: 1000,\n });\n\n const checks = await Promise.allSettled([\n mirrorNode\n .getAccountBalance(entity)\n .then((result) => (result !== null ? EntityFormat.ACCOUNT_ID : null))\n .catch(() => null),\n\n mirrorNode\n .getTokenInfo(entity)\n .then((result) => (result !== null ? EntityFormat.TOKEN_ID : null))\n .catch(() => null),\n\n mirrorNode\n .getTopicInfo(entity)\n .then((result) => (result !== null ? EntityFormat.TOPIC_ID : null))\n .catch(() => null),\n\n mirrorNode\n .getContract(entity)\n .then((result) => (result !== null ? EntityFormat.CONTRACT_ID : null))\n .catch(() => null),\n ]);\n\n const successful = checks.find(\n (result) => result.status === 'fulfilled' && result.value !== null\n );\n\n return successful && successful.status === 'fulfilled'\n ? (successful.value as EntityFormat)\n : EntityFormat.ANY;\n }\n\n /**\n * Get cached entity format if valid\n */\n private getCachedFormat(entity: string): EntityFormat | null {\n const entry = this.entityTypeCache.get(entity);\n if (!entry || this.isCacheExpired(entry)) {\n this.entityTypeCache.delete(entity);\n return null;\n }\n return entry.format;\n }\n\n /**\n * Set cached entity format\n */\n private setCachedFormat(entity: string, format: EntityFormat): void {\n this.entityTypeCache.set(entity, {\n format,\n timestamp: Date.now(),\n ttl: this.defaultCacheTTL,\n });\n }\n\n /**\n * Check if cache entry is expired\n */\n private isCacheExpired(entry: CacheEntry): boolean {\n return Date.now() - entry.timestamp > entry.ttl;\n }\n\n /**\n * Get all registered converters\n */\n getRegisteredConverters(): Array<{\n source: EntityFormat;\n target: EntityFormat;\n }> {\n return Array.from(this.converters.keys()).map((key) => {\n const [source, target] = key.split('→');\n return {\n source: source as EntityFormat,\n target: target as EntityFormat,\n };\n });\n }\n\n /**\n * Check if a converter exists for the given formats\n */\n hasConverter(source: EntityFormat, target: EntityFormat): boolean {\n return this.findConverter(source, target) !== null;\n }\n\n /**\n * Clear all registered converters\n */\n clear(): void {\n this.converters.clear();\n }\n\n /**\n * Clear entity type cache\n */\n clearCache(): void {\n this.entityTypeCache.clear();\n }\n}\n"],"names":[],"mappings":";;AAgBO,MAAM,wBAAwB;AAAA,EAA9B,cAAA;AACL,SAAQ,iCAAiB,IAAA;AACzB,SAAQ,sCAAsB,IAAA;AAC9B,SAAQ,SAAS,IAAI,OAAO,EAAE,QAAQ,2BAA2B;AACjE,SAAQ,kBAAkB,IAAI,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAKnC,SACE,WACM;AACN,UAAM,MAAM,GAAG,UAAU,YAAY,IAAI,UAAU,YA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AAgB,QAAgB,QAA4B;AAClE,SAAK,gBAAgB,IAAI,QAAQ;AAAA,MAC/B;AAAA,MACA,WAAW,KAAK,IAAA;AAAA,MAChB,KAAK,KAAK;AAAA,IAAA,CACX;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKQ,eAAe,OAA4B;AACjD,WAAO,KAAK,IAAA,IAAQ,MAAM,YAAY,MAAM;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,0BAGG;AACD,WAAO,MAAM,KAAK,KAAK,WAAW,MAAM,EAAE,IAAI,CAAC,QAAQ;AACrD,YAAM,CAAC,QAAQ,MAAM,IAAI,IAAI,MAAM,GAAG;AACtC,aAAO;AAAA,QACL;AAAA,QACA;AAAA,MAAA;AAAA,IAEJ,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,QAAsB,QAA+B;AAChE,WAAO,KAAK,cAAc,QAAQ,MAAM,MAAM;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,WAAW,MAAA;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKA,aAAmB;AACjB,SAAK,gBAAgB,MAAA;AAAA,EACvB;AACF;"}
@@ -9,7 +9,7 @@ import { convertMCPToolToLangChain } from "./index17.js";
9
9
  import { SmartMemoryManager } from "./index18.js";
10
10
  import { ResponseFormatter } from "./index33.js";
11
11
  import { ERROR_MESSAGES } from "./index40.js";
12
- import "./index37.js";
12
+ import "./index38.js";
13
13
  import { SystemMessage, AIMessage, HumanMessage } from "@langchain/core/messages";
14
14
  import { ToolRegistry } from "./index41.js";
15
15
  import { ExecutionPipeline } from "./index42.js";
@@ -59,7 +59,11 @@ class AirdropToolWrapper extends StructuredTool {
59
59
  return Math.floor(amount * Math.pow(10, decimals));
60
60
  }
61
61
  async getTokenInfo(tokenId) {
62
- return await this.queryTokenInfo(tokenId);
62
+ try {
63
+ return await this.queryTokenInfo(tokenId);
64
+ } catch (error) {
65
+ throw error;
66
+ }
63
67
  }
64
68
  async queryTokenInfo(tokenId) {
65
69
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"index35.js","sources":["../../src/plugins/hbar/AirdropToolWrapper.ts"],"sourcesContent":["import { StructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { HederaAgentKit } from 'hedera-agent-kit';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\ninterface TokenInfo {\n decimals: number;\n [key: string]: unknown;\n}\n\ninterface ToolWithCall {\n _call(input: unknown): Promise<string>;\n}\n\ninterface AgentKitWithMirrorNode {\n mirrorNode?: {\n getTokenInfo(tokenId: string): Promise<TokenInfo>;\n };\n network: string;\n}\n\nexport class AirdropToolWrapper extends StructuredTool {\n name = 'hedera-hts-airdrop-token';\n description =\n 'Airdrops fungible tokens to multiple recipients. Automatically converts human-readable amounts to smallest units based on token decimals.';\n\n schema = z.object({\n tokenId: z\n .string()\n .describe('The ID of the fungible token to airdrop (e.g., \"0.0.yyyy\").'),\n recipients: z\n .array(\n z.object({\n accountId: z\n .string()\n .describe('Recipient account ID (e.g., \"0.0.xxxx\").'),\n amount: z\n .union([z.number(), z.string()])\n .describe(\n 'Amount in human-readable format (e.g., \"10\" for 10 tokens).'\n ),\n })\n )\n .min(1)\n .describe('Array of recipient objects, each with accountId and amount.'),\n memo: z.string().optional().describe('Optional. Memo for the transaction.'),\n });\n\n private originalTool: StructuredTool & ToolWithCall;\n private agentKit: HederaAgentKit & AgentKitWithMirrorNode;\n private logger: Logger;\n\n constructor(originalTool: StructuredTool, agentKit: unknown) {\n super();\n this.originalTool = originalTool as StructuredTool & ToolWithCall;\n this.agentKit = agentKit as HederaAgentKit & AgentKitWithMirrorNode;\n this.logger = new Logger({ module: 'AirdropToolWrapper' });\n }\n\n async _call(input: z.infer<typeof this.schema>): Promise<string> {\n try {\n this.logger.info(\n `Processing airdrop request for token ${input.tokenId} with ${input.recipients.length} recipients`\n );\n\n const tokenInfo = await this.getTokenInfo(input.tokenId);\n const decimals = tokenInfo.decimals || 0;\n\n this.logger.info(`Token ${input.tokenId} has ${decimals} decimal places`);\n\n const convertedRecipients = input.recipients.map((recipient) => {\n const humanAmount =\n typeof recipient.amount === 'string'\n ? parseFloat(recipient.amount)\n : recipient.amount;\n const smallestUnitAmount = this.convertToSmallestUnits(\n humanAmount,\n decimals\n );\n\n this.logger.info(\n `Converting amount for ${recipient.accountId}: ${humanAmount} tokens → ${smallestUnitAmount} smallest units`\n );\n\n return {\n ...recipient,\n amount: smallestUnitAmount.toString(),\n };\n });\n\n const convertedInput = {\n ...input,\n recipients: convertedRecipients,\n };\n\n this.logger.info(`Calling original airdrop tool with converted amounts`);\n return await this.originalTool._call(convertedInput);\n } catch (error) {\n this.logger.error('Error in airdrop tool wrapper:', error);\n throw error;\n }\n }\n\n private convertToSmallestUnits(amount: number, decimals: number): number {\n return Math.floor(amount * Math.pow(10, decimals));\n }\n\n private async getTokenInfo(tokenId: string): Promise<TokenInfo> {\n return await this.queryTokenInfo(tokenId);\n }\n\n private async queryTokenInfo(tokenId: string): Promise<TokenInfo> {\n try {\n this.logger.info('Querying token info using mirror node');\n const mirrorNode = this.agentKit.mirrorNode;\n if (!mirrorNode) {\n this.logger.info(\n 'MirrorNode not found in agentKit, attempting to access via fetch'\n );\n const network = this.agentKit.network || 'testnet';\n const mirrorNodeUrl =\n network === 'mainnet'\n ? 'https://mainnet.mirrornode.hedera.com'\n : 'https://testnet.mirrornode.hedera.com';\n\n const response = await fetch(\n `${mirrorNodeUrl}/api/v1/tokens/${tokenId}`\n );\n if (response.ok) {\n const tokenData = (await response.json()) as Record<string, unknown>;\n const decimals = parseInt(String(tokenData.decimals || '0'));\n this.logger.info(\n `Token ${tokenId} found with ${decimals} decimals via API`\n );\n return { ...tokenData, decimals };\n }\n } else {\n const tokenData = await mirrorNode.getTokenInfo(tokenId);\n\n if (tokenData && typeof tokenData.decimals !== 'undefined') {\n const decimals = parseInt(tokenData.decimals.toString()) || 0;\n this.logger.info(`Token ${tokenId} found with ${decimals} decimals`);\n return { ...tokenData, decimals };\n }\n }\n\n throw new Error(`Token data not found or missing decimals field`);\n } catch (error) {\n this.logger.warn(`Failed to query token info for ${tokenId}:`, error);\n\n this.logger.info(\n 'Falling back to assumed 0 decimal places (smallest units)'\n );\n return { decimals: 0 };\n }\n }\n}\n"],"names":[],"mappings":";;;AAqBO,MAAM,2BAA2B,eAAe;AAAA,EA+BrD,YAAY,cAA8B,UAAmB;AAC3D,UAAA;AA/BF,SAAA,OAAO;AACP,SAAA,cACE;AAEF,SAAA,SAAS,EAAE,OAAO;AAAA,MAChB,SAAS,EACN,SACA,SAAS,6DAA6D;AAAA,MACzE,YAAY,EACT;AAAA,QACC,EAAE,OAAO;AAAA,UACP,WAAW,EACR,SACA,SAAS,0CAA0C;AAAA,UACtD,QAAQ,EACL,MAAM,CAAC,EAAE,OAAA,GAAU,EAAE,QAAQ,CAAC,EAC9B;AAAA,YACC;AAAA,UAAA;AAAA,QACF,CACH;AAAA,MAAA,EAEF,IAAI,CAAC,EACL,SAAS,6DAA6D;AAAA,MACzE,MAAM,EAAE,OAAA,EAAS,SAAA,EAAW,SAAS,qCAAqC;AAAA,IAAA,CAC3E;AAQC,SAAK,eAAe;AACpB,SAAK,WAAW;AAChB,SAAK,SAAS,IAAI,OAAO,EAAE,QAAQ,sBAAsB;AAAA,EAC3D;AAAA,EAEA,MAAM,MAAM,OAAqD;AAC/D,QAAI;AACF,WAAK,OAAO;AAAA,QACV,wCAAwC,MAAM,OAAO,SAAS,MAAM,WAAW,MAAM;AAAA,MAAA;AAGvF,YAAM,YAAY,MAAM,KAAK,aAAa,MAAM,OAAO;AACvD,YAAM,WAAW,UAAU,YAAY;AAEvC,WAAK,OAAO,KAAK,SAAS,MAAM,OAAO,QAAQ,QAAQ,iBAAiB;AAExE,YAAM,sBAAsB,MAAM,WAAW,IAAI,CAAC,cAAc;AAC9D,cAAM,cACJ,OAAO,UAAU,WAAW,WACxB,WAAW,UAAU,MAAM,IAC3B,UAA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,OAAO;AACL,cAAM,YAAY,MAAM,WAAW,aAAa,OAAO;AAEvD,YAAI,aAAa,OAAO,UAAU,aAAa,aAAa;AAC1D,gBAAM,WAAW,SAAS,UAAU,SAAS,SAAA,CAAU,KAAK;AAC5D,eAAK,OAAO,KAAK,SAAS,OAAO,eAAe,QAAQ,WAAW;AACnE,iBAAO,EAAE,GAAG,WAAW,SAAA;AAAA,QACzB;AAAA,MACF;AAEA,YAAM,IAAI,MAAM,gDAAgD;AAAA,IAClE,SAAS,OAAO;AACd,WAAK,OAAO,KAAK,kCAAkC,OAAO,KAAK,KAAK;AAEpE,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAEF,aAAO,EAAE,UAAU,EAAA;AAAA,IACrB;AAAA,EACF;AACF;"}
1
+ {"version":3,"file":"index35.js","sources":["../../src/plugins/hbar/AirdropToolWrapper.ts"],"sourcesContent":["import { StructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { HederaAgentKit } from 'hedera-agent-kit';\nimport { Logger } from '@hashgraphonline/standards-sdk';\n\ninterface TokenInfo {\n decimals: number;\n [key: string]: unknown;\n}\n\ninterface ToolWithCall {\n _call(input: unknown): Promise<string>;\n}\n\ninterface AgentKitWithMirrorNode {\n mirrorNode?: {\n getTokenInfo(tokenId: string): Promise<TokenInfo>;\n };\n network: string;\n}\n\nexport class AirdropToolWrapper extends StructuredTool {\n name = 'hedera-hts-airdrop-token';\n description =\n 'Airdrops fungible tokens to multiple recipients. Automatically converts human-readable amounts to smallest units based on token decimals.';\n\n schema = z.object({\n tokenId: z\n .string()\n .describe('The ID of the fungible token to airdrop (e.g., \"0.0.yyyy\").'),\n recipients: z\n .array(\n z.object({\n accountId: z\n .string()\n .describe('Recipient account ID (e.g., \"0.0.xxxx\").'),\n amount: z\n .union([z.number(), z.string()])\n .describe(\n 'Amount in human-readable format (e.g., \"10\" for 10 tokens).'\n ),\n })\n )\n .min(1)\n .describe('Array of recipient objects, each with accountId and amount.'),\n memo: z.string().optional().describe('Optional. Memo for the transaction.'),\n });\n\n private originalTool: StructuredTool & ToolWithCall;\n private agentKit: HederaAgentKit & AgentKitWithMirrorNode;\n private logger: Logger;\n\n constructor(originalTool: StructuredTool, agentKit: unknown) {\n super();\n this.originalTool = originalTool as StructuredTool & ToolWithCall;\n this.agentKit = agentKit as HederaAgentKit & AgentKitWithMirrorNode;\n this.logger = new Logger({ module: 'AirdropToolWrapper' });\n }\n\n async _call(input: z.infer<typeof this.schema>): Promise<string> {\n try {\n this.logger.info(\n `Processing airdrop request for token ${input.tokenId} with ${input.recipients.length} recipients`\n );\n\n const tokenInfo = await this.getTokenInfo(input.tokenId);\n const decimals = tokenInfo.decimals || 0;\n\n this.logger.info(`Token ${input.tokenId} has ${decimals} decimal places`);\n\n const convertedRecipients = input.recipients.map((recipient) => {\n const humanAmount =\n typeof recipient.amount === 'string'\n ? parseFloat(recipient.amount)\n : recipient.amount;\n const smallestUnitAmount = this.convertToSmallestUnits(\n humanAmount,\n decimals\n );\n\n this.logger.info(\n `Converting amount for ${recipient.accountId}: ${humanAmount} tokens → ${smallestUnitAmount} smallest units`\n );\n\n return {\n ...recipient,\n amount: smallestUnitAmount.toString(),\n };\n });\n\n const convertedInput = {\n ...input,\n recipients: convertedRecipients,\n };\n\n this.logger.info(`Calling original airdrop tool with converted amounts`);\n return await this.originalTool._call(convertedInput);\n } catch (error) {\n this.logger.error('Error in airdrop tool wrapper:', error);\n throw error;\n }\n }\n\n private convertToSmallestUnits(amount: number, decimals: number): number {\n return Math.floor(amount * Math.pow(10, decimals));\n }\n\n private async getTokenInfo(tokenId: string): Promise<TokenInfo> {\n try {\n return await this.queryTokenInfo(tokenId);\n } catch (error) {\n throw error;\n }\n }\n\n private async queryTokenInfo(tokenId: string): Promise<TokenInfo> {\n try {\n this.logger.info('Querying token info using mirror node');\n const mirrorNode = this.agentKit.mirrorNode;\n if (!mirrorNode) {\n this.logger.info(\n 'MirrorNode not found in agentKit, attempting to access via fetch'\n );\n const network = this.agentKit.network || 'testnet';\n const mirrorNodeUrl =\n network === 'mainnet'\n ? 'https://mainnet.mirrornode.hedera.com'\n : 'https://testnet.mirrornode.hedera.com';\n\n const response = await fetch(\n `${mirrorNodeUrl}/api/v1/tokens/${tokenId}`\n );\n if (response.ok) {\n const tokenData = (await response.json()) as Record<string, unknown>;\n const decimals = parseInt(String(tokenData.decimals || '0'));\n this.logger.info(\n `Token ${tokenId} found with ${decimals} decimals via API`\n );\n return { ...tokenData, decimals };\n }\n } else {\n const tokenData = await mirrorNode.getTokenInfo(tokenId);\n\n if (tokenData && typeof tokenData.decimals !== 'undefined') {\n const decimals = parseInt(tokenData.decimals.toString()) || 0;\n this.logger.info(`Token ${tokenId} found with ${decimals} decimals`);\n return { ...tokenData, decimals };\n }\n }\n\n throw new Error(`Token data not found or missing decimals field`);\n } catch (error) {\n this.logger.warn(`Failed to query token info for ${tokenId}:`, error);\n\n this.logger.info(\n 'Falling back to assumed 0 decimal places (smallest units)'\n );\n return { decimals: 0 };\n }\n }\n}\n"],"names":[],"mappings":";;;AAqBO,MAAM,2BAA2B,eAAe;AAAA,EA+BrD,YAAY,cAA8B,UAAmB;AAC3D,UAAA;AA/BF,SAAA,OAAO;AACP,SAAA,cACE;AAEF,SAAA,SAAS,EAAE,OAAO;AAAA,MAChB,SAAS,EACN,SACA,SAAS,6DAA6D;AAAA,MACzE,YAAY,EACT;AAAA,QACC,EAAE,OAAO;AAAA,UACP,WAAW,EACR,SACA,SAAS,0CAA0C;AAAA,UACtD,QAAQ,EACL,MAAM,CAAC,EAAE,OAAA,GAAU,EAAE,QAAQ,CAAC,EAC9B;AAAA,YACC;AAAA,UAAA;AAAA,QACF,CACH;AAAA,MAAA,EAEF,IAAI,CAAC,EACL,SAAS,6DAA6D;AAAA,MACzE,MAAM,EAAE,OAAA,EAAS,SAAA,EAAW,SAAS,qCAAqC;AAAA,IAAA,CAC3E;AAQC,SAAK,eAAe;AACpB,SAAK,WAAW;AAChB,SAAK,SAAS,IAAI,OAA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AuC;AACxD,YAAM,aAAa,KAAK,SAAS;AACjC,UAAI,CAAC,YAAY;AACf,aAAK,OAAO;AAAA,UACV;AAAA,QAAA;AAEF,cAAM,UAAU,KAAK,SAAS,WAAW;AACzC,cAAM,gBACJ,YAAY,YACR,0CACA;AAEN,cAAM,WAAW,MAAM;AAAA,UACrB,GAAG,aAAa,kBAAkB,OAAO;AAAA,QAAA;AAE3C,YAAI,SAAS,IAAI;AACf,gBAAM,YAAa,MAAM,SAAS,KAAA;AAClC,gBAAM,WAAW,SAAS,OAAO,UAAU,YAAY,GAAG,CAAC;AAC3D,eAAK,OAAO;AAAA,YACV,SAAS,OAAO,eAAe,QAAQ;AAAA,UAAA;AAEzC,iBAAO,EAAE,GAAG,WAAW,SAAA;AAAA,QACzB;AAAA,MACF,OAAO;AACL,cAAM,YAAY,MAAM,WAAW,aAAa,OAAO;AAEvD,YAAI,aAAa,OAAO,UAAU,aAAa,aAAa;AAC1D,gBAAM,WAAW,SAAS,UAAU,SAAS,SAAA,CAAU,KAAK;AAC5D,eAAK,OAAO,KAAK,SAAS,OAAO,eAAe,QAAQ,WAAW;AACnE,iBAAO,EAAE,GAAG,WAAW,SAAA;AAAA,QACzB;AAAA,MACF;AAEA,YAAM,IAAI,MAAM,gDAAgD;AAAA,IAClE,SAAS,OAAO;AACd,WAAK,OAAO,KAAK,kCAAkC,OAAO,KAAK,KAAK;AAEpE,WAAK,OAAO;AAAA,QACV;AAAA,MAAA;AAEF,aAAO,EAAE,UAAU,EAAA;AAAA,IACrB;AAAA,EACF;AACF;"}
@@ -1,15 +1,30 @@
1
- import { EntityFormat } from "./index26.js";
2
- const ENTITY_PATTERNS = {
3
- TOPIC_REFERENCE: "the topic",
4
- TOKEN_REFERENCE: "the token"
1
+ const DEFAULT_CONTENT_REFERENCE_CONFIG = {
2
+ sizeThresholdBytes: 10 * 1024,
3
+ maxAgeMs: 60 * 60 * 1e3,
4
+ maxReferences: 100,
5
+ maxTotalStorageBytes: 100 * 1024 * 1024,
6
+ enableAutoCleanup: true,
7
+ cleanupIntervalMs: 5 * 60 * 1e3,
8
+ enablePersistence: false,
9
+ storageBackend: "memory",
10
+ cleanupPolicies: {
11
+ recent: { maxAgeMs: 30 * 60 * 1e3, priority: 1 },
12
+ userContent: { maxAgeMs: 2 * 60 * 60 * 1e3, priority: 2 },
13
+ agentGenerated: { maxAgeMs: 60 * 60 * 1e3, priority: 3 },
14
+ default: { maxAgeMs: 60 * 60 * 1e3, priority: 4 }
15
+ }
5
16
  };
6
- ({
7
- TOPIC: EntityFormat.TOPIC_ID,
8
- TOKEN: EntityFormat.TOKEN_ID,
9
- ACCOUNT: EntityFormat.ACCOUNT_ID,
10
- CONTRACT: EntityFormat.CONTRACT_ID
11
- });
17
+ class ContentReferenceError extends Error {
18
+ constructor(message, type, referenceId, suggestedActions) {
19
+ super(message);
20
+ this.type = type;
21
+ this.referenceId = referenceId;
22
+ this.suggestedActions = suggestedActions;
23
+ this.name = "ContentReferenceError";
24
+ }
25
+ }
12
26
  export {
13
- ENTITY_PATTERNS
27
+ ContentReferenceError,
28
+ DEFAULT_CONTENT_REFERENCE_CONFIG
14
29
  };
15
30
  //# sourceMappingURL=index37.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index37.js","sources":["../../src/constants/entity-references.ts"],"sourcesContent":["/**\n * Common entity reference patterns used across the application\n */\nexport const ENTITY_PATTERNS = {\n TOPIC_REFERENCE: 'the topic',\n TOKEN_REFERENCE: 'the token',\n ACCOUNT_REFERENCE: 'the account',\n TRANSACTION_REFERENCE: 'the transaction',\n CONTRACT_REFERENCE: 'the contract',\n} as const;\n\n/**\n * Entity type identifiers\n */\nimport { EntityFormat } from '../services/formatters/types';\n\nexport const ENTITY_TYPES = {\n TOPIC: EntityFormat.TOPIC_ID,\n TOKEN: EntityFormat.TOKEN_ID,\n ACCOUNT: EntityFormat.ACCOUNT_ID,\n TRANSACTION: 'transaction',\n CONTRACT: EntityFormat.CONTRACT_ID,\n} as const;\n"],"names":[],"mappings":";AAGO,MAAM,kBAAkB;AAAA,EAC7B,iBAAiB;AAAA,EACjB,iBAAiB;AAInB;AAAA,CAO4B;AAAA,EAC1B,OAAO,aAAa;AAAA,EACpB,OAAO,aAAa;AAAA,EACpB,SAAS,aAAa;AAAA,EAEtB,UAAU,aAAa;AACzB;"}
1
+ {"version":3,"file":"index37.js","sources":["../../src/types/content-reference.ts"],"sourcesContent":["/**\n * Content Reference System Types\n *\n * Shared interfaces for the Reference-Based Content System that handles\n * large content storage with unique reference IDs to optimize context window usage.\n */\n\n/**\n * Unique identifier for stored content references\n * Format: Cryptographically secure 32-byte identifier with base64url encoding\n */\nexport type ReferenceId = string;\n\n/**\n * Lifecycle state of a content reference\n */\nexport type ReferenceLifecycleState =\n | 'active'\n | 'expired'\n | 'cleanup_pending'\n | 'invalid';\n\n/**\n * Content types supported by the reference system\n */\nexport type ContentType =\n | 'text'\n | 'json'\n | 'html'\n | 'markdown'\n | 'binary'\n | 'unknown';\n\n/**\n * Sources that created the content reference\n */\nexport type ContentSource =\n | 'mcp_tool'\n | 'user_upload'\n | 'agent_generated'\n | 'system';\n\n/**\n * Metadata associated with stored content\n */\nexport interface ContentMetadata {\n /** Content type classification */\n contentType: ContentType;\n\n /** MIME type of the original content */\n mimeType?: string;\n\n /** Size in bytes of the stored content */\n sizeBytes: number;\n\n /** When the content was originally stored */\n createdAt: Date;\n\n /** Last time the content was accessed via reference resolution */\n lastAccessedAt: Date;\n\n /** Source that created this content reference */\n source: ContentSource;\n\n /** Name of the MCP tool that generated the content (if applicable) */\n mcpToolName?: string;\n\n /** Original filename or suggested name for the content */\n fileName?: string;\n\n /** Number of times this reference has been resolved */\n accessCount: number;\n\n /** Tags for categorization and cleanup policies */\n tags?: string[];\n\n /** Custom metadata from the source */\n customMetadata?: Record<string, unknown>;\n}\n\n/**\n * Core content reference object passed through agent context\n * Designed to be lightweight (<100 tokens) while providing enough\n * information for agent decision-making\n */\nexport interface ContentReference {\n /** Unique identifier for resolving the content */\n referenceId: ReferenceId;\n\n /** Current lifecycle state */\n state: ReferenceLifecycleState;\n\n /** Brief description or preview of the content (max 200 chars) */\n preview: string;\n\n /** Essential metadata for agent decision-making */\n metadata: Pick<\n ContentMetadata,\n 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'\n >;\n\n /** When this reference was created */\n createdAt: Date;\n\n /** Special format indicator for reference IDs in content */\n readonly format: 'ref://{id}';\n}\n\n/**\n * Result of attempting to resolve a content reference\n */\nexport interface ReferenceResolutionResult {\n /** Whether the resolution was successful */\n success: boolean;\n\n /** The resolved content if successful */\n content?: Buffer;\n\n /** Complete metadata if successful */\n metadata?: ContentMetadata;\n\n /** Error message if resolution failed */\n error?: string;\n\n /** Specific error type for targeted error handling */\n errorType?:\n | 'not_found'\n | 'expired'\n | 'corrupted'\n | 'access_denied'\n | 'system_error';\n\n /** Suggested actions for recovery */\n suggestedActions?: string[];\n}\n\n/**\n * Configuration for content reference storage and lifecycle\n */\nexport interface ContentReferenceConfig {\n /** Size threshold above which content should be stored as references (default: 10KB) */\n sizeThresholdBytes: number;\n\n /** Maximum age for unused references before cleanup (default: 1 hour) */\n maxAgeMs: number;\n\n /** Maximum number of references to store simultaneously */\n maxReferences: number;\n\n /** Maximum total storage size for all references */\n maxTotalStorageBytes: number;\n\n /** Whether to enable automatic cleanup */\n enableAutoCleanup: boolean;\n\n /** Interval for cleanup checks in milliseconds */\n cleanupIntervalMs: number;\n\n /** Whether to persist references across restarts */\n enablePersistence: boolean;\n\n /** Storage backend configuration */\n storageBackend: 'memory' | 'filesystem' | 'hybrid';\n\n /** Cleanup policies for different content types */\n cleanupPolicies: {\n /** Policy for content marked as \"recent\" from MCP tools */\n recent: { maxAgeMs: number; priority: number };\n\n /** Policy for user-uploaded content */\n userContent: { maxAgeMs: number; priority: number };\n\n /** Policy for agent-generated content */\n agentGenerated: { maxAgeMs: number; priority: number };\n\n /** Default policy for other content */\n default: { maxAgeMs: number; priority: number };\n };\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONTENT_REFERENCE_CONFIG: ContentReferenceConfig = {\n sizeThresholdBytes: 10 * 1024,\n maxAgeMs: 60 * 60 * 1000,\n maxReferences: 100,\n maxTotalStorageBytes: 100 * 1024 * 1024,\n enableAutoCleanup: true,\n cleanupIntervalMs: 5 * 60 * 1000,\n enablePersistence: false,\n storageBackend: 'memory',\n cleanupPolicies: {\n recent: { maxAgeMs: 30 * 60 * 1000, priority: 1 },\n userContent: { maxAgeMs: 2 * 60 * 60 * 1000, priority: 2 },\n agentGenerated: { maxAgeMs: 60 * 60 * 1000, priority: 3 },\n default: { maxAgeMs: 60 * 60 * 1000, priority: 4 },\n },\n};\n\n/**\n * Statistics about content reference usage and storage\n */\nexport interface ContentReferenceStats {\n /** Total number of active references */\n activeReferences: number;\n\n /** Total storage used by all references in bytes */\n totalStorageBytes: number;\n\n /** Number of references cleaned up in last cleanup cycle */\n recentlyCleanedUp: number;\n\n /** Number of successful reference resolutions since startup */\n totalResolutions: number;\n\n /** Number of failed resolution attempts */\n failedResolutions: number;\n\n /** Average content size in bytes */\n averageContentSize: number;\n\n /** Most frequently accessed reference ID */\n mostAccessedReferenceId?: ReferenceId;\n\n /** Storage utilization percentage */\n storageUtilization: number;\n\n /** Performance metrics */\n performanceMetrics: {\n /** Average time to create a reference in milliseconds */\n averageCreationTimeMs: number;\n\n /** Average time to resolve a reference in milliseconds */\n averageResolutionTimeMs: number;\n\n /** Average cleanup time in milliseconds */\n averageCleanupTimeMs: number;\n };\n}\n\n/**\n * Error types for content reference operations\n */\nexport class ContentReferenceError extends Error {\n constructor(\n message: string,\n public readonly type: ReferenceResolutionResult['errorType'],\n public readonly referenceId?: ReferenceId,\n public readonly suggestedActions?: string[]\n ) {\n super(message);\n this.name = 'ContentReferenceError';\n }\n}\n\n/**\n * Interface for content reference storage implementations\n */\nexport interface ContentReferenceStore {\n /**\n * Store content and return a reference\n */\n storeContent(\n content: Buffer,\n metadata: Omit<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n >\n ): Promise<ContentReference>;\n\n /**\n * Resolve a reference to its content\n */\n resolveReference(\n referenceId: ReferenceId\n ): Promise<ReferenceResolutionResult>;\n\n /**\n * Check if a reference exists and is valid\n */\n hasReference(referenceId: ReferenceId): Promise<boolean>;\n\n /**\n * Mark a reference for cleanup\n */\n cleanupReference(referenceId: ReferenceId): Promise<boolean>;\n\n /**\n * Get current storage statistics\n */\n getStats(): Promise<ContentReferenceStats>;\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ContentReferenceConfig>): Promise<void>;\n\n /**\n * Perform cleanup based on current policies\n */\n performCleanup(): Promise<{ cleanedUp: number; errors: string[] }>;\n\n /**\n * Dispose of resources\n */\n dispose(): Promise<void>;\n}\n"],"names":[],"mappings":"AAuLO,MAAM,mCAA2D;AAAA,EACtE,oBAAoB,KAAK;AAAA,EACzB,UAAU,KAAK,KAAK;AAAA,EACpB,eAAe;AAAA,EACf,sBAAsB,MAAM,OAAO;AAAA,EACnC,mBAAmB;AAAA,EACnB,mBAAmB,IAAI,KAAK;AAAA,EAC5B,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,IACf,QAAQ,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IAC9C,aAAa,EAAE,UAAU,IAAI,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACvD,gBAAgB,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACtD,SAAS,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,EAAE;AAErD;AA8CO,MAAM,8BAA8B,MAAM;AAAA,EAC/C,YACE,SACgB,MACA,aACA,kBAChB;AACA,UAAM,OAAO;AAJG,SAAA,OAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;"}
@@ -1,10 +1,15 @@
1
- const FIELD_PRIORITIES = {
2
- ESSENTIAL: "essential",
3
- COMMON: "common",
4
- ADVANCED: "advanced",
5
- EXPERT: "expert"
1
+ import { EntityFormat } from "./index26.js";
2
+ const ENTITY_PATTERNS = {
3
+ TOPIC_REFERENCE: "the topic",
4
+ TOKEN_REFERENCE: "the token"
6
5
  };
6
+ ({
7
+ TOPIC: EntityFormat.TOPIC_ID,
8
+ TOKEN: EntityFormat.TOKEN_ID,
9
+ ACCOUNT: EntityFormat.ACCOUNT_ID,
10
+ CONTRACT: EntityFormat.CONTRACT_ID
11
+ });
7
12
  export {
8
- FIELD_PRIORITIES
13
+ ENTITY_PATTERNS
9
14
  };
10
15
  //# sourceMappingURL=index38.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index38.js","sources":["../../src/constants/form-priorities.ts"],"sourcesContent":["/**\n * Form field priorities for progressive disclosure\n */\nexport const FIELD_PRIORITIES = {\n ESSENTIAL: 'essential',\n COMMON: 'common', \n ADVANCED: 'advanced',\n EXPERT: 'expert'\n} as const;\n\n/**\n * Form field types\n */\nexport const FORM_FIELD_TYPES = {\n TEXT: 'text',\n NUMBER: 'number',\n SELECT: 'select',\n CHECKBOX: 'checkbox',\n TEXTAREA: 'textarea',\n FILE: 'file',\n ARRAY: 'array',\n OBJECT: 'object',\n CURRENCY: 'currency',\n PERCENTAGE: 'percentage',\n} as const;"],"names":[],"mappings":"AAGO,MAAM,mBAAmB;AAAA,EAC9B,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,QAAQ;AACV;"}
1
+ {"version":3,"file":"index38.js","sources":["../../src/constants/entity-references.ts"],"sourcesContent":["/**\n * Common entity reference patterns used across the application\n */\nexport const ENTITY_PATTERNS = {\n TOPIC_REFERENCE: 'the topic',\n TOKEN_REFERENCE: 'the token',\n ACCOUNT_REFERENCE: 'the account',\n TRANSACTION_REFERENCE: 'the transaction',\n CONTRACT_REFERENCE: 'the contract',\n} as const;\n\n/**\n * Entity type identifiers\n */\nimport { EntityFormat } from '../services/formatters/types';\n\nexport const ENTITY_TYPES = {\n TOPIC: EntityFormat.TOPIC_ID,\n TOKEN: EntityFormat.TOKEN_ID,\n ACCOUNT: EntityFormat.ACCOUNT_ID,\n TRANSACTION: 'transaction',\n CONTRACT: EntityFormat.CONTRACT_ID,\n} as const;\n"],"names":[],"mappings":";AAGO,MAAM,kBAAkB;AAAA,EAC7B,iBAAiB;AAAA,EACjB,iBAAiB;AAInB;AAAA,CAO4B;AAAA,EAC1B,OAAO,aAAa;AAAA,EACpB,OAAO,aAAa;AAAA,EACpB,SAAS,aAAa;AAAA,EAEtB,UAAU,aAAa;AACzB;"}
@@ -1,30 +1,10 @@
1
- const DEFAULT_CONTENT_REFERENCE_CONFIG = {
2
- sizeThresholdBytes: 10 * 1024,
3
- maxAgeMs: 60 * 60 * 1e3,
4
- maxReferences: 100,
5
- maxTotalStorageBytes: 100 * 1024 * 1024,
6
- enableAutoCleanup: true,
7
- cleanupIntervalMs: 5 * 60 * 1e3,
8
- enablePersistence: false,
9
- storageBackend: "memory",
10
- cleanupPolicies: {
11
- recent: { maxAgeMs: 30 * 60 * 1e3, priority: 1 },
12
- userContent: { maxAgeMs: 2 * 60 * 60 * 1e3, priority: 2 },
13
- agentGenerated: { maxAgeMs: 60 * 60 * 1e3, priority: 3 },
14
- default: { maxAgeMs: 60 * 60 * 1e3, priority: 4 }
15
- }
1
+ const FIELD_PRIORITIES = {
2
+ ESSENTIAL: "essential",
3
+ COMMON: "common",
4
+ ADVANCED: "advanced",
5
+ EXPERT: "expert"
16
6
  };
17
- class ContentReferenceError extends Error {
18
- constructor(message, type, referenceId, suggestedActions) {
19
- super(message);
20
- this.type = type;
21
- this.referenceId = referenceId;
22
- this.suggestedActions = suggestedActions;
23
- this.name = "ContentReferenceError";
24
- }
25
- }
26
7
  export {
27
- ContentReferenceError,
28
- DEFAULT_CONTENT_REFERENCE_CONFIG
8
+ FIELD_PRIORITIES
29
9
  };
30
10
  //# sourceMappingURL=index39.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index39.js","sources":["../../src/types/content-reference.ts"],"sourcesContent":["/**\n * Content Reference System Types\n *\n * Shared interfaces for the Reference-Based Content System that handles\n * large content storage with unique reference IDs to optimize context window usage.\n */\n\n/**\n * Unique identifier for stored content references\n * Format: Cryptographically secure 32-byte identifier with base64url encoding\n */\nexport type ReferenceId = string;\n\n/**\n * Lifecycle state of a content reference\n */\nexport type ReferenceLifecycleState =\n | 'active'\n | 'expired'\n | 'cleanup_pending'\n | 'invalid';\n\n/**\n * Content types supported by the reference system\n */\nexport type ContentType =\n | 'text'\n | 'json'\n | 'html'\n | 'markdown'\n | 'binary'\n | 'unknown';\n\n/**\n * Sources that created the content reference\n */\nexport type ContentSource =\n | 'mcp_tool'\n | 'user_upload'\n | 'agent_generated'\n | 'system';\n\n/**\n * Metadata associated with stored content\n */\nexport interface ContentMetadata {\n /** Content type classification */\n contentType: ContentType;\n\n /** MIME type of the original content */\n mimeType?: string;\n\n /** Size in bytes of the stored content */\n sizeBytes: number;\n\n /** When the content was originally stored */\n createdAt: Date;\n\n /** Last time the content was accessed via reference resolution */\n lastAccessedAt: Date;\n\n /** Source that created this content reference */\n source: ContentSource;\n\n /** Name of the MCP tool that generated the content (if applicable) */\n mcpToolName?: string;\n\n /** Original filename or suggested name for the content */\n fileName?: string;\n\n /** Number of times this reference has been resolved */\n accessCount: number;\n\n /** Tags for categorization and cleanup policies */\n tags?: string[];\n\n /** Custom metadata from the source */\n customMetadata?: Record<string, unknown>;\n}\n\n/**\n * Core content reference object passed through agent context\n * Designed to be lightweight (<100 tokens) while providing enough\n * information for agent decision-making\n */\nexport interface ContentReference {\n /** Unique identifier for resolving the content */\n referenceId: ReferenceId;\n\n /** Current lifecycle state */\n state: ReferenceLifecycleState;\n\n /** Brief description or preview of the content (max 200 chars) */\n preview: string;\n\n /** Essential metadata for agent decision-making */\n metadata: Pick<\n ContentMetadata,\n 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'\n >;\n\n /** When this reference was created */\n createdAt: Date;\n\n /** Special format indicator for reference IDs in content */\n readonly format: 'ref://{id}';\n}\n\n/**\n * Result of attempting to resolve a content reference\n */\nexport interface ReferenceResolutionResult {\n /** Whether the resolution was successful */\n success: boolean;\n\n /** The resolved content if successful */\n content?: Buffer;\n\n /** Complete metadata if successful */\n metadata?: ContentMetadata;\n\n /** Error message if resolution failed */\n error?: string;\n\n /** Specific error type for targeted error handling */\n errorType?:\n | 'not_found'\n | 'expired'\n | 'corrupted'\n | 'access_denied'\n | 'system_error';\n\n /** Suggested actions for recovery */\n suggestedActions?: string[];\n}\n\n/**\n * Configuration for content reference storage and lifecycle\n */\nexport interface ContentReferenceConfig {\n /** Size threshold above which content should be stored as references (default: 10KB) */\n sizeThresholdBytes: number;\n\n /** Maximum age for unused references before cleanup (default: 1 hour) */\n maxAgeMs: number;\n\n /** Maximum number of references to store simultaneously */\n maxReferences: number;\n\n /** Maximum total storage size for all references */\n maxTotalStorageBytes: number;\n\n /** Whether to enable automatic cleanup */\n enableAutoCleanup: boolean;\n\n /** Interval for cleanup checks in milliseconds */\n cleanupIntervalMs: number;\n\n /** Whether to persist references across restarts */\n enablePersistence: boolean;\n\n /** Storage backend configuration */\n storageBackend: 'memory' | 'filesystem' | 'hybrid';\n\n /** Cleanup policies for different content types */\n cleanupPolicies: {\n /** Policy for content marked as \"recent\" from MCP tools */\n recent: { maxAgeMs: number; priority: number };\n\n /** Policy for user-uploaded content */\n userContent: { maxAgeMs: number; priority: number };\n\n /** Policy for agent-generated content */\n agentGenerated: { maxAgeMs: number; priority: number };\n\n /** Default policy for other content */\n default: { maxAgeMs: number; priority: number };\n };\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONTENT_REFERENCE_CONFIG: ContentReferenceConfig = {\n sizeThresholdBytes: 10 * 1024,\n maxAgeMs: 60 * 60 * 1000,\n maxReferences: 100,\n maxTotalStorageBytes: 100 * 1024 * 1024,\n enableAutoCleanup: true,\n cleanupIntervalMs: 5 * 60 * 1000,\n enablePersistence: false,\n storageBackend: 'memory',\n cleanupPolicies: {\n recent: { maxAgeMs: 30 * 60 * 1000, priority: 1 },\n userContent: { maxAgeMs: 2 * 60 * 60 * 1000, priority: 2 },\n agentGenerated: { maxAgeMs: 60 * 60 * 1000, priority: 3 },\n default: { maxAgeMs: 60 * 60 * 1000, priority: 4 },\n },\n};\n\n/**\n * Statistics about content reference usage and storage\n */\nexport interface ContentReferenceStats {\n /** Total number of active references */\n activeReferences: number;\n\n /** Total storage used by all references in bytes */\n totalStorageBytes: number;\n\n /** Number of references cleaned up in last cleanup cycle */\n recentlyCleanedUp: number;\n\n /** Number of successful reference resolutions since startup */\n totalResolutions: number;\n\n /** Number of failed resolution attempts */\n failedResolutions: number;\n\n /** Average content size in bytes */\n averageContentSize: number;\n\n /** Most frequently accessed reference ID */\n mostAccessedReferenceId?: ReferenceId;\n\n /** Storage utilization percentage */\n storageUtilization: number;\n\n /** Performance metrics */\n performanceMetrics: {\n /** Average time to create a reference in milliseconds */\n averageCreationTimeMs: number;\n\n /** Average time to resolve a reference in milliseconds */\n averageResolutionTimeMs: number;\n\n /** Average cleanup time in milliseconds */\n averageCleanupTimeMs: number;\n };\n}\n\n/**\n * Error types for content reference operations\n */\nexport class ContentReferenceError extends Error {\n constructor(\n message: string,\n public readonly type: ReferenceResolutionResult['errorType'],\n public readonly referenceId?: ReferenceId,\n public readonly suggestedActions?: string[]\n ) {\n super(message);\n this.name = 'ContentReferenceError';\n }\n}\n\n/**\n * Interface for content reference storage implementations\n */\nexport interface ContentReferenceStore {\n /**\n * Store content and return a reference\n */\n storeContent(\n content: Buffer,\n metadata: Omit<\n ContentMetadata,\n 'createdAt' | 'lastAccessedAt' | 'accessCount'\n >\n ): Promise<ContentReference>;\n\n /**\n * Resolve a reference to its content\n */\n resolveReference(\n referenceId: ReferenceId\n ): Promise<ReferenceResolutionResult>;\n\n /**\n * Check if a reference exists and is valid\n */\n hasReference(referenceId: ReferenceId): Promise<boolean>;\n\n /**\n * Mark a reference for cleanup\n */\n cleanupReference(referenceId: ReferenceId): Promise<boolean>;\n\n /**\n * Get current storage statistics\n */\n getStats(): Promise<ContentReferenceStats>;\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ContentReferenceConfig>): Promise<void>;\n\n /**\n * Perform cleanup based on current policies\n */\n performCleanup(): Promise<{ cleanedUp: number; errors: string[] }>;\n\n /**\n * Dispose of resources\n */\n dispose(): Promise<void>;\n}\n"],"names":[],"mappings":"AAuLO,MAAM,mCAA2D;AAAA,EACtE,oBAAoB,KAAK;AAAA,EACzB,UAAU,KAAK,KAAK;AAAA,EACpB,eAAe;AAAA,EACf,sBAAsB,MAAM,OAAO;AAAA,EACnC,mBAAmB;AAAA,EACnB,mBAAmB,IAAI,KAAK;AAAA,EAC5B,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,IACf,QAAQ,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IAC9C,aAAa,EAAE,UAAU,IAAI,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACvD,gBAAgB,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACtD,SAAS,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,EAAE;AAErD;AA8CO,MAAM,8BAA8B,MAAM;AAAA,EAC/C,YACE,SACgB,MACA,aACA,kBAChB;AACA,UAAM,OAAO;AAJG,SAAA,OAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;"}
1
+ {"version":3,"file":"index39.js","sources":["../../src/constants/form-priorities.ts"],"sourcesContent":["/**\n * Form field priorities for progressive disclosure\n */\nexport const FIELD_PRIORITIES = {\n ESSENTIAL: 'essential',\n COMMON: 'common', \n ADVANCED: 'advanced',\n EXPERT: 'expert'\n} as const;\n\n/**\n * Form field types\n */\nexport const FORM_FIELD_TYPES = {\n TEXT: 'text',\n NUMBER: 'number',\n SELECT: 'select',\n CHECKBOX: 'checkbox',\n TEXTAREA: 'textarea',\n FILE: 'file',\n ARRAY: 'array',\n OBJECT: 'object',\n CURRENCY: 'currency',\n PERCENTAGE: 'percentage',\n} as const;"],"names":[],"mappings":"AAGO,MAAM,mBAAmB;AAAA,EAC9B,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,QAAQ;AACV;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hashgraphonline/conversational-agent",
3
- "version": "0.1.221",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "main": "./dist/cjs/index.cjs",
6
6
  "module": "./dist/esm/index.js",
@@ -29,7 +29,7 @@
29
29
  "README.md"
30
30
  ],
31
31
  "scripts": {
32
- "test": "jest",
32
+ "test": "jest --detectOpenHandles",
33
33
  "test:integration": "jest tests/integration",
34
34
  "clean": "rimraf dist",
35
35
  "build:es": "BUILD_FORMAT=es vite build",
@@ -95,7 +95,7 @@
95
95
  },
96
96
  "dependencies": {
97
97
  "@hashgraph/sdk": "^2.69.0",
98
- "@hashgraphonline/standards-agent-kit": "0.2.135",
98
+ "@hashgraphonline/standards-agent-kit": "file:.yalc/@hashgraphonline/standards-agent-kit",
99
99
  "@hashgraphonline/standards-sdk": "0.0.187",
100
100
  "@langchain/anthropic": "^0.3.26",
101
101
  "@langchain/core": "^0.3.72",
@@ -356,7 +356,9 @@ export class ContentStorage implements ContentReferenceStore {
356
356
  */
357
357
  exportMessages(): Array<{ content: string; type: string; storedAt: string; id: string }> {
358
358
  return this.messages.map((stored) => ({
359
- content: stored.message.content,
359
+ content: typeof stored.message.content === 'string'
360
+ ? stored.message.content
361
+ : JSON.stringify(stored.message.content),
360
362
  type: stored.message._getType(),
361
363
  storedAt: stored.storedAt.toISOString(),
362
364
  id: stored.id,
@@ -106,7 +106,11 @@ export class AirdropToolWrapper extends StructuredTool {
106
106
  }
107
107
 
108
108
  private async getTokenInfo(tokenId: string): Promise<TokenInfo> {
109
- return await this.queryTokenInfo(tokenId);
109
+ try {
110
+ return await this.queryTokenInfo(tokenId);
111
+ } catch (error) {
112
+ throw error;
113
+ }
110
114
  }
111
115
 
112
116
  private async queryTokenInfo(tokenId: string): Promise<TokenInfo> {