import './AIStream-BwgeGI-N.js'; import './streaming/index.js'; import { L as LLMProvider, M as Message } from './AgentSwarm-TLYCGpA9.js'; import './common.d-iR60eBef.js'; import './agents.d-Dhf5taAS.js'; import './ConversationStore-C33N9v7n.js'; import './store/index.js'; import './context/index.js'; import './summarization/index.js'; import './ZeroDBSessionStore-BQisM5nM.js'; import './auth/index.js'; import './zerodb/index.js'; import './ZeroDBStorage-BrocsToA.js'; import './search/index.js'; import './DesignConstraints-C19svfal.js'; /** * Type definitions for user memory system */ /** * Types of memory items */ type MemoryType = 'fact' | 'preference' | 'context' | 'entity' | 'goal'; /** * Individual memory item */ interface MemoryItem { /** Unique identifier for the memory item */ id: string; /** User ID this memory belongs to */ userId: string; /** Type of memory */ type: MemoryType; /** Memory content */ content: string; /** Optional entity name (for entity type memories) */ entityName?: string; /** Optional entity type (person, place, organization, etc.) */ entityType?: string; /** Timestamp when memory was created */ createdAt: number; /** Timestamp when memory was last updated */ updatedAt: number; /** Timestamp when memory was last accessed */ lastAccessedAt: number; /** TTL in seconds (0 = no expiration) */ ttl?: number; /** Priority/importance score (0-1) */ importance: number; /** Confidence score (0-1) */ confidence: number; /** Source of the memory (e.g., conversation ID) */ source?: string; /** Custom metadata */ metadata?: Record; } /** * Entity mention in conversation */ interface EntityMention { /** Entity name */ name: string; /** Entity type */ type: 'person' | 'place' | 'organization' | 'product' | 'event' | 'other'; /** Context around the mention */ context: string; /** Confidence score (0-1) */ confidence: number; } /** * Fact extraction result */ interface FactExtractionResult { /** Extracted facts */ facts: Array<{ content: string; type: MemoryType; entityName?: string; entityType?: string; confidence: number; importance: number; }>; /** Extracted entities */ entities: EntityMention[]; /** Whether extraction was successful */ success: boolean; /** Error message if extraction failed */ error?: string; } /** * Memory search options */ interface MemorySearchOptions { /** Filter by memory type */ type?: MemoryType; /** Filter by entity name */ entityName?: string; /** Filter by entity type */ entityType?: string; /** Minimum importance score */ minImportance?: number; /** Minimum confidence score */ minConfidence?: number; /** Maximum age in seconds */ maxAge?: number; /** Maximum number of results */ limit?: number; /** Offset for pagination */ offset?: number; /** Whether to include expired memories */ includeExpired?: boolean; } /** * Memory configuration */ interface MemoryConfig { /** Default TTL in seconds (0 = no expiration) */ defaultTTL?: number; /** Default importance score for new memories */ defaultImportance?: number; /** Default confidence score for new memories */ defaultConfidence?: number; /** Maximum number of memories to keep per user */ maxMemoriesPerUser?: number; /** Minimum importance score to keep a memory */ minImportanceThreshold?: number; /** Whether to automatically consolidate similar memories */ autoConsolidate?: boolean; } /** * Memory store statistics */ interface MemoryStoreStats { /** Total number of memories */ totalMemories: number; /** Number of memories by type */ memoriesByType: Record; /** Number of unique users */ uniqueUsers: number; /** Number of expired memories */ expiredMemories?: number; /** Storage size in bytes (if available) */ storageSize?: number; } /** * Options for saving a memory */ interface SaveMemoryOptions { /** TTL in seconds (overrides default) */ ttl?: number; /** Importance score (0-1) */ importance?: number; /** Confidence score (0-1) */ confidence?: number; /** Source identifier */ source?: string; /** Custom metadata */ metadata?: Record; } /** * Memory update options */ interface UpdateMemoryOptions { /** New content */ content?: string; /** New importance score */ importance?: number; /** New confidence score */ confidence?: number; /** New TTL in seconds */ ttl?: number; /** Additional metadata to merge */ metadata?: Record; } /** * Contradiction detection result */ interface ContradictionResult { /** Whether a contradiction was detected */ hasContradiction: boolean; /** The existing memory that contradicts */ existingMemory?: MemoryItem; /** The new memory being added */ newMemory?: Partial; /** Explanation of the contradiction */ explanation?: string; /** Confidence in the contradiction detection (0-1) */ confidence: number; /** Suggested resolution strategy */ resolution?: 'keep_existing' | 'replace' | 'merge' | 'keep_both'; } /** * Memory consolidation result */ interface ConsolidationResult { /** Whether memories were consolidated */ consolidated: boolean; /** The consolidated memory (if consolidation occurred) */ consolidatedMemory?: MemoryItem; /** Original memories that were consolidated */ originalMemories: MemoryItem[]; /** Explanation of the consolidation */ explanation?: string; } /** * Base configuration for memory stores */ interface BaseMemoryStoreConfig { /** Default TTL in seconds (0 = no expiration) */ defaultTTL?: number; /** Namespace/prefix for keys */ namespace?: string; /** Memory configuration */ memoryConfig?: MemoryConfig; } /** * Configuration for in-memory memory store */ interface InMemoryMemoryStoreConfig extends BaseMemoryStoreConfig { type: 'memory'; /** Maximum number of memories to store (LRU eviction) */ maxMemories?: number; } /** * Configuration for Redis memory store */ interface RedisMemoryStoreConfig extends BaseMemoryStoreConfig { type: 'redis'; /** Redis connection URL */ url?: string; /** Redis host */ host?: string; /** Redis port */ port?: number; /** Redis password */ password?: string; /** Redis database number */ db?: number; /** Key prefix for Redis keys */ keyPrefix?: string; } /** * Configuration for ZeroDB memory store */ interface ZeroDBMemoryStoreConfig extends BaseMemoryStoreConfig { type: 'zerodb'; /** ZeroDB project ID */ projectId: string; /** ZeroDB API key */ apiKey: string; /** Table name for memories */ tableName?: string; } /** * Union type for all memory store configurations */ type MemoryStoreConfig = InMemoryMemoryStoreConfig | RedisMemoryStoreConfig | ZeroDBMemoryStoreConfig; /** * Abstract base class for memory stores * * Provides a common interface for persisting user memories across different backends. * All memory store implementations must extend this class and implement the abstract methods. */ declare abstract class MemoryStore { protected config: BaseMemoryStoreConfig; constructor(config?: BaseMemoryStoreConfig); /** * Save a memory item * @param memory - Memory item to save * @param options - Optional save options * @returns The saved memory item */ abstract save(memory: Omit, options?: SaveMemoryOptions): Promise; /** * Get a memory by ID * @param memoryId - Unique identifier for the memory * @returns The memory item if found, null otherwise */ abstract get(memoryId: string): Promise; /** * Update a memory item * @param memoryId - Unique identifier for the memory * @param updates - Updates to apply * @returns The updated memory item */ abstract update(memoryId: string, updates: UpdateMemoryOptions): Promise; /** * Delete a memory by ID * @param memoryId - Unique identifier for the memory * @returns True if deleted, false if not found */ abstract delete(memoryId: string): Promise; /** * Search memories for a user * @param userId - User ID to search memories for * @param options - Search options * @returns Array of matching memory items */ abstract search(userId: string, options?: MemorySearchOptions): Promise; /** * Get all memories for a user * @param userId - User ID * @param includeExpired - Whether to include expired memories * @returns Array of memory items */ abstract getByUser(userId: string, includeExpired?: boolean): Promise; /** * Get memories by type * @param userId - User ID * @param type - Memory type * @param includeExpired - Whether to include expired memories * @returns Array of memory items */ abstract getByType(userId: string, type: MemoryType, includeExpired?: boolean): Promise; /** * Get memories by entity * @param userId - User ID * @param entityName - Entity name * @param includeExpired - Whether to include expired memories * @returns Array of memory items */ abstract getByEntity(userId: string, entityName: string, includeExpired?: boolean): Promise; /** * Delete all memories for a user * @param userId - User ID * @returns Number of memories deleted */ abstract deleteByUser(userId: string): Promise; /** * Clear all memories from the store * @returns Number of memories cleared */ abstract clear(): Promise; /** * Get store statistics * @returns Memory store statistics */ abstract getStats(): Promise; /** * Clean up expired memories * @returns Number of memories removed */ abstract cleanup(): Promise; /** * Close the store and cleanup resources */ abstract close(): Promise; /** * Check if a memory has expired based on TTL * @param memory - Memory item * @returns True if expired, false otherwise */ protected isExpired(memory: MemoryItem): boolean; /** * Generate a namespaced key for storage * @param key - Key identifier * @returns Namespaced key */ protected getKey(key: string): string; /** * Generate a unique memory ID * @returns Unique ID */ protected generateId(): string; /** * Create a complete memory item from partial data * @param partial - Partial memory data * @param options - Save options * @returns Complete memory item */ protected createMemoryItem(partial: Omit, options?: SaveMemoryOptions): MemoryItem; /** * Filter memories based on search options * @param memories - Array of memories to filter * @param options - Search options * @returns Filtered array of memories */ protected filterMemories(memories: MemoryItem[], options?: MemorySearchOptions): MemoryItem[]; } /** * In-memory memory store implementation * * Stores user memories in memory with optional LRU eviction. * Suitable for development, testing, or single-process applications. * Data is lost when the process restarts. */ declare class InMemoryMemoryStore extends MemoryStore { private memories; private userMemories; private accessOrder; private maxMemories; constructor(config?: Omit); save(memory: Omit, options?: SaveMemoryOptions): Promise; get(memoryId: string): Promise; update(memoryId: string, updates: UpdateMemoryOptions): Promise; delete(memoryId: string): Promise; search(userId: string, options?: MemorySearchOptions): Promise; getByUser(userId: string, includeExpired?: boolean): Promise; getByType(userId: string, type: MemoryType, includeExpired?: boolean): Promise; getByEntity(userId: string, entityName: string, includeExpired?: boolean): Promise; deleteByUser(userId: string): Promise; clear(): Promise; getStats(): Promise; cleanup(): Promise; close(): Promise; /** * Update the access order for LRU eviction */ private updateAccessOrder; /** * Remove a memory ID from the access order */ private removeFromAccessOrder; /** * Evict least recently used memories if over limit */ private evictIfNeeded; /** * Get the current size of the store */ size(): number; } /** * ZeroDB memory store implementation * * Stores user memories in ZeroDB for cloud persistence and scalability. */ declare class ZeroDBMemoryStore extends MemoryStore { private projectId; private apiKey; private tableName; private baseUrl; constructor(config: Omit); save(memory: Omit, options?: SaveMemoryOptions): Promise; get(memoryId: string): Promise; update(memoryId: string, updates: UpdateMemoryOptions): Promise; delete(memoryId: string): Promise; search(userId: string, options?: MemorySearchOptions): Promise; getByUser(userId: string, includeExpired?: boolean): Promise; getByType(userId: string, type: MemoryType, includeExpired?: boolean): Promise; getByEntity(userId: string, entityName: string, includeExpired?: boolean): Promise; deleteByUser(userId: string): Promise; clear(): Promise; getStats(): Promise; cleanup(): Promise; close(): Promise; /** * Convert rows to memory items */ private rowsToMemories; /** * Insert a row into ZeroDB */ private insertRow; /** * Query rows from ZeroDB */ private queryRows; /** * Update a row in ZeroDB */ private updateRow; /** * Delete a row from ZeroDB */ private deleteRow; } /** * Configuration for UserMemory */ interface UserMemoryConfig { /** Memory store implementation */ store: MemoryStore; /** LLM provider for fact extraction and analysis */ llmProvider?: LLMProvider; /** Whether to automatically extract facts from conversations */ autoExtract?: boolean; /** Whether to automatically detect contradictions */ detectContradictions?: boolean; /** Whether to automatically consolidate similar memories */ autoConsolidate?: boolean; /** Minimum confidence for auto-extracted facts */ minConfidence?: number; } /** * User memory system */ declare class UserMemory { private store; private llmProvider?; private factExtractor?; private detectContradictions; private autoConsolidate; constructor(config: UserMemoryConfig); /** * Add a memory item * @param userId - User ID * @param content - Memory content * @param type - Memory type * @param options - Save options * @returns The saved memory item */ addMemory(userId: string, content: string, type: MemoryType, options?: SaveMemoryOptions & { entityName?: string; entityType?: string; }): Promise; /** * Extract and save memories from conversation messages * @param userId - User ID * @param messages - Conversation messages * @param source - Optional source identifier * @returns Array of saved memory items */ extractFromConversation(userId: string, messages: Message[], source?: string): Promise; /** * Get memory by ID * @param memoryId - Memory ID * @returns Memory item or null */ getMemory(memoryId: string): Promise; /** * Search memories * @param userId - User ID * @param options - Search options * @returns Array of matching memories */ searchMemories(userId: string, options?: MemorySearchOptions): Promise; /** * Get all memories for a user * @param userId - User ID * @returns Array of memory items */ getUserMemories(userId: string): Promise; /** * Get memories by type * @param userId - User ID * @param type - Memory type * @returns Array of memory items */ getMemoriesByType(userId: string, type: MemoryType): Promise; /** * Get memories by entity * @param userId - User ID * @param entityName - Entity name * @returns Array of memory items */ getMemoriesByEntity(userId: string, entityName: string): Promise; /** * Update a memory * @param memoryId - Memory ID * @param content - New content * @param importance - New importance score * @returns Updated memory or null */ updateMemory(memoryId: string, updates: { content?: string; importance?: number; confidence?: number; }): Promise; /** * Delete a memory * @param memoryId - Memory ID * @returns True if deleted */ deleteMemory(memoryId: string): Promise; /** * Delete all memories for a user * @param userId - User ID * @returns Number of memories deleted */ deleteUserMemories(userId: string): Promise; /** * Check for contradictions with existing memories * @param userId - User ID * @param newContent - New memory content * @returns Contradiction result */ checkContradiction(userId: string, newContent: string): Promise; /** * Consolidate similar memories for a user * @param userId - User ID * @returns Consolidation results */ consolidateMemories(userId: string): Promise; /** * Find and consolidate similar memories */ private findAndConsolidateSimilar; /** * Check if two memories should be consolidated */ private shouldConsolidateMemories; /** * Clean up expired memories * @returns Number of memories removed */ cleanup(): Promise; /** * Get memory statistics */ getStats(): Promise; /** * Close the memory system */ close(): Promise; } /** * Fact extractor for user memory system * * Uses LLM to extract facts, preferences, entities, and other memory items * from conversations. */ /** * Configuration for fact extraction */ interface FactExtractorConfig { /** LLM provider to use for extraction */ llmProvider: LLMProvider; /** Temperature for LLM calls (0-1) */ temperature?: number; /** Maximum tokens for LLM response */ maxTokens?: number; /** Minimum confidence score to include a fact (0-1) */ minConfidence?: number; /** Whether to extract entities */ extractEntities?: boolean; /** Whether to extract preferences */ extractPreferences?: boolean; /** Whether to extract goals */ extractGoals?: boolean; } /** * Fact extractor class */ declare class FactExtractor { private config; constructor(config: FactExtractorConfig); /** * Extract facts from messages * @param messages - Array of conversation messages * @returns Extraction result with facts and entities */ extract(messages: Message[]): Promise; /** * Build extraction prompt from messages */ private buildExtractionPrompt; /** * Get system prompt for extraction */ private getSystemPrompt; /** * Parse extraction result from LLM response */ private parseExtractionResult; /** * Extract facts from a single message * @param message - Single message to extract from * @returns Extraction result */ extractFromMessage(message: Message): Promise; /** * Deduplicate extracted facts * @param facts - Array of facts to deduplicate * @returns Deduplicated array of facts */ deduplicateFacts(facts: Array<{ content: string; type: MemoryType; confidence: number; importance: number; }>): Array<{ content: string; type: MemoryType; confidence: number; importance: number; }>; } /** * Rate limiting types and interfaces for AI Kit */ /** * Supported rate limiting algorithms */ declare enum RateLimitAlgorithm { /** Token bucket algorithm - smooth rate limiting with burst capacity */ TOKEN_BUCKET = "token_bucket", /** Fixed window counter - simple time-based windows */ FIXED_WINDOW = "fixed_window", /** Sliding window log - precise rate limiting with historical tracking */ SLIDING_WINDOW = "sliding_window", /** Leaky bucket - consistent output rate */ LEAKY_BUCKET = "leaky_bucket", /** Cost-based limiting - track usage by cost (tokens, dollars) */ COST_BASED = "cost_based" } /** * Time window options for rate limiting */ declare enum TimeWindow { SECOND = 1000, MINUTE = 60000, HOUR = 3600000, DAY = 86400000 } /** * Storage backend types */ declare enum StorageBackend { MEMORY = "memory", REDIS = "redis" } /** * Rate limit scope types */ declare enum RateLimitScope { USER = "user", IP = "ip", GLOBAL = "global", API_KEY = "api_key" } /** * Actions to take when rate limit is exceeded */ declare enum RateLimitAction { /** Reject the request */ REJECT = "reject", /** Queue the request */ QUEUE = "queue", /** Allow with warning */ WARN = "warn" } /** * Configuration for a rate limit rule */ interface RateLimitRule { /** Algorithm to use */ algorithm: RateLimitAlgorithm; /** Maximum requests/tokens allowed */ limit: number; /** Time window in milliseconds */ window: TimeWindow | number; /** Burst capacity (for token bucket) */ burst?: number; /** Refill rate (tokens per second for leaky bucket) */ refillRate?: number; /** Cost per request (for cost-based limiting) */ costPerRequest?: number; /** Action to take when limit exceeded */ action?: RateLimitAction; } /** * Configuration for the rate limiter */ interface RateLimiterConfig { /** Storage backend to use */ storage?: StorageBackend; /** Redis connection options (if using Redis backend) */ redis?: { host: string; port: number; password?: string; db?: number; }; /** Rate limit rules by scope */ rules: { [key in RateLimitScope]?: RateLimitRule[]; }; /** Key prefix for storage */ keyPrefix?: string; /** Enable detailed logging */ debug?: boolean; } /** * Result of a rate limit check */ interface RateLimitResult { /** Whether the request is allowed */ allowed: boolean; /** Current limit for this scope */ limit: number; /** Remaining requests/tokens */ remaining: number; /** Time until reset (milliseconds) */ resetAt: number; /** Retry after (milliseconds) - only set when not allowed */ retryAfter?: number; /** Total requests made in current window */ totalRequests?: number; /** Cost consumed (for cost-based limiting) */ costConsumed?: number; /** Action taken */ action?: RateLimitAction; /** Additional metadata */ metadata?: Record; } /** * Cost information for a request */ interface RequestCost { /** Input tokens used */ inputTokens?: number; /** Output tokens used */ outputTokens?: number; /** Total tokens used */ totalTokens?: number; /** Monetary cost in dollars */ cost?: number; /** Custom cost metric */ customCost?: number; } /** * Internal storage interface for rate limit data */ interface RateLimitStorage { /** Get value for a key */ get(key: string): Promise; /** Set value for a key with optional TTL */ set(key: string, value: any, ttl?: number): Promise; /** Increment a counter */ increment(key: string, amount?: number): Promise; /** Delete a key */ delete(key: string): Promise; /** Get multiple keys */ mget(keys: string[]): Promise; /** Set multiple keys */ mset(entries: Array<[string, any]>, ttl?: number): Promise; /** Add to a list */ lpush(key: string, value: any): Promise; /** Get list range */ lrange(key: string, start: number, stop: number): Promise; /** Remove list items */ lrem(key: string, count: number, value: any): Promise; /** Get list length */ llen(key: string): Promise; /** Set expiry on a key */ expire(key: string, ttl: number): Promise; } /** * Rate limit check options */ interface RateLimitCheckOptions { /** Identifier for the entity (user ID, IP, etc.) */ identifier: string; /** Scope of the rate limit */ scope: RateLimitScope; /** Cost of this request (for cost-based limiting) */ cost?: RequestCost; /** Number of tokens to consume (for token bucket) */ tokens?: number; /** Additional metadata */ metadata?: Record; } /** * Rate limiter statistics */ interface RateLimiterStats { /** Total requests processed */ totalRequests: number; /** Requests allowed */ allowed: number; /** Requests blocked */ blocked: number; /** Requests queued */ queued: number; /** Average response time */ avgResponseTime?: number; /** Top limited identifiers */ topLimited?: Array<{ identifier: string; count: number; }>; } /** * Rate Limiter for AI Kit * Implements multiple rate limiting algorithms with flexible storage backends */ /** * Main RateLimiter class */ declare class RateLimiter { private storage; private config; private keyPrefix; private stats; private cleanupInterval?; constructor(config: RateLimiterConfig); /** * Check if a request should be allowed */ check(options: RateLimitCheckOptions): Promise; /** * Check a single rule */ private checkRule; /** * Token bucket algorithm * Allows bursts up to bucket capacity, refills at a steady rate */ private checkTokenBucket; /** * Fixed window counter * Simple time-based windows with reset at window boundaries */ private checkFixedWindow; /** * Sliding window log * Maintains a log of timestamps for precise rate limiting */ private checkSlidingWindow; /** * Leaky bucket algorithm * Processes requests at a constant rate */ private checkLeakyBucket; /** * Cost-based rate limiting * Tracks usage by cost (tokens, dollars, etc.) */ private checkCostBased; /** * Calculate cost from RequestCost object */ private calculateCost; /** * Generate storage key */ private getKey; /** * Reset rate limits for an identifier */ reset(scope: RateLimitScope, identifier: string): Promise; /** * Get current statistics */ getStats(): RateLimiterStats; /** * Reset statistics */ resetStats(): void; /** * Cleanup and close connections */ close(): Promise; /** * Get remaining limit for an identifier */ getRemaining(scope: RateLimitScope, identifier: string, algorithm?: RateLimitAlgorithm): Promise; } /** * ID generation utilities */ /** * Generate a unique ID with optional prefix */ declare function generateId(prefix?: string): string; /** * Generate a short unique ID */ declare function generateShortId(): string; export { type BaseMemoryStoreConfig as B, type EntityMention as E, FactExtractor as F, InMemoryMemoryStore as I, MemoryStore as M, type RedisMemoryStoreConfig as R, type SaveMemoryOptions as S, type UpdateMemoryOptions as U, ZeroDBMemoryStore as Z, type MemoryItem as a, type MemorySearchOptions as b, type MemoryType as c, type MemoryStoreStats as d, UserMemory as e, type MemoryConfig as f, type MemoryStoreConfig as g, type InMemoryMemoryStoreConfig as h, type ZeroDBMemoryStoreConfig as i, type FactExtractionResult as j, RateLimiter as k, type RateLimiterConfig as l, type RateLimitRule as m, type RateLimitStorage as n, StorageBackend as o, generateId as p, generateShortId as q };