import winston from 'winston'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { GetPromptResult, ReadResourceResult } from '@modelcontextprotocol/sdk/types.js'; import { z, ZodSchema } from 'zod'; import OpenAI from 'openai'; type ChalkColor = 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray' | 'redBright' | 'greenBright' | 'yellowBright' | 'blueBright' | 'magentaBright' | 'cyanBright' | 'whiteBright'; interface LoggerOptions { level?: string; silent?: boolean; file?: string; } declare class Logger { private logger; private isSilent; constructor(options?: LoggerOptions); private createTransports; error(message: string, meta?: any, color?: ChalkColor): void; warn(message: string, meta?: any, color?: ChalkColor): void; info(message: string, meta?: any, color?: ChalkColor): void; http(message: string, meta?: any, color?: ChalkColor): void; verbose(message: string, meta?: any, color?: ChalkColor): void; debug(message: string, meta?: any, color?: ChalkColor): void; silly(message: string, meta?: any, color?: ChalkColor): void; displayAIResponse(response: any): void; toolCall(toolName: string, args: any): void; toolResult(result: any): void; displayBox(title: string, content: string, borderColor?: ChalkColor): void; setLevel(level: string): void; getLevel(): string; setSilent(silent: boolean): void; redirectToFile(filePath: string): void; redirectToConsole(): void; createChild(options?: LoggerOptions): Logger; getWinstonLogger(): winston.Logger; } declare const logger: Logger; declare const createLogger: (options?: LoggerOptions) => Logger; declare const setGlobalLogLevel: (level: string) => void; declare const getGlobalLogLevel: () => string; /** * Core types and interfaces for the Model Context Protocol (MCP) module. * * This file contains all the type definitions needed for working with MCP servers, * including client interfaces, server configurations, and tool/prompt/resource types. */ /** * Available MCP client transport types for connecting to MCP servers. * These define the communication protocol used to connect to individual MCP servers. */ type TransportType = 'stdio' | 'sse' | 'streamable-http'; /** * Available server configuration types. * Includes both transport types (for direct server connections) and operational modes (like aggregator). */ type ServerConfigType = TransportType | 'aggregator'; /** * Base configuration for any MCP server. */ interface BaseServerConfig { /** * Configuration type: transport protocol for direct connections or operational mode. * - Transport types ('stdio', 'sse', 'streamable-http'): Connect directly to MCP servers * - Operational modes ('aggregator'): Special server modes that aggregate other servers */ type: ServerConfigType; /** * Whether this server is enabled. Disabled servers will be skipped during initialization. * @default true */ enabled?: boolean; /** * Connection mode determines how failures to connect are handled. * - 'strict': Connection failures will throw errors and halt initialization. * - 'lenient': Connection failures will be logged but won't stop other servers from connecting. * @default 'lenient' */ connectionMode?: 'strict' | 'lenient'; /** * Timeout in milliseconds for server operations. * @default 60000 (1 minute) */ timeout?: number; } /** * Configuration for a stdio-based MCP server. */ interface StdioServerConfig extends BaseServerConfig { type: 'stdio'; /** * Command to run the server. */ command: string; /** * Arguments to pass to the command. */ args: string[]; /** * Environment variables to set for the command. */ env?: Record; } /** * Configuration for an SSE-based MCP server. */ interface SseServerConfig extends BaseServerConfig { type: 'sse'; /** * URL of the SSE server. */ url: string; /** * Headers to include with requests. */ headers?: Record; } /** * Configuration for a streamable HTTP-based MCP server. */ interface StreamableHttpServerConfig extends BaseServerConfig { type: 'streamable-http'; /** * URL of the streamable HTTP server. */ url: string; /** * Headers to include with requests. */ headers?: Record; } /** * Union type representing any valid MCP server configuration. */ type McpServerConfig = StdioServerConfig | SseServerConfig | StreamableHttpServerConfig; /** * Record mapping server names to their configurations. */ type ServerConfigs = Record; /** * Represents a tool parameter schema. */ interface ToolParameterSchema { type: string; description?: string; [key: string]: any; } /** * Represents a tool parameter definition. */ interface ToolParameterDefinition { [parameterName: string]: ToolParameterSchema; } /** * Represents a tool's parameter definitions and requirements. */ interface ToolParameters { type: string; properties: ToolParameterDefinition; required?: string[]; } /** * Represents a single tool definition. */ interface Tool { description: string; parameters: ToolParameters; } /** * A collection of tools indexed by their names. */ interface ToolSet { [toolName: string]: Tool; } /** * Result of a tool execution. */ type ToolExecutionResult = any; /** * Interface for an MCP client that communicates with a single MCP server. */ interface IMCPClient { /** * Connect to an MCP server using the provided configuration. */ connect(config: McpServerConfig, serverName: string): Promise; /** * Disconnect from the MCP server. */ disconnect(): Promise; /** * Call a tool with the given name and arguments. */ callTool(name: string, args: any): Promise; /** * Get all tools provided by this client. */ getTools(): Promise; /** * List all prompts provided by this client. */ listPrompts(): Promise; /** * Get a prompt by name. */ getPrompt(name: string, args?: any): Promise; /** * List all resources provided by this client. */ listResources(): Promise; /** * Read a resource by URI. */ readResource(uri: string): Promise; /** * Get the connection status of the client. */ getConnectionStatus(): boolean; /** * Get the underlying MCP client instance. */ getClient(): Client | null; /** * Get information about the connected server. */ getServerInfo(): { spawned: boolean; pid: number | null; command: string | null; originalArgs: string[] | null; resolvedArgs: string[] | null; env: Record | null; alias: string | null; }; /** * Get the client instance once connected. */ getConnectedClient(): Promise; } /** * Interface for the MCP Manager that orchestrates multiple MCP clients. */ interface IMCPManager { /** * Register a client with the manager. */ registerClient(name: string, client: IMCPClient): void; /** * Get all available tools from all connected clients. */ getAllTools(): Promise; /** * Get the client that provides a specific tool. */ getToolClient(toolName: string): IMCPClient | undefined; /** * Execute a tool with the given name and arguments. */ executeTool(toolName: string, args: any): Promise; /** * List all available prompts from all connected clients. */ listAllPrompts(): Promise; /** * Get the client that provides a specific prompt. */ getPromptClient(promptName: string): IMCPClient | undefined; /** * Get a prompt by name. */ getPrompt(name: string, args?: any): Promise; /** * List all available resources from all connected clients. */ listAllResources(): Promise; /** * Get the client that provides a specific resource. */ getResourceClient(resourceUri: string): IMCPClient | undefined; /** * Read a resource by URI. */ readResource(uri: string): Promise; /** * Initialize clients from server configurations. */ initializeFromConfig(serverConfigs: ServerConfigs): Promise; /** * Connect to a new MCP server. */ connectServer(name: string, config: McpServerConfig): Promise; /** * Get all registered clients. */ getClients(): Map; /** * Get errors from failed connections. */ getFailedConnections(): { [key: string]: string; }; /** * Disconnect and remove a specific client. */ removeClient(name: string): Promise; /** * Disconnect all clients and clear caches. */ disconnectAll(): Promise; } /** * MCPClient implementation for the Model Context Protocol (MCP) module. * * This file contains the MCPClient class that handles connection management, * transport abstraction, and operations for a single MCP server. */ /** * Implementation of the IMCPClient interface for managing connections to MCP servers. * Supports stdio, SSE, and HTTP transports with comprehensive error handling and timeout management. */ declare class MCPClient implements IMCPClient { private client; private transport; private connected; private serverConfig; private serverName; private logger; private connectionPromise; private quietMode; private serverInfo; constructor(); /** * Enable quiet mode to reduce logging verbosity (useful for CLI mode) */ setQuietMode(quiet: boolean): void; /** * Connect to an MCP server using the provided configuration. */ connect(config: McpServerConfig, serverName: string): Promise; /** * Internal method to perform the actual connection. */ private _performConnection; /** * Create transport based on server configuration. */ private _createTransport; /** * Create stdio transport. */ private _createStdioTransport; /** * Create SSE transport. */ private _createSseTransport; /** * Create streamable HTTP transport. */ private _createStreamableHttpTransport; /** * Connect client to transport with timeout. */ private _connectWithTimeout; /** * Disconnect from the MCP server. */ disconnect(): Promise; /** * Call a tool with the given name and arguments. */ callTool(name: string, args: any): Promise; /** * Get all tools provided by this client. */ getTools(): Promise; /** * List all prompts provided by this client. */ listPrompts(): Promise; /** * Get a prompt by name. */ getPrompt(name: string, args?: any): Promise; /** * List all resources provided by this client. */ listResources(): Promise; /** * Read a resource by URI. */ readResource(uri: string): Promise; /** * Get the connection status of the client. */ getConnectionStatus(): boolean; /** * Get the underlying MCP client instance. */ getClient(): Client | null; /** * Get information about the connected server. */ getServerInfo(): { spawned: boolean; pid: number | null; command: string | null; originalArgs: string[] | null; resolvedArgs: string[] | null; env: Record | null; alias: string | null; }; /** * Get the client instance once connected. */ getConnectedClient(): Promise; /** * Ensure the client is connected before performing operations. */ private _ensureConnected; /** * Get the operation timeout from configuration or default. */ private _getOperationTimeout; /** * Execute a function with timeout. */ private _executeWithTimeout; /** * Resolve command path, handling bundled scripts and relative paths. */ private _resolveCommand; /** * Resolve arguments, performing any necessary path resolution. */ private _resolveArgs; /** * Merge environment variables with current process environment. */ private _mergeEnvironment; /** * Clean up resources and reset state. */ private _cleanup; } interface ServiceEventMap { 'cipher:started': { timestamp: number; version?: string; }; 'cipher:stopped': { timestamp: number; reason?: string; }; 'cipher:error': { error: string; stack?: string; timestamp: number; }; 'cipher:serviceStarted': { serviceType: string; timestamp: number; }; 'cipher:serviceError': { serviceType: string; error: string; timestamp: number; }; 'cipher:allServicesReady': { timestamp: number; services: string[]; }; 'cipher:toolRegistered': { toolName: string; toolType: 'internal' | 'mcp'; timestamp: number; }; 'cipher:toolUnregistered': { toolName: string; toolType: 'internal' | 'mcp'; timestamp: number; }; 'cipher:toolError': { toolName: string; error: string; timestamp: number; }; 'cipher:mcpClientConnected': { clientId: string; serverName: string; timestamp: number; }; 'cipher:mcpClientDisconnected': { clientId: string; serverName: string; reason?: string; timestamp: number; }; 'cipher:mcpClientError': { clientId: string; serverName: string; error: string; timestamp: number; }; 'cipher:memoryOperationStarted': { operation: string; sessionId?: string; timestamp: number; }; 'cipher:memoryOperationCompleted': { operation: string; sessionId?: string; duration: number; timestamp: number; }; 'cipher:memoryOperationFailed': { operation: string; sessionId?: string; error: string; timestamp: number; }; 'cipher:vectorStoreConnected': { provider: string; timestamp: number; }; 'cipher:vectorStoreDisconnected': { provider: string; reason?: string; timestamp: number; }; 'cipher:vectorStoreError': { provider: string; error: string; timestamp: number; }; 'cipher:llmProviderRegistered': { provider: string; timestamp: number; }; 'cipher:llmProviderError': { provider: string; error: string; timestamp: number; }; 'lazy-memory:loading': { componentType: string; timestamp: number; }; 'lazy-memory:loaded': { componentType: string; loadTime: number; timestamp: number; }; 'lazy-memory:error': { componentType: string; error: string; timestamp: number; }; 'lazy-service:loaded': { serviceType: string; timestamp: number; }; 'lazy-service:initialized': { initTime: number; lazyLoadingEnabled: boolean; timestamp: number; }; } interface SessionEventMap { 'session:created': { sessionId: string; timestamp: number; }; 'session:activated': { sessionId: string; timestamp: number; }; 'session:deactivated': { sessionId: string; timestamp: number; }; 'session:expired': { sessionId: string; timestamp: number; }; 'session:deleted': { sessionId: string; timestamp: number; }; 'tool:executionStarted': { toolName: string; toolType: 'internal' | 'mcp'; sessionId: string; executionId: string; timestamp: number; args?: any; }; 'tool:executionCompleted': { toolName: string; toolType: 'internal' | 'mcp'; sessionId: string; executionId: string; duration: number; success: boolean; result?: any; timestamp: number; }; 'tool:executionFailed': { toolName: string; toolType: 'internal' | 'mcp'; sessionId: string; executionId: string; error: string; duration: number; timestamp: number; }; 'llm:thinking': { sessionId: string; messageId: string; timestamp: number; }; 'llm:responseStarted': { sessionId: string; messageId: string; model: string; timestamp: number; }; 'llm:responseChunk': { sessionId: string; messageId: string; chunk: string; timestamp: number; }; 'llm:responseCompleted': { sessionId: string; messageId: string; model: string; tokenCount?: number; duration: number; timestamp: number; response?: string; }; 'llm:responseError': { sessionId: string; messageId: string; model: string; error: string; timestamp: number; }; 'memory:stored': { sessionId: string; type: 'conversation' | 'embedding' | 'knowledge'; size: number; timestamp: number; }; 'memory:retrieved': { sessionId: string; type: 'conversation' | 'embedding' | 'knowledge'; count: number; timestamp: number; }; 'memory:searched': { sessionId: string; query: string; resultCount: number; duration: number; timestamp: number; }; 'conversation:messageAdded': { sessionId: string; messageId: string; role: 'user' | 'assistant' | 'system'; timestamp: number; }; 'conversation:messageUpdated': { sessionId: string; messageId: string; timestamp: number; }; 'conversation:cleared': { sessionId: string; timestamp: number; }; 'context:updated': { sessionId: string; contextSize: number; timestamp: number; }; 'context:truncated': { sessionId: string; removedCount: number; timestamp: number; }; } interface EventMetadata { timestamp: number; sessionId?: string; source?: string; priority?: 'high' | 'normal' | 'low'; tags?: string[]; eventManagerId?: string; } interface EventEnvelope { id: string; type: string; data: T; metadata: EventMetadata; } type EventFilter$1 = (event: EventEnvelope) => boolean; /** * Event Filtering System * * Provides efficient filtering capabilities for events to optimize performance * and enable selective event processing. */ type EventFilter = (event: EventEnvelope) => boolean; interface FilterConfig { name: string; description?: string; enabled: boolean; filter: EventFilter; priority?: number; } interface FilteringStats { totalEventsProcessed: number; totalEventsFiltered: number; filteringRate: number; averageFilteringTime: number; filterStats: Record; } type EventListener = (event: T) => void | Promise; type EventListenerOptions = { signal?: AbortSignal; once?: boolean; priority?: 'high' | 'normal' | 'low'; }; declare class TypedEventEmitter> { private emitter; private readonly maxListeners; private readonly enableLogging; private listenerCount; constructor(options?: { maxListeners?: number; enableLogging?: boolean; }); /** * Emit an event with type safety */ emit(event: K, data: EventMap[K]): void; /** * Add a typed event listener with AbortController support */ on(event: K, listener: EventListener, options?: EventListenerOptions): void; /** * Add a one-time event listener */ once(event: K, listener: EventListener, options?: Omit): void; /** * Remove an event listener */ off(event: K, listener: EventListener): void; /** * Remove all listeners for an event */ removeAllListeners(event?: K): void; /** * Get the number of listeners for an event */ listenerCountFor(event: K): number; /** * Get all event names that have listeners */ eventNames(): (keyof EventMap)[]; /** * Wait for a specific event to be emitted */ waitFor(event: K, options?: { timeout?: number; signal?: AbortSignal; }): Promise; /** * Dispose of the event emitter and clean up resources */ dispose(): void; /** * Wrap listener with error handling and async support */ private wrapListener; } /** * Event Persistence Layer * * Provides persistent storage for events to enable debugging, monitoring, and replay capabilities. */ interface EventPersistenceConfig { enabled: boolean; storageType: 'file' | 'memory' | 'database'; maxEvents?: number; rotationSize?: number; retentionDays?: number; filePath?: string; } interface EventQuery { sessionId?: string; eventType?: string; since?: number; until?: number; limit?: number; offset?: number; } /** * Event persistence manager */ declare class EventPersistence { private storage; private cleanupInterval?; constructor(config: EventPersistenceConfig); store(event: EventEnvelope): Promise; query(query: EventQuery): Promise; getStats(): Promise<{ totalEvents: number; storageSize: number; }>; dispose(): void; } interface ServiceEventBusOptions { enableLogging?: boolean; maxListeners?: number; enablePersistence?: boolean; eventPersistence?: EventPersistence; } declare class ServiceEventBus extends TypedEventEmitter { private readonly instanceId; private readonly startTime; private eventHistory; private readonly enablePersistence; private readonly maxHistorySize; private readonly eventPersistence?; constructor(options?: ServiceEventBusOptions); /** * Emit a service event with metadata and optional persistence */ emitServiceEvent(event: K, data: ServiceEventMap[K], metadata?: Partial): void; /** * Get event history (if persistence is enabled) */ getEventHistory(filter?: { eventType?: keyof ServiceEventMap; since?: number; limit?: number; }): EventEnvelope[]; /** * Get service event bus statistics */ getStatistics(): { instanceId: string; uptime: number; totalEvents: number; eventTypes: Record; activeListeners: Record; }; /** * Clear event history */ clearHistory(): void; /** * Dispose of the service event bus */ dispose(): void; /** * Add event to history with size management */ private addToHistory; /** * Get instance ID */ getInstanceId(): string; /** * Get uptime in milliseconds */ getUptime(): number; } interface SessionEventBusOptions { sessionId: string; enableLogging?: boolean; maxListeners?: number; enablePersistence?: boolean; maxHistorySize?: number; eventPersistence?: EventPersistence; } declare class SessionEventBus extends TypedEventEmitter { private readonly sessionId; private readonly createdAt; private eventHistory; private readonly enablePersistence; private readonly maxHistorySize; private readonly eventPersistence?; private isDisposed; constructor(options: SessionEventBusOptions); /** * Emit a session event with metadata and optional persistence */ emitSessionEvent(event: K, data: SessionEventMap[K], metadata?: Partial): void; /** * Get session event history (if persistence is enabled) */ getEventHistory(filter?: { eventType?: keyof SessionEventMap; since?: number; limit?: number; }): EventEnvelope[]; /** * Get session event bus statistics */ getStatistics(): { sessionId: string; age: number; totalEvents: number; eventTypes: Record; activeListeners: Record; recentActivity: { lastEventTime?: number; eventsInLastMinute: number; eventsInLastHour: number; }; }; /** * Clear event history */ clearHistory(): void; /** * Get session ID */ getSessionId(): string; /** * Get session age in milliseconds */ getAge(): number; /** * Check if session event bus is disposed */ isSessionDisposed(): boolean; /** * Dispose of the session event bus */ dispose(): void; /** * Add event to history with size management */ private addToHistory; /** * Determine if an event should be logged based on its importance */ private shouldLogEvent; /** * Get events matching a pattern */ getEventsByPattern(pattern: RegExp): EventEnvelope[]; /** * Get the most recent event of a specific type */ getLastEvent(eventType: K): EventEnvelope | undefined; /** * Count events of a specific type */ countEvents(eventType: K): number; } interface EventManagerOptions { enableLogging?: boolean; enablePersistence?: boolean; enableFiltering?: boolean; maxServiceListeners?: number; maxSessionListeners?: number; maxSessionHistorySize?: number; sessionCleanupInterval?: number; eventPersistenceConfig?: Partial; } declare class EventManager { private readonly serviceEventBus; private readonly sessionEventBuses; private readonly filterManager; private readonly options; private readonly instanceId; private cleanupInterval?; private isDisposed; private eventPersistence?; constructor(options?: EventManagerOptions); /** * Get or create a session event bus */ getSessionEventBus(sessionId: string): SessionEventBus; /** * Get the service event bus */ getServiceEventBus(): ServiceEventBus; /** * Remove a session event bus */ removeSessionEventBus(sessionId: string): void; /** * Emit a service event */ emitServiceEvent(event: K, data: ServiceEventMap[K]): void; /** * Emit a session event */ emitSessionEvent(sessionId: string, event: K, data: SessionEventMap[K]): void; /** * Get all active session IDs */ getActiveSessionIds(): string[]; /** * Get comprehensive statistics */ getStatistics(): { instanceId: string; uptime: number; totalSessions: number; activeSessions: number; serviceEvents: { totalEvents: number; eventTypes: Record; activeListeners: Record; }; sessionStats: { sessionId: string; age: number; totalEvents: number; recentActivity: { lastEventTime?: number; eventsInLastMinute: number; eventsInLastHour: number; }; }[]; }; /** * Search for events across all session buses */ searchSessionEvents(filter: { sessionId?: string; eventType?: keyof SessionEventMap; since?: number; pattern?: RegExp; limit?: number; }): EventEnvelope[]; /** * Clean up inactive sessions */ private cleanupInactiveSessions; /** * Create a cross-bus event forwarding rule */ createForwardingRule(sessionEventType: K, forwardToService?: boolean, filter?: EventFilter$1): void; /** * Get event manager instance ID */ getInstanceId(): string; /** * Check if event manager is disposed */ isEventManagerDisposed(): boolean; /** * Register an event filter */ registerFilter(config: FilterConfig): void; /** * Unregister an event filter */ unregisterFilter(name: string): boolean; /** * Enable or disable a filter */ setFilterEnabled(name: string, enabled: boolean): void; /** * Get filtering statistics */ getFilteringStats(): FilteringStats; /** * Get list of registered filters */ getFilters(): FilterConfig[]; /** * Setup common filters for typical use cases */ setupCommonFilters(): void; /** * Dispose of the event manager and all resources */ dispose(): void; } /** * MCPManager implementation for the Model Context Protocol (MCP) module. * * This file contains the MCPManager class that orchestrates multiple MCP clients, * provides caching for O(1) lookups, and handles connection strategies. */ /** * Implementation of the IMCPManager interface for orchestrating multiple MCP clients. * Provides O(1) cached lookups, connection management, and error handling strategies. */ declare class MCPManager implements IMCPManager { private clients; private failedConnections; protected logger: Logger; private eventManager?; private quietMode; private toolCache; private toolClientMap; private promptCache; private promptClientMap; private resourceCache; private resourceClientMap; private cacheTimeout; private maxCacheSize; constructor(); /** * Set the event manager for emitting connection lifecycle events */ setEventManager(eventManager: EventManager): void; /** * Enable quiet mode to reduce logging verbosity (useful for CLI mode) */ setQuietMode(quiet: boolean): void; /** * Register a client with the manager. */ registerClient(name: string, client: IMCPClient): void; /** * Get all available tools from all connected clients. */ getAllTools(): Promise; /** * Get the client that provides a specific tool. */ getToolClient(toolName: string): IMCPClient | undefined; /** * Execute a tool with the given name and arguments. */ executeTool(toolName: string, args: any): Promise; /** * List all available prompts from all connected clients. */ listAllPrompts(): Promise; /** * Get the client that provides a specific prompt. */ getPromptClient(promptName: string): IMCPClient | undefined; /** * Get a prompt by name. */ getPrompt(name: string, args?: any): Promise; /** * List all available resources from all connected clients. */ listAllResources(): Promise; /** * Get the client that provides a specific resource. */ getResourceClient(resourceUri: string): IMCPClient | undefined; /** * Read a resource by URI. */ readResource(uri: string): Promise; /** * Initialize clients from server configurations. */ initializeFromConfig(serverConfigs: ServerConfigs): Promise; /** * Connect to a new MCP server. */ connectServer(name: string, config: McpServerConfig): Promise; /** * Get all registered clients. */ getClients(): Map; /** * Get errors from failed connections. */ getFailedConnections(): { [key: string]: string; }; /** * Disconnect and remove a specific client. */ removeClient(name: string): Promise; /** * Disconnect all clients and clear caches. */ disconnectAll(): Promise; /** * Refresh tool cache from all connected clients. */ private _refreshToolCache; /** * Refresh prompt cache from all connected clients. */ private _refreshPromptCache; /** * Refresh resource cache from all connected clients. */ private _refreshResourceCache; /** * Refresh all caches. */ private _refreshAllCaches; /** * Clean up expired cache entries. */ private _cleanupCache; /** * Remove a client from all caches. */ private _removeClientFromCaches; /** * Clear all caches. */ private _clearAllCaches; /** * Update client failure count and connected status. */ private _updateClientFailure; } /** * Constants for the Model Context Protocol (MCP) module. * * This file contains all constant values used throughout the MCP implementation, * including default values, error messages, and configuration constants. */ /** * Default timeout for MCP operations in milliseconds. * Used for all operations if not overridden in the server configuration. */ declare const DEFAULT_TIMEOUT_MS = 60000; /** * Default connection mode for servers. */ declare const DEFAULT_CONNECTION_MODE = "lenient"; /** * Minimum timeout value allowed for operations. */ declare const MIN_TIMEOUT_MS = 5000; /** * Maximum timeout value allowed for operations. */ declare const MAX_TIMEOUT_MS = 300000; /** * Available transport types for MCP servers. */ declare const TRANSPORT_TYPES: { readonly STDIO: "stdio"; readonly SSE: "sse"; readonly STREAMABLE_HTTP: "streamable-http"; }; /** * Available connection modes. */ declare const CONNECTION_MODES: { /** * Strict mode requires the server to successfully connect. * If connection fails, an error will be thrown. */ readonly STRICT: "strict"; /** * Lenient mode allows the server to fail connecting. * If connection fails, a warning will be logged but no error will be thrown. */ readonly LENIENT: "lenient"; }; /** * Error messages used throughout the MCP module. */ declare const ERROR_MESSAGES$2: { CONNECTION_FAILED: string; DISCONNECTION_FAILED: string; NOT_CONNECTED: string; TOOL_EXECUTION_FAILED: string; NO_CLIENT_FOR_TOOL: string; NO_CLIENT_FOR_PROMPT: string; NO_CLIENT_FOR_RESOURCE: string; PROMPT_NOT_FOUND: string; RESOURCE_NOT_FOUND: string; INVALID_CONFIG: string; UNSUPPORTED_SERVER_TYPE: string; CLIENT_ALREADY_REGISTERED: string; MISSING_REQUIRED_SERVERS: string; }; /** * Log message prefixes for the MCP module. */ declare const LOG_PREFIXES$2: { CONNECT: string; TOOL: string; PROMPT: string; RESOURCE: string; MANAGER: string; }; /** * Environment variables that affect the behavior of the MCP module. */ declare const ENV_VARS: { /** * Environment variable to set the global timeout for all MCP operations. */ GLOBAL_TIMEOUT: string; /** * Environment variable to set the default connection mode. */ DEFAULT_CONNECTION_MODE: string; }; /** * Core interfaces for the System Prompt Plugin Architecture * * This module defines the foundational interfaces and types for the * extensible system prompt management system. */ /** * Context information passed to prompt providers for dynamic content generation */ interface ProviderContext { /** Current timestamp */ timestamp: Date; /** User ID or identifier if available */ userId?: string; /** Session identifier */ sessionId?: string; /** Current memory state or relevant memory chunks */ memoryContext?: Record; /** Additional runtime context data */ metadata?: Record; } /** * Configuration options for prompt providers */ interface ProviderConfig { /** Provider name/identifier */ name: string; /** Provider type */ type: ProviderType; /** Execution priority (higher numbers execute first) */ priority: number; /** Whether this provider is enabled */ enabled: boolean; /** Provider-specific configuration */ config?: Record; } /** * Types of prompt providers supported by the system */ declare enum ProviderType { /** Static content that doesn't change */ STATIC = "static", /** Dynamic content generated at runtime */ DYNAMIC = "dynamic", /** Content loaded from external files */ FILE_BASED = "file-based" } /** * Main interface for all prompt providers */ interface PromptProvider { /** Unique identifier for this provider */ readonly id: string; /** Human-readable name */ readonly name: string; /** Provider type */ readonly type: ProviderType; /** Execution priority */ readonly priority: number; /** Whether this provider is currently enabled */ enabled: boolean; /** * Generate prompt content * @param context Runtime context for dynamic content generation * @returns Promise resolving to the generated prompt content */ generateContent(context: ProviderContext): Promise; /** * Validate provider configuration * @param config Configuration to validate * @returns True if configuration is valid */ validateConfig(config: Record): boolean; /** * Initialize the provider with configuration * @param config Provider configuration */ initialize(config: Record): Promise; /** * Clean up resources when provider is destroyed */ destroy(): Promise; } /** * Configuration for the entire prompt management system */ interface SystemPromptConfig { /** List of provider configurations */ providers: ProviderConfig[]; /** Global settings */ settings: { /** Maximum time to wait for all providers (ms) */ maxGenerationTime: number; /** Whether to fail if any provider fails */ failOnProviderError: boolean; /** Separator between provider outputs */ contentSeparator: string; }; } /** * Result from generating system prompt content */ interface PromptGenerationResult { /** The complete generated prompt */ content: string; /** Individual provider results */ providerResults: ProviderResult[]; /** Total generation time in milliseconds */ generationTimeMs: number; /** Whether generation was successful */ success: boolean; /** Any errors that occurred */ errors: Error[]; } /** * Result from a single provider */ interface ProviderResult { /** Provider ID */ providerId: string; /** Generated content */ content: string; /** Generation time for this provider */ generationTimeMs: number; /** Whether this provider succeeded */ success: boolean; /** Error if provider failed */ error?: Error; } /** * Enhanced Prompt Manager * * New plugin-based prompt manager that replaces the legacy PromptManager. * Provides extensible, configurable, and high-performance system prompt generation. */ interface EnhancedPromptManagerOptions { /** Configuration for the prompt manager */ config?: SystemPromptConfig; /** Whether to automatically register built-in generators */ registerBuiltInGenerators?: boolean; /** Custom context to merge with runtime context */ defaultContext?: Partial; } declare class EnhancedPromptManager { private configManager; private providers; private dynamicAndFileProviderConfigs; private defaultContext; private initialized; private llmService; constructor(options?: EnhancedPromptManagerOptions); /** * Set the LLM service reference for use in provider context */ setLLMService(llmService: any): void; /** * Initialize the manager with configuration */ initialize(config?: SystemPromptConfig): Promise; /** * Load configuration from file */ loadConfigFromFile(filePath: string): Promise; /** * Generate complete system prompt */ generateSystemPrompt(runtimeContext?: Partial): Promise; /** * Get current configuration */ getConfig(): SystemPromptConfig; /** * Get all providers (enabled and disabled) */ getProviders(): PromptProvider[]; /** * Get enabled providers sorted by priority */ getEnabledProviders(): PromptProvider[]; /** * Get a specific provider by ID */ getProvider(id: string): PromptProvider | undefined; /** * Enable or disable a provider */ setProviderEnabled(id: string, enabled: boolean): void; /** * Check if manager is initialized */ isInitialized(): boolean; /** * Get performance statistics */ getPerformanceStats(): Promise<{ totalProviders: number; enabledProviders: number; averageGenerationTime: number; lastGenerationResult?: PromptGenerationResult; }>; /** * Destroy the manager and clean up resources */ destroy(): Promise; /** * Initialize built-in generators */ private initializeBuiltInGenerators; /** * Create provider instances from configuration * Only instantiate static providers at startup. * Store dynamic and file-based provider configs for runtime activation. */ private createProviders; /** * Add or update a dynamic or file-based provider at runtime. * If a provider with the same name exists, replace it. * Triggers prompt rebuild. */ addOrUpdateProvider(config: any): Promise; /** * Remove a dynamic or file-based provider at runtime. * Triggers prompt rebuild. */ removeProvider(name: string): Promise; /** * List all providers and their status. */ listProviders(): { id: string; type: string; enabled: boolean; }[]; /** * Destroy all provider instances */ private destroyProviders; /** * Build context by merging default and runtime context */ private buildContext; /** * Execute a function with timeout */ private executeWithTimeout; /** * Ensure manager is initialized */ private ensureInitialized; } declare const AwsConfigSchema: z.ZodObject<{ region: z.ZodOptional; accessKeyId: z.ZodOptional; secretAccessKey: z.ZodOptional; sessionToken: z.ZodOptional; inferenceProfileArn: z.ZodOptional; }, "strip", z.ZodTypeAny, { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }, { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }>; declare const AzureConfigSchema: z.ZodObject<{ endpoint: z.ZodString; deploymentName: z.ZodOptional; }, "strip", z.ZodTypeAny, { endpoint?: string; deploymentName?: string; }, { endpoint?: string; deploymentName?: string; }>; declare const LLMConfigSchema: z.ZodEffects; maxIterations: z.ZodDefault>; baseURL: z.ZodOptional; qwenOptions: z.ZodOptional; thinkingBudget: z.ZodOptional; temperature: z.ZodOptional; top_p: z.ZodOptional; }, "strip", z.ZodTypeAny, { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }, { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }>>; aws: z.ZodOptional; accessKeyId: z.ZodOptional; secretAccessKey: z.ZodOptional; sessionToken: z.ZodOptional; inferenceProfileArn: z.ZodOptional; }, "strip", z.ZodTypeAny, { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }, { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }>>; azure: z.ZodOptional; }, "strip", z.ZodTypeAny, { endpoint?: string; deploymentName?: string; }, { endpoint?: string; deploymentName?: string; }>>; }, "strict", z.ZodTypeAny, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }>, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }>; type LLMConfig = z.infer; type AwsConfig = z.infer; type AzureConfig = z.infer; declare const AgentConfigSchema: z.ZodObject<{ agentCard: z.ZodOptional; description: z.ZodDefault; provider: z.ZodOptional; url: z.ZodDefault; }, "strip", z.ZodTypeAny, { url?: string; organization?: string; }, { url?: string; organization?: string; }>>; version: z.ZodDefault; defaultInputModes: z.ZodDefault>; defaultOutputModes: z.ZodDefault>; skills: z.ZodDefault; examples: z.ZodOptional>; inputModes: z.ZodDefault>>; outputModes: z.ZodDefault>>; }, "strip", z.ZodTypeAny, { description?: string; name?: string; id?: string; tags?: string[]; examples?: string[]; inputModes?: string[]; outputModes?: string[]; }, { description?: string; name?: string; id?: string; tags?: string[]; examples?: string[]; inputModes?: string[]; outputModes?: string[]; }>, "many">>; }, "strict", z.ZodTypeAny, { description?: string; name?: string; version?: string; provider?: { url?: string; organization?: string; }; defaultInputModes?: string[]; defaultOutputModes?: string[]; skills?: { description?: string; name?: string; id?: string; tags?: string[]; examples?: string[]; inputModes?: string[]; outputModes?: string[]; }[]; }, { description?: string; name?: string; version?: string; provider?: { url?: string; organization?: string; }; defaultInputModes?: string[]; defaultOutputModes?: string[]; skills?: { description?: string; name?: string; id?: string; tags?: string[]; examples?: string[]; inputModes?: string[]; outputModes?: string[]; }[]; }>>; systemPrompt: z.ZodString; mcpServers: z.ZodDefault; command: z.ZodString; args: z.ZodArray; env: z.ZodDefault>; enabled: z.ZodDefault; timeout: z.ZodDefault; connectionMode: z.ZodDefault>; }, "strict", z.ZodTypeAny, { type?: "stdio"; enabled?: boolean; command?: string; args?: string[]; env?: Record; timeout?: number; connectionMode?: "strict" | "lenient"; }, { type?: "stdio"; enabled?: boolean; command?: string; args?: string[]; env?: Record; timeout?: number; connectionMode?: "strict" | "lenient"; }>, z.ZodObject<{ type: z.ZodLiteral<"sse">; url: z.ZodString; headers: z.ZodDefault>; enabled: z.ZodDefault; timeout: z.ZodDefault; connectionMode: z.ZodDefault>; }, "strict", z.ZodTypeAny, { type?: "sse"; enabled?: boolean; url?: string; timeout?: number; headers?: Record; connectionMode?: "strict" | "lenient"; }, { type?: "sse"; enabled?: boolean; url?: string; timeout?: number; headers?: Record; connectionMode?: "strict" | "lenient"; }>, z.ZodObject<{ type: z.ZodLiteral<"streamable-http">; url: z.ZodString; headers: z.ZodDefault>; enabled: z.ZodDefault; timeout: z.ZodDefault; connectionMode: z.ZodDefault>; }, "strict", z.ZodTypeAny, { type?: "streamable-http"; enabled?: boolean; url?: string; timeout?: number; headers?: Record; connectionMode?: "strict" | "lenient"; }, { type?: "streamable-http"; enabled?: boolean; url?: string; timeout?: number; headers?: Record; connectionMode?: "strict" | "lenient"; }>]>>>; llm: z.ZodEffects; maxIterations: z.ZodDefault>; baseURL: z.ZodOptional; qwenOptions: z.ZodOptional; thinkingBudget: z.ZodOptional; temperature: z.ZodOptional; top_p: z.ZodOptional; }, "strip", z.ZodTypeAny, { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }, { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }>>; aws: z.ZodOptional; accessKeyId: z.ZodOptional; secretAccessKey: z.ZodOptional; sessionToken: z.ZodOptional; inferenceProfileArn: z.ZodOptional; }, "strip", z.ZodTypeAny, { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }, { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }>>; azure: z.ZodOptional; }, "strip", z.ZodTypeAny, { endpoint?: string; deploymentName?: string; }, { endpoint?: string; deploymentName?: string; }>>; }, "strict", z.ZodTypeAny, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }>, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }>; evalLlm: z.ZodOptional; maxIterations: z.ZodDefault>; baseURL: z.ZodOptional; qwenOptions: z.ZodOptional; thinkingBudget: z.ZodOptional; temperature: z.ZodOptional; top_p: z.ZodOptional; }, "strip", z.ZodTypeAny, { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }, { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }>>; aws: z.ZodOptional; accessKeyId: z.ZodOptional; secretAccessKey: z.ZodOptional; sessionToken: z.ZodOptional; inferenceProfileArn: z.ZodOptional; }, "strip", z.ZodTypeAny, { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }, { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }>>; azure: z.ZodOptional; }, "strip", z.ZodTypeAny, { endpoint?: string; deploymentName?: string; }, { endpoint?: string; deploymentName?: string; }>>; }, "strict", z.ZodTypeAny, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }>, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }, { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }>>; embedding: z.ZodOptional; apiKey: z.ZodOptional; model: z.ZodDefault>; baseUrl: z.ZodOptional; organization: z.ZodOptional; dimensions: z.ZodOptional; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "openai"; apiKey?: string; model?: "text-embedding-3-small" | "text-embedding-3-large" | "text-embedding-ada-002"; baseUrl?: string; organization?: string; dimensions?: number; timeout?: number; maxRetries?: number; }, { type?: "openai"; apiKey?: string; model?: "text-embedding-3-small" | "text-embedding-3-large" | "text-embedding-ada-002"; baseUrl?: string; organization?: string; dimensions?: number; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"gemini">; apiKey: z.ZodOptional; model: z.ZodDefault>; baseUrl: z.ZodOptional; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "gemini"; apiKey?: string; model?: "text-embedding-004" | "gemini-embedding-001"; baseUrl?: string; timeout?: number; maxRetries?: number; }, { type?: "gemini"; apiKey?: string; model?: "text-embedding-004" | "gemini-embedding-001"; baseUrl?: string; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"ollama">; baseUrl: z.ZodDefault; model: z.ZodDefault; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "ollama"; model?: string; baseUrl?: string; timeout?: number; maxRetries?: number; }, { type?: "ollama"; model?: string; baseUrl?: string; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"voyage">; apiKey: z.ZodOptional; model: z.ZodDefault>; baseUrl: z.ZodOptional; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "voyage"; apiKey?: string; model?: "voyage-3-large" | "voyage-3" | "voyage-2"; baseUrl?: string; timeout?: number; maxRetries?: number; }, { type?: "voyage"; apiKey?: string; model?: "voyage-3-large" | "voyage-3" | "voyage-2"; baseUrl?: string; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"qwen">; apiKey: z.ZodOptional; model: z.ZodDefault>; baseUrl: z.ZodOptional; dimensions: z.ZodDefault>; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "qwen"; apiKey?: string; model?: "text-embedding-v3"; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; }, { type?: "qwen"; apiKey?: string; model?: "text-embedding-v3"; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"aws-bedrock">; model: z.ZodDefault>; region: z.ZodOptional; accessKeyId: z.ZodOptional; secretAccessKey: z.ZodOptional; sessionToken: z.ZodOptional; dimensions: z.ZodDefault>; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "aws-bedrock"; model?: "amazon.titan-embed-text-v2:0" | "cohere.embed-english-v3"; dimensions?: number; timeout?: number; maxRetries?: number; region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; }, { type?: "aws-bedrock"; model?: "amazon.titan-embed-text-v2:0" | "cohere.embed-english-v3"; dimensions?: number; timeout?: number; maxRetries?: number; region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; }>, z.ZodObject<{ type: z.ZodLiteral<"lmstudio">; baseUrl: z.ZodDefault; model: z.ZodDefault; dimensions: z.ZodOptional; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "lmstudio"; model?: string; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; }, { type?: "lmstudio"; model?: string; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; }>]>, z.ZodObject<{ disabled: z.ZodBoolean; }, "strip", z.ZodTypeAny, { disabled?: boolean; }, { disabled?: boolean; }>, z.ZodBoolean, z.ZodNull]>>; sessions: z.ZodDefault; sessionTTL: z.ZodDefault; }, "strip", z.ZodTypeAny, { maxSessions?: number; sessionTTL?: number; }, { maxSessions?: number; sessionTTL?: number; }>>; eventPersistence: z.ZodOptional; storageType: z.ZodDefault>; maxEvents: z.ZodOptional; rotationSize: z.ZodOptional; retentionDays: z.ZodOptional; filePath: z.ZodOptional; }, "strip", z.ZodTypeAny, { enabled?: boolean; storageType?: "file" | "memory" | "database"; maxEvents?: number; rotationSize?: number; retentionDays?: number; filePath?: string; }, { enabled?: boolean; storageType?: "file" | "memory" | "database"; maxEvents?: number; rotationSize?: number; retentionDays?: number; filePath?: string; }>>; }, "strict", z.ZodTypeAny, { embedding?: boolean | { type?: "openai"; apiKey?: string; model?: "text-embedding-3-small" | "text-embedding-3-large" | "text-embedding-ada-002"; baseUrl?: string; organization?: string; dimensions?: number; timeout?: number; maxRetries?: number; } | { type?: "gemini"; apiKey?: string; model?: "text-embedding-004" | "gemini-embedding-001"; baseUrl?: string; timeout?: number; maxRetries?: number; } | { type?: "ollama"; model?: string; baseUrl?: string; timeout?: number; maxRetries?: number; } | { type?: "voyage"; apiKey?: string; model?: "voyage-3-large" | "voyage-3" | "voyage-2"; baseUrl?: string; timeout?: number; maxRetries?: number; } | { type?: "qwen"; apiKey?: string; model?: "text-embedding-v3"; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; } | { type?: "aws-bedrock"; model?: "amazon.titan-embed-text-v2:0" | "cohere.embed-english-v3"; dimensions?: number; timeout?: number; maxRetries?: number; region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; } | { type?: "lmstudio"; model?: string; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; } | { disabled?: boolean; }; eventPersistence?: { enabled?: boolean; storageType?: "file" | "memory" | "database"; maxEvents?: number; rotationSize?: number; retentionDays?: number; filePath?: string; }; agentCard?: { description?: string; name?: string; version?: string; provider?: { url?: string; organization?: string; }; defaultInputModes?: string[]; defaultOutputModes?: string[]; skills?: { description?: string; name?: string; id?: string; tags?: string[]; examples?: string[]; inputModes?: string[]; outputModes?: string[]; }[]; }; systemPrompt?: string; mcpServers?: Record; timeout?: number; connectionMode?: "strict" | "lenient"; } | { type?: "sse"; enabled?: boolean; url?: string; timeout?: number; headers?: Record; connectionMode?: "strict" | "lenient"; } | { type?: "streamable-http"; enabled?: boolean; url?: string; timeout?: number; headers?: Record; connectionMode?: "strict" | "lenient"; }>; llm?: { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }; evalLlm?: { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }; sessions?: { maxSessions?: number; sessionTTL?: number; }; }, { embedding?: boolean | { type?: "openai"; apiKey?: string; model?: "text-embedding-3-small" | "text-embedding-3-large" | "text-embedding-ada-002"; baseUrl?: string; organization?: string; dimensions?: number; timeout?: number; maxRetries?: number; } | { type?: "gemini"; apiKey?: string; model?: "text-embedding-004" | "gemini-embedding-001"; baseUrl?: string; timeout?: number; maxRetries?: number; } | { type?: "ollama"; model?: string; baseUrl?: string; timeout?: number; maxRetries?: number; } | { type?: "voyage"; apiKey?: string; model?: "voyage-3-large" | "voyage-3" | "voyage-2"; baseUrl?: string; timeout?: number; maxRetries?: number; } | { type?: "qwen"; apiKey?: string; model?: "text-embedding-v3"; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; } | { type?: "aws-bedrock"; model?: "amazon.titan-embed-text-v2:0" | "cohere.embed-english-v3"; dimensions?: number; timeout?: number; maxRetries?: number; region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; } | { type?: "lmstudio"; model?: string; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; } | { disabled?: boolean; }; eventPersistence?: { enabled?: boolean; storageType?: "file" | "memory" | "database"; maxEvents?: number; rotationSize?: number; retentionDays?: number; filePath?: string; }; agentCard?: { description?: string; name?: string; version?: string; provider?: { url?: string; organization?: string; }; defaultInputModes?: string[]; defaultOutputModes?: string[]; skills?: { description?: string; name?: string; id?: string; tags?: string[]; examples?: string[]; inputModes?: string[]; outputModes?: string[]; }[]; }; systemPrompt?: string; mcpServers?: Record; timeout?: number; connectionMode?: "strict" | "lenient"; } | { type?: "sse"; enabled?: boolean; url?: string; timeout?: number; headers?: Record; connectionMode?: "strict" | "lenient"; } | { type?: "streamable-http"; enabled?: boolean; url?: string; timeout?: number; headers?: Record; connectionMode?: "strict" | "lenient"; }>; llm?: { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }; evalLlm?: { aws?: { region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; inferenceProfileArn?: string; }; apiKey?: string; model?: string; provider?: string; azure?: { endpoint?: string; deploymentName?: string; }; maxIterations?: number; baseURL?: string; qwenOptions?: { enableThinking?: boolean; thinkingBudget?: number; temperature?: number; top_p?: number; }; }; sessions?: { maxSessions?: number; sessionTTL?: number; }; }>; type AgentConfig = z.input; type ValidationErrorType = 'missing_api_key' | 'invalid_model' | 'invalid_provider' | 'incompatible_model_provider' | 'unsupported_router' | 'invalid_base_url' | 'invalid_max_tokens' | 'schema_validation' | 'general'; interface ValidationError { type: ValidationErrorType; message: string; field?: string; provider?: string; model?: string; router?: string; suggestedAction?: string; } interface McpServerValidationResult { isValid: boolean; errors: ValidationError[]; warnings: string[]; config: McpServerConfig | undefined; } interface SessionOverride { /** Override LLM config for this session */ llm?: Partial; /** Override evaluation LLM config for this session */ evalLlm?: Partial; } declare class MemAgentStateManager { private runtimeConfig; private readonly baselineConfig; private sessionOverrides; constructor(staticConfig: AgentConfig); addMcpServer(serverName: string, serverConfig: McpServerConfig): McpServerValidationResult; removeMcpServer(serverName: string): void; getRuntimeConfig(sessionId?: string): Readonly; getLLMConfig(sessionId?: string): Readonly; /** * Get evaluation LLM configuration with fallback to main LLM config * Used for evaluation tasks that typically require non-thinking models */ getEvalLLMConfig(sessionId?: string): Readonly; /** * Update LLM configuration globally or for a specific session */ updateLLMConfig(newConfig: Partial, sessionId?: string): void; /** * Remove session-specific LLM configuration override */ clearSessionLLMOverride(sessionId: string): void; /** * Get all active session overrides (for debugging/inspection) */ getSessionOverrides(): Map; } /** * Image data interface */ interface ImageData { image: string | Uint8Array | Buffer | ArrayBuffer | URL; mimeType?: string; } /** * Text segment interface */ interface TextSegment { type: 'text'; text: string; } /** * Image segment interface */ interface ImageSegment extends ImageData { type: 'image'; } /** * Internal message interface */ interface InternalMessage { role: 'system' | 'user' | 'assistant' | 'tool'; content: string | null | Array; toolCalls?: Array<{ id: string; type: 'function'; function: { name: string; arguments: string; }; }>; toolCallId?: string; name?: string; } interface IMessageFormatter { /** * Format a single message into the specific structure of target LLM API. * This method always returns an array for interface compatibility. * * @param message - The message to format. * @param systemPrompt - Optional system prompt to include. * @returns Array of formatted messages. */ format(message: Readonly, systemPrompt?: string | null): any[]; /** * Parse the response from the LLM into a list of internal messages * @param response - The response from the LLM * @returns A list of internal messages */ parseResponse(response: any): InternalMessage[]; /** * Parse the stream response from the LLM into a list of internal messages * @param response - The stream response from the LLM * @returns A list of internal messages */ parseStreamResponse?(response: any): Promise; } /** * Enhanced message interface with compression metadata */ interface EnhancedInternalMessage extends InternalMessage { priority?: 'critical' | 'high' | 'normal' | 'low'; preserveInCompression?: boolean; tokenCount?: number; timestamp?: number; messageId?: string; } /** * Compression result interface */ interface CompressionResult { compressedMessages: EnhancedInternalMessage[]; removedMessages: EnhancedInternalMessage[]; originalTokenCount: number; compressedTokenCount: number; compressionRatio: number; strategy: string; timestamp: number; } /** * Compression levels based on token usage */ declare enum CompressionLevel { NONE = 0, WARNING = 1, SOFT = 2, HARD = 3, EMERGENCY = 4 } interface IConversationHistoryProvider { getHistory(sessionId: string, limit?: number): Promise; saveMessage(sessionId: string, message: InternalMessage): Promise; clearHistory(sessionId: string): Promise; } declare class ContextManager { private promptManager; private formatter; private historyProvider; private sessionId; private messages; private tokenizer?; private compressionStrategy?; private enableCompression; private currentTokenCount; private compressionHistory; private lastCompressionCheck; private readonly compressionConfig; private fallbackToMemory; constructor(formatter: IMessageFormatter, promptManager: EnhancedPromptManager, historyProvider: IConversationHistoryProvider | undefined, sessionId: string | undefined); getSystemPrompt(): Promise; addMessage(message: InternalMessage): Promise; restoreHistory(): Promise; addUserMessage(textContent: string, imageData?: ImageData): Promise; addAssistantMessage(content: string | null, toolCalls?: InternalMessage['toolCalls']): Promise; addToolResult(toolCallId: string, name: string, result: any): Promise; getFormattedMessage(_message: InternalMessage): Promise; getAllFormattedMessages(includeSystemMessage?: boolean): Promise; processLLMStreamResponse(response: any): Promise; processLLMResponse(response: any): Promise; getRawMessages(): InternalMessage[]; /** * @deprecated Use getRawMessagesAsync() for persistent storage support */ getRawMessagesSync(): InternalMessage[]; getRawMessagesAsync(): Promise; restoreHistoryPersistent(): Promise; configureCompression(provider: string, model?: string, contextWindow?: number): Promise; getCompressionLevel(): CompressionLevel; getTokenStats(): { currentTokens: number; maxTokens: number; utilization: number; compressionLevel: CompressionLevel; compressionHistory: number; }; forceCompression(): Promise; private validateMessage; private validateUserMessage; private validateAssistantMessage; private validateToolMessage; private validateSystemMessage; private isValidToolCalls; private storeMessage; private shouldUsePersistentStorage; private buildUserMessageContent; private formatToolResultContent; private processMessages; private createTokenizer; private createCompressionStrategy; private updateTokenCount; private calculateMessageTokens; private extractTextFromMessage; private checkAndCompress; private shouldCheckCompression; private calculateUtilization; private logCompressionWarningIfNeeded; private performCompression; private enhanceMessagesForCompression; private calculateTargetTokenCount; private applyCompressionResult; private updateCompressionHistory; /** * Validates and repairs message flow to ensure OpenAI compatibility. * OpenAI requires that tool messages always follow assistant messages with tool_calls. * This method removes orphaned tool messages and warns about inconsistencies. */ private validateAndRepairMessageFlow; /** * Validates that a tool message is a valid response to the given assistant message. */ private isValidToolResponse; } /** * The LLMService interface provides a contract for interacting with an LLM service. * It defines methods for generating text, retrieving available tools, and retrieving the service configuration. */ interface ILLMService { generate(userInput: string, imageData?: ImageData, stream?: boolean): Promise; directGenerate(userInput: string, systemPrompt?: string): Promise; getAllTools(): Promise; getConfig(): LLMServiceConfig; } /** * The LLMServiceConfig interface defines the configuration for an LLM service. * It includes the provider and model information. */ type LLMServiceConfig = { provider: string; model: string; }; /** * Embedding Backend Types and Interfaces * * Core type definitions for the embedding system backends. * Provides the fundamental interfaces that all embedding providers must implement. * * @module embedding/backend/types */ /** * Core interface for embedding providers * * All embedding backends must implement this interface to provide * consistent embedding functionality across different providers. */ interface Embedder { /** * Generate embedding for a single text input * * @param text - The text to embed * @returns Promise resolving to the embedding vector */ embed(text: string): Promise; /** * Generate embeddings for multiple text inputs in batch * * @param texts - Array of texts to embed * @returns Promise resolving to array of embedding vectors */ embedBatch(texts: string[]): Promise; /** * Get the dimension of embeddings produced by this embedder * * @returns The vector dimension */ getDimension(): number; /** * Get the configuration used by this embedder * * @returns The embedder configuration */ getConfig(): EmbeddingConfig$1; /** * Check if the embedder is healthy and can process requests * * @returns Promise resolving to health status */ isHealthy(): Promise; /** * Clean up resources and close connections */ disconnect(): Promise; } /** * Base configuration interface for all embedding providers */ interface EmbeddingConfig$1 { /** The embedding provider type */ type: string; /** API key for the provider */ apiKey?: string; /** Model name to use for embeddings */ model?: string; /** Base URL for the provider API */ baseUrl?: string; /** Request timeout in milliseconds */ timeout?: number; /** Maximum number of retry attempts */ maxRetries?: number; /** Provider-specific options */ options?: Record; } /** * OpenAI-specific embedding configuration */ interface OpenAIEmbeddingConfig extends EmbeddingConfig$1 { type: 'openai'; model?: 'text-embedding-3-small' | 'text-embedding-3-large' | 'text-embedding-ada-002'; /** Organization ID for OpenAI API */ organization?: string; /** Custom dimensions for embedding-3 models */ dimensions?: number; } /** * Gemini-specific embedding configuration */ interface GeminiEmbeddingConfig extends EmbeddingConfig$1 { type: 'gemini'; model?: 'text-embedding-004' | 'gemini-embedding-001' | 'embedding-001'; /** Custom dimensions for Gemini models */ dimensions?: number; } /** * Ollama-specific embedding configuration */ interface OllamaEmbeddingConfig extends EmbeddingConfig$1 { type: 'ollama'; model?: 'nomic-embed-text' | 'all-minilm' | 'mxbai-embed-large' | string; /** Custom dimensions if supported by the model */ dimensions?: number; } /** * Voyage-specific embedding configuration */ interface VoyageEmbeddingConfig extends EmbeddingConfig$1 { type: 'voyage'; model?: 'voyage-3-large' | 'voyage-3' | 'voyage-2'; } /** * Qwen-specific embedding configuration */ interface QwenEmbeddingConfig extends EmbeddingConfig$1 { type: 'qwen'; model?: 'text-embedding-v3'; /** Custom dimensions for Qwen models */ dimensions?: 1024 | 768 | 512; } /** * AWS Bedrock-specific embedding configuration */ interface AWSBedrockEmbeddingConfig extends EmbeddingConfig$1 { type: 'aws-bedrock'; model?: 'amazon.titan-embed-text-v2:0' | 'cohere.embed-english-v3'; region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; /** Custom dimensions for Titan V2 */ dimensions?: 1024 | 512 | 256; } /** * LM Studio-specific embedding configuration */ interface LMStudioEmbeddingConfig extends EmbeddingConfig$1 { type: 'lmstudio'; model?: 'nomic-embed-text-v1.5' | 'text-embedding-nomic-embed-text-v1.5' | string; /** Base URL for LM Studio server, defaults to http://localhost:1234/v1 */ baseUrl?: string; /** Custom dimensions if supported by the model */ dimensions?: number; } /** * Union type for all supported backend configurations */ type BackendConfig$3 = OpenAIEmbeddingConfig | GeminiEmbeddingConfig | OllamaEmbeddingConfig | VoyageEmbeddingConfig | QwenEmbeddingConfig | AWSBedrockEmbeddingConfig | LMStudioEmbeddingConfig; /** * Embedding Configuration Schema and Utilities * * This module provides Zod schemas for validating embedding configurations * and utilities for parsing configurations from environment variables. */ /** * Main embedding configuration schema */ declare const EmbeddingConfigSchema: z.ZodUnion<[z.ZodObject<{ type: z.ZodLiteral<"openai">; apiKey: z.ZodOptional; model: z.ZodDefault>; baseUrl: z.ZodOptional; organization: z.ZodOptional; dimensions: z.ZodOptional; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "openai"; apiKey?: string; model?: "text-embedding-3-small" | "text-embedding-3-large" | "text-embedding-ada-002"; baseUrl?: string; organization?: string; dimensions?: number; timeout?: number; maxRetries?: number; }, { type?: "openai"; apiKey?: string; model?: "text-embedding-3-small" | "text-embedding-3-large" | "text-embedding-ada-002"; baseUrl?: string; organization?: string; dimensions?: number; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"gemini">; apiKey: z.ZodOptional; model: z.ZodDefault>; baseUrl: z.ZodOptional; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "gemini"; apiKey?: string; model?: "text-embedding-004" | "gemini-embedding-001"; baseUrl?: string; timeout?: number; maxRetries?: number; }, { type?: "gemini"; apiKey?: string; model?: "text-embedding-004" | "gemini-embedding-001"; baseUrl?: string; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"ollama">; baseUrl: z.ZodDefault; model: z.ZodDefault; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "ollama"; model?: string; baseUrl?: string; timeout?: number; maxRetries?: number; }, { type?: "ollama"; model?: string; baseUrl?: string; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"voyage">; apiKey: z.ZodOptional; model: z.ZodDefault>; baseUrl: z.ZodOptional; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "voyage"; apiKey?: string; model?: "voyage-3-large" | "voyage-3" | "voyage-2"; baseUrl?: string; timeout?: number; maxRetries?: number; }, { type?: "voyage"; apiKey?: string; model?: "voyage-3-large" | "voyage-3" | "voyage-2"; baseUrl?: string; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"qwen">; apiKey: z.ZodOptional; model: z.ZodDefault>; baseUrl: z.ZodOptional; dimensions: z.ZodDefault>; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "qwen"; apiKey?: string; model?: "text-embedding-v3"; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; }, { type?: "qwen"; apiKey?: string; model?: "text-embedding-v3"; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; }>, z.ZodObject<{ type: z.ZodLiteral<"aws-bedrock">; model: z.ZodDefault>; region: z.ZodOptional; accessKeyId: z.ZodOptional; secretAccessKey: z.ZodOptional; sessionToken: z.ZodOptional; dimensions: z.ZodDefault>; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "aws-bedrock"; model?: "amazon.titan-embed-text-v2:0" | "cohere.embed-english-v3"; dimensions?: number; timeout?: number; maxRetries?: number; region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; }, { type?: "aws-bedrock"; model?: "amazon.titan-embed-text-v2:0" | "cohere.embed-english-v3"; dimensions?: number; timeout?: number; maxRetries?: number; region?: string; accessKeyId?: string; secretAccessKey?: string; sessionToken?: string; }>, z.ZodObject<{ type: z.ZodLiteral<"lmstudio">; baseUrl: z.ZodDefault; model: z.ZodDefault; dimensions: z.ZodOptional; timeout: z.ZodDefault; maxRetries: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "lmstudio"; model?: string; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; }, { type?: "lmstudio"; model?: string; baseUrl?: string; dimensions?: number; timeout?: number; maxRetries?: number; }>]>; type EmbeddingConfig = z.infer; /** * Embedding Manager Module * * Provides lifecycle management, health monitoring, and connection management * for embedding services. Manages multiple embedder instances and provides * centralized monitoring and cleanup capabilities. * * @module embedding/manager */ /** * Simple session-specific embedding state */ declare class SessionEmbeddingState { private disabled; private disabledReason; disableForSession(reason: string): void; isDisabled(): boolean; getDisabledReason(): string; } /** * Health check result for an embedder instance */ interface HealthCheckResult$3 { /** Whether the embedder is healthy */ healthy: boolean; /** Provider type */ provider: string; /** Model being used */ model: string; /** Embedding dimension */ dimension?: number; /** Response time in milliseconds */ responseTime?: number; /** Error message if unhealthy */ error?: string; /** Timestamp of the health check */ timestamp: Date; } /** * Information about an embedder instance */ interface EmbedderInfo { /** Unique identifier for this embedder */ id: string; /** Provider type */ provider: string; /** Model being used */ model: string; /** Embedding dimension */ dimension: number; /** Configuration used */ config: BackendConfig$3; /** Creation timestamp */ createdAt: Date; /** Last health check result */ lastHealthCheck?: HealthCheckResult$3; } /** * Statistics about embedding operations */ interface EmbeddingStats { /** Total number of single embed operations */ totalEmbeds: number; /** Total number of batch embed operations */ totalBatchEmbeds: number; /** Total number of texts processed */ totalTexts: number; /** Total processing time in milliseconds */ totalProcessingTime: number; /** Number of successful operations */ successfulOperations: number; /** Number of failed operations */ failedOperations: number; /** Average processing time per operation */ averageProcessingTime: number; } /** * Embedding Manager * * Manages the lifecycle of embedding instances, providing centralized * health monitoring, statistics collection, and resource cleanup. */ declare class EmbeddingManager { private embedders; private embedderInfo; private sessionState; constructor(); /** * Create and register an embedder instance * * @param config - Embedding configuration * @param id - Optional custom ID for the embedder * @returns Promise resolving to embedder instance and info */ createEmbedder(config: BackendConfig$3, id?: string): Promise<{ embedder: Embedder; info: EmbedderInfo; }>; /** * Create and register an embedder from YAML configuration * * @param config - Embedding configuration from YAML * @param id - Optional custom ID for the embedder * @returns Promise resolving to embedder instance and info, or null */ createEmbedderFromConfig(config: EmbeddingConfig, id?: string): Promise<{ embedder: Embedder; info: EmbedderInfo; } | null>; /** * Handle runtime embedding failure and disable globally if needed * * This method is called when any embedding-related tool fails. * It immediately disables embeddings globally to prevent further failures * and allow the application to continue in chat-only mode. */ handleRuntimeFailure(error: Error, provider: string): void; /** * Create embedder from environment variables * * @param id - Optional custom ID for the embedder * @returns Promise resolving to embedder instance and info, or null */ createEmbedderFromEnv(id?: string): Promise<{ embedder: Embedder; info: EmbedderInfo; } | null>; /** * Get embedder instance by ID * * @param id - Embedder ID * @returns Embedder instance or undefined */ getEmbedder(id: string): Embedder | undefined; /** * Get embedder information by ID * * @param id - Embedder ID * @returns Embedder information or undefined */ getEmbedderInfo(id: string): EmbedderInfo | undefined; /** * Get all registered embedders * * @returns Map of embedder ID to embedder instance */ getAllEmbedders(): Map; /** * Get all embedder information * * @returns Map of embedder ID to embedder information */ getAllEmbedderInfo(): Map; /** * Remove and disconnect an embedder * * @param id - Embedder ID * @returns Promise resolving to true if removed, false if not found */ removeEmbedder(id: string): Promise; /** * Perform health check on a specific embedder * * @param id - Embedder ID * @returns Promise resolving to health check result */ checkHealth(id: string): Promise; /** * Perform health check on all embedders * * @returns Promise resolving to map of embedder ID to health check result */ checkAllHealth(): Promise>; /** * Start periodic health checks (simplified - no automatic scheduling) * * @param intervalMs - Health check interval in milliseconds (default: 5 minutes) */ startHealthChecks(_intervalMs?: number): void; /** * Stop periodic health checks (simplified - no automatic scheduling) */ stopHealthChecks(): void; /** * Get current statistics (simplified - basic stats only) * * @returns Current embedding statistics */ getStats(): EmbeddingStats; /** * Reset statistics (simplified - no-op) */ resetStats(): void; /** * Update statistics (simplified - no-op) */ private updateStats; /** * Get embedding status for all embedders */ getEmbeddingStatus(): Record; /** * Check if embeddings are available for this session */ hasAvailableEmbeddings(): boolean; /** * Get session embedding state */ getSessionState(): SessionEmbeddingState; /** * Disconnect all embedders and cleanup */ disconnect(): Promise; /** * Generate a unique ID for embedders */ private generateId; } /** * Vector Store Interface * * Defines the contract for vector storage implementations. * Vector stores are optimized for similarity search over high-dimensional vectors. * * Implementations can include: * - Qdrant: High-performance vector similarity search engine * - Pinecone: Managed vector database service * - Weaviate: Open-source vector search engine * - In-Memory: Fast local storage for development/testing * * @module vector_storage/backend/vector-store */ /** * VectorStore Interface * * Provides a unified API for different vector storage implementations. * All methods are asynchronous to support both local and network-based backends. * * @example * ```typescript * class QdrantBackend implements VectorStore { * async search(query: number[], limit?: number): Promise { * const results = await this.client.search(this.collectionName, { * vector: query, * limit: limit || 10 * }); * return results.map(this.formatResult); * } * // ... other methods * } * ``` */ interface VectorStore { /** * Insert vectors with their metadata * * @param vectors - Array of embedding vectors * @param ids - Array of unique integer identifiers for each vector * @param payloads - Array of metadata objects for each vector * @throws {VectorDimensionError} If vector dimensions don't match configuration * @throws {VectorStoreError} If insertion fails * * @example * ```typescript * await store.insert( * [embedding1, embedding2], * [1, 2], * [{ title: 'Doc 1' }, { title: 'Doc 2' }] * ); * ``` */ insert(vectors: number[][], ids: number[], payloads: Record[]): Promise; /** * Search for similar vectors * * @param query - Query vector to search for * @param limit - Maximum number of results to return * @param filters - Optional metadata filters * @returns Array of search results sorted by similarity * @throws {VectorDimensionError} If query dimension doesn't match configuration * * @example * ```typescript * const results = await store.search(queryVector, 5, { * category: 'technical', * date: { gte: startDate } * }); * ``` */ search(query: number[], limit?: number, filters?: SearchFilters): Promise; /** * Retrieve a specific vector by ID * * @param vectorId - The unique integer identifier of the vector * @returns The vector result or null if not found * * @example * ```typescript * const vector = await store.get(123); * if (vector) { * console.log(vector.payload); * } * ``` */ get(vectorId: number): Promise; /** * Update a vector and its metadata * * @param vectorId - The unique integer identifier of the vector * @param vector - The new embedding vector * @param payload - The new metadata * @throws {VectorDimensionError} If vector dimension doesn't match configuration * * @example * ```typescript * await store.update(123, newEmbedding, { * title: 'Updated Title', * modified_at: Date.now() * }); * ``` */ update(vectorId: number, vector: number[], payload: Record): Promise; /** * Delete a vector * * @param vectorId - The unique integer identifier of the vector to delete * * @example * ```typescript * await store.delete(123); * ``` */ delete(vectorId: number): Promise; /** * Delete the entire collection * * WARNING: This will permanently delete all vectors in the collection. * * @example * ```typescript * // Use with caution! * await store.deleteCollection(); * ``` */ deleteCollection(): Promise; /** * List vectors with optional filtering * * @param filters - Optional metadata filters * @param limit - Maximum number of results * @returns Tuple of [results, total count] * * @example * ```typescript * const [vectors, totalCount] = await store.list( * { category: 'documents' }, * 100 * ); * console.log(`Found ${vectors.length} of ${totalCount} total`); * ``` */ list(filters?: SearchFilters, limit?: number): Promise<[VectorStoreResult[], number]>; /** * Establishes connection to the vector store backend * * Should be called before performing any operations. * Implementations should handle reconnection logic internally. * * @throws {VectorStoreConnectionError} If connection fails * * @example * ```typescript * const store = new QdrantBackend(config); * await store.connect(); * // Now ready to use * ``` */ connect(): Promise; /** * Gracefully closes the connection to the vector store * * Should clean up resources and close any open connections. * After disconnect, connect() must be called again before use. * * @example * ```typescript * // Clean shutdown * await store.disconnect(); * ``` */ disconnect(): Promise; /** * Checks if the backend is currently connected and ready * * @returns true if connected and operational, false otherwise * * @example * ```typescript * if (!store.isConnected()) { * await store.connect(); * } * ``` */ isConnected(): boolean; /** * Returns the backend type identifier * * Useful for logging, monitoring, and conditional logic based on backend type. * * @returns Backend type string (e.g., 'qdrant', 'pinecone', 'in-memory') * * @example * ```typescript * console.log(`Using ${store.getBackendType()} for vector storage`); * ``` */ getBackendType(): string; /** * Get the configured vector dimension * * @returns The dimension of vectors this store expects * * @example * ```typescript * const dim = store.getDimension(); * console.log(`Store configured for ${dim}-dimensional vectors`); * ``` */ getDimension(): number; /** * Get the collection name * * @returns The name of the collection this store operates on * * @example * ```typescript * console.log(`Operating on collection: ${store.getCollectionName()}`); * ``` */ getCollectionName(): string; } /** * Vector Storage Configuration Module * * Defines the configuration schemas for the vector storage system using Zod for * runtime validation and type safety. Supports multiple backend types with * different configuration requirements. * * The vector storage system provides similarity search capabilities: * - Vector Backend: For similarity search over embeddings * * Supported backends: * - In-Memory: Fast local storage for development/testing * - Qdrant: High-performance vector similarity search engine * - Milvus: Open-source vector database with horizontal scaling * - ChromaDB: Developer-friendly open-source embedding database * - Pinecone: Managed vector database service * - Weaviate: Open-source vector search engine (planned) * * @module vector_storage/config */ /** * Backend Configuration Union Schema * * Discriminated union of all supported backend configurations. * Uses the 'type' field to determine which configuration schema to apply. * * Includes custom validation to ensure backends have required connection info. */ declare const BackendConfigSchema$2: z.ZodEffects; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"in-memory">; /** Maximum number of vectors to store (prevents memory overflow) */ maxVectors: z.ZodDefault; }, "strict", z.ZodTypeAny, { options?: Record; type?: "in-memory"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; maxVectors?: number; }, { options?: Record; type?: "in-memory"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; maxVectors?: number; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"qdrant">; /** Qdrant connection URL (http://...) - overrides individual params if provided */ url: z.ZodOptional; /** Qdrant server hostname */ host: z.ZodOptional; /** Qdrant REST API port (default: 6333) */ port: z.ZodOptional>; /** Qdrant API key for authentication */ apiKey: z.ZodOptional; /** Store vectors on disk (for large datasets) */ onDisk: z.ZodOptional; /** Path for local Qdrant storage (if not using remote server) */ path: z.ZodOptional; /** Distance metric for similarity search */ distance: z.ZodOptional>>; }, "strict", z.ZodTypeAny, { path?: string; options?: Record; type?: "qdrant"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; collectionName?: string; dimension?: number; onDisk?: boolean; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; }, { path?: string; options?: Record; type?: "qdrant"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; collectionName?: string; dimension?: number; onDisk?: boolean; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"milvus">; /** Milvus connection URL (http://...) - overrides individual params if provided */ url: z.ZodOptional; /** Milvus server hostname */ host: z.ZodOptional; /** Milvus REST API port (default: 19530) */ port: z.ZodOptional>; /** Milvus username for authentication (Zilliz Cloud) */ username: z.ZodOptional; /** Milvus password for authentication (Zilliz Cloud) */ password: z.ZodOptional; /** Milvus API token for authentication (Zilliz Cloud) */ token: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "milvus"; password?: string; token?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; }, { options?: Record; type?: "milvus"; password?: string; token?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"chroma">; /** ChromaDB connection URL (http://...) - overrides individual params if provided */ url: z.ZodOptional; /** ChromaDB server hostname */ host: z.ZodOptional; /** ChromaDB HTTP port (default: 8000) */ port: z.ZodOptional>; /** Use SSL/TLS for connection (default: false) */ ssl: z.ZodOptional>; /** Custom HTTP headers for authentication */ headers: z.ZodOptional>; /** Distance metric for similarity search */ distance: z.ZodOptional>>; /** Custom path for ChromaDB API endpoints */ path: z.ZodOptional; }, "strict", z.ZodTypeAny, { path?: string; options?: Record; type?: "chroma"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "cosine" | "l2" | "euclidean" | "ip" | "dot"; headers?: Record; }, { path?: string; options?: Record; type?: "chroma"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "cosine" | "l2" | "euclidean" | "ip" | "dot"; headers?: Record; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"pinecone">; /** Pinecone API key for authentication */ apiKey: z.ZodString; /** Pinecone provider (optional) */ provider: z.ZodOptional; /** Pinecone region (default: 'us-west1') */ region: z.ZodOptional>; /** Distance metric for similarity search */ metric: z.ZodOptional>>; /** Pinecone pod type (for performance tuning) */ podType: z.ZodOptional; /** Number of replicas for high availability */ replicas: z.ZodOptional; /** Source collection for cloning */ sourceCollection: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "pinecone"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; provider?: string; region?: string; collectionName?: string; dimension?: number; metric?: "cosine" | "euclidean" | "dotproduct"; podType?: string; replicas?: number; sourceCollection?: string; }, { options?: Record; type?: "pinecone"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; provider?: string; region?: string; collectionName?: string; dimension?: number; metric?: "cosine" | "euclidean" | "dotproduct"; podType?: string; replicas?: number; sourceCollection?: string; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"pgvector">; /** PostgreSQL connection URL (postgresql://...) - overrides individual params if provided */ url: z.ZodOptional; /** Use SSL/TLS for connection (default: false) */ ssl: z.ZodOptional>; /** Distance metric for similarity search */ distance: z.ZodOptional>>; /** Connection pool size (default: 10) */ poolSize: z.ZodOptional>; /** Index type for vector similarity search */ indexType: z.ZodOptional>>; indexMetric: z.ZodOptional>>; /** Schema name (default: 'public') */ schema: z.ZodOptional>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "pgvector"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; poolSize?: number; indexType?: "hnsw" | "ivfflat"; indexMetric?: "vector_l2_ops" | "vector_ip_ops" | "vector_cosine_ops"; schema?: string; }, { options?: Record; type?: "pgvector"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; poolSize?: number; indexType?: "hnsw" | "ivfflat"; indexMetric?: "vector_l2_ops" | "vector_ip_ops" | "vector_cosine_ops"; schema?: string; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"faiss">; /** Distance metric for similarity search */ distance: z.ZodOptional>>; /** Path to store the FAISS index file (for persistence) */ baseStoragePath: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "faiss"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; baseStoragePath?: string; }, { options?: Record; type?: "faiss"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; baseStoragePath?: string; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"redis">; url: z.ZodString; host: z.ZodOptional; port: z.ZodOptional>; username: z.ZodOptional; password: z.ZodOptional; distance: z.ZodOptional>>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "redis"; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; distance?: "IP" | "COSINE" | "L2"; }, { options?: Record; type?: "redis"; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; distance?: "IP" | "COSINE" | "L2"; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"weaviate">; /** Weaviate connection URL (http://...) - overrides individual params if provided */ url: z.ZodOptional; /** Weaviate server hostname */ host: z.ZodOptional; /** Weaviate REST API port (default: 8080) */ port: z.ZodOptional>; /** Weaviate gRPC port (default: 50051) */ grpcPort: z.ZodOptional>; /** Weaviate API key for authentication */ apiKey: z.ZodOptional; /** Weaviate username for authentication */ username: z.ZodOptional; /** Weaviate password for authentication */ password: z.ZodOptional; /** Additional headers (e.g., for third-party API keys) */ headers: z.ZodOptional>; /** Use HTTPS/secure connection */ secure: z.ZodOptional>; /** Connection timeout in milliseconds */ timeout: z.ZodOptional>; /** Distance metric for similarity search */ distance: z.ZodOptional>>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "weaviate"; apiKey?: string; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; timeout?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; headers?: Record; grpcPort?: number; secure?: boolean; }, { options?: Record; type?: "weaviate"; apiKey?: string; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; timeout?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; headers?: Record; grpcPort?: number; secure?: boolean; }>]>, { options?: Record; type?: "in-memory"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; maxVectors?: number; } | { path?: string; options?: Record; type?: "qdrant"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; collectionName?: string; dimension?: number; onDisk?: boolean; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; } | { options?: Record; type?: "milvus"; password?: string; token?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; } | { options?: Record; type?: "faiss"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; baseStoragePath?: string; } | { path?: string; options?: Record; type?: "chroma"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "cosine" | "l2" | "euclidean" | "ip" | "dot"; headers?: Record; } | { options?: Record; type?: "pinecone"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; provider?: string; region?: string; collectionName?: string; dimension?: number; metric?: "cosine" | "euclidean" | "dotproduct"; podType?: string; replicas?: number; sourceCollection?: string; } | { options?: Record; type?: "pgvector"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; poolSize?: number; indexType?: "hnsw" | "ivfflat"; indexMetric?: "vector_l2_ops" | "vector_ip_ops" | "vector_cosine_ops"; schema?: string; } | { options?: Record; type?: "redis"; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; distance?: "IP" | "COSINE" | "L2"; } | { options?: Record; type?: "weaviate"; apiKey?: string; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; timeout?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; headers?: Record; grpcPort?: number; secure?: boolean; }, { options?: Record; type?: "in-memory"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; maxVectors?: number; } | { path?: string; options?: Record; type?: "qdrant"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; collectionName?: string; dimension?: number; onDisk?: boolean; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; } | { options?: Record; type?: "milvus"; password?: string; token?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; } | { options?: Record; type?: "faiss"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; baseStoragePath?: string; } | { path?: string; options?: Record; type?: "chroma"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "cosine" | "l2" | "euclidean" | "ip" | "dot"; headers?: Record; } | { options?: Record; type?: "pinecone"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; provider?: string; region?: string; collectionName?: string; dimension?: number; metric?: "cosine" | "euclidean" | "dotproduct"; podType?: string; replicas?: number; sourceCollection?: string; } | { options?: Record; type?: "pgvector"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; poolSize?: number; indexType?: "hnsw" | "ivfflat"; indexMetric?: "vector_l2_ops" | "vector_ip_ops" | "vector_cosine_ops"; schema?: string; } | { options?: Record; type?: "redis"; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; distance?: "IP" | "COSINE" | "L2"; } | { options?: Record; type?: "weaviate"; apiKey?: string; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; timeout?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; headers?: Record; grpcPort?: number; secure?: boolean; }>; type BackendConfig$2 = z.infer; /** * Vector Storage System Configuration Schema * * Top-level configuration for the vector storage system. * Unlike the dual-backend storage system, vector storage uses a single backend. * * @example * ```typescript * const vectorConfig: VectorStoreConfig = { * type: 'qdrant', * host: 'localhost', * port: 6333, * collectionName: 'embeddings', * dimension: 1536 * }; * ``` */ declare const VectorStoreSchema: z.ZodEffects; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"in-memory">; /** Maximum number of vectors to store (prevents memory overflow) */ maxVectors: z.ZodDefault; }, "strict", z.ZodTypeAny, { options?: Record; type?: "in-memory"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; maxVectors?: number; }, { options?: Record; type?: "in-memory"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; maxVectors?: number; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"qdrant">; /** Qdrant connection URL (http://...) - overrides individual params if provided */ url: z.ZodOptional; /** Qdrant server hostname */ host: z.ZodOptional; /** Qdrant REST API port (default: 6333) */ port: z.ZodOptional>; /** Qdrant API key for authentication */ apiKey: z.ZodOptional; /** Store vectors on disk (for large datasets) */ onDisk: z.ZodOptional; /** Path for local Qdrant storage (if not using remote server) */ path: z.ZodOptional; /** Distance metric for similarity search */ distance: z.ZodOptional>>; }, "strict", z.ZodTypeAny, { path?: string; options?: Record; type?: "qdrant"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; collectionName?: string; dimension?: number; onDisk?: boolean; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; }, { path?: string; options?: Record; type?: "qdrant"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; collectionName?: string; dimension?: number; onDisk?: boolean; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"milvus">; /** Milvus connection URL (http://...) - overrides individual params if provided */ url: z.ZodOptional; /** Milvus server hostname */ host: z.ZodOptional; /** Milvus REST API port (default: 19530) */ port: z.ZodOptional>; /** Milvus username for authentication (Zilliz Cloud) */ username: z.ZodOptional; /** Milvus password for authentication (Zilliz Cloud) */ password: z.ZodOptional; /** Milvus API token for authentication (Zilliz Cloud) */ token: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "milvus"; password?: string; token?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; }, { options?: Record; type?: "milvus"; password?: string; token?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"chroma">; /** ChromaDB connection URL (http://...) - overrides individual params if provided */ url: z.ZodOptional; /** ChromaDB server hostname */ host: z.ZodOptional; /** ChromaDB HTTP port (default: 8000) */ port: z.ZodOptional>; /** Use SSL/TLS for connection (default: false) */ ssl: z.ZodOptional>; /** Custom HTTP headers for authentication */ headers: z.ZodOptional>; /** Distance metric for similarity search */ distance: z.ZodOptional>>; /** Custom path for ChromaDB API endpoints */ path: z.ZodOptional; }, "strict", z.ZodTypeAny, { path?: string; options?: Record; type?: "chroma"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "cosine" | "l2" | "euclidean" | "ip" | "dot"; headers?: Record; }, { path?: string; options?: Record; type?: "chroma"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "cosine" | "l2" | "euclidean" | "ip" | "dot"; headers?: Record; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"pinecone">; /** Pinecone API key for authentication */ apiKey: z.ZodString; /** Pinecone provider (optional) */ provider: z.ZodOptional; /** Pinecone region (default: 'us-west1') */ region: z.ZodOptional>; /** Distance metric for similarity search */ metric: z.ZodOptional>>; /** Pinecone pod type (for performance tuning) */ podType: z.ZodOptional; /** Number of replicas for high availability */ replicas: z.ZodOptional; /** Source collection for cloning */ sourceCollection: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "pinecone"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; provider?: string; region?: string; collectionName?: string; dimension?: number; metric?: "cosine" | "euclidean" | "dotproduct"; podType?: string; replicas?: number; sourceCollection?: string; }, { options?: Record; type?: "pinecone"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; provider?: string; region?: string; collectionName?: string; dimension?: number; metric?: "cosine" | "euclidean" | "dotproduct"; podType?: string; replicas?: number; sourceCollection?: string; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"pgvector">; /** PostgreSQL connection URL (postgresql://...) - overrides individual params if provided */ url: z.ZodOptional; /** Use SSL/TLS for connection (default: false) */ ssl: z.ZodOptional>; /** Distance metric for similarity search */ distance: z.ZodOptional>>; /** Connection pool size (default: 10) */ poolSize: z.ZodOptional>; /** Index type for vector similarity search */ indexType: z.ZodOptional>>; indexMetric: z.ZodOptional>>; /** Schema name (default: 'public') */ schema: z.ZodOptional>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "pgvector"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; poolSize?: number; indexType?: "hnsw" | "ivfflat"; indexMetric?: "vector_l2_ops" | "vector_ip_ops" | "vector_cosine_ops"; schema?: string; }, { options?: Record; type?: "pgvector"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; poolSize?: number; indexType?: "hnsw" | "ivfflat"; indexMetric?: "vector_l2_ops" | "vector_ip_ops" | "vector_cosine_ops"; schema?: string; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"faiss">; /** Distance metric for similarity search */ distance: z.ZodOptional>>; /** Path to store the FAISS index file (for persistence) */ baseStoragePath: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "faiss"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; baseStoragePath?: string; }, { options?: Record; type?: "faiss"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; baseStoragePath?: string; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"redis">; url: z.ZodString; host: z.ZodOptional; port: z.ZodOptional>; username: z.ZodOptional; password: z.ZodOptional; distance: z.ZodOptional>>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "redis"; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; distance?: "IP" | "COSINE" | "L2"; }, { options?: Record; type?: "redis"; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; distance?: "IP" | "COSINE" | "L2"; }>, z.ZodObject<{ /** Name of the collection/index to use */ collectionName: z.ZodString; /** Dimension of vectors (must match embedding model output) */ dimension: z.ZodDefault; /** Maximum number of concurrent connections */ maxConnections: z.ZodOptional; /** Connection timeout in milliseconds */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"weaviate">; /** Weaviate connection URL (http://...) - overrides individual params if provided */ url: z.ZodOptional; /** Weaviate server hostname */ host: z.ZodOptional; /** Weaviate REST API port (default: 8080) */ port: z.ZodOptional>; /** Weaviate gRPC port (default: 50051) */ grpcPort: z.ZodOptional>; /** Weaviate API key for authentication */ apiKey: z.ZodOptional; /** Weaviate username for authentication */ username: z.ZodOptional; /** Weaviate password for authentication */ password: z.ZodOptional; /** Additional headers (e.g., for third-party API keys) */ headers: z.ZodOptional>; /** Use HTTPS/secure connection */ secure: z.ZodOptional>; /** Connection timeout in milliseconds */ timeout: z.ZodOptional>; /** Distance metric for similarity search */ distance: z.ZodOptional>>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "weaviate"; apiKey?: string; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; timeout?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; headers?: Record; grpcPort?: number; secure?: boolean; }, { options?: Record; type?: "weaviate"; apiKey?: string; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; timeout?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; headers?: Record; grpcPort?: number; secure?: boolean; }>]>, { options?: Record; type?: "in-memory"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; maxVectors?: number; } | { path?: string; options?: Record; type?: "qdrant"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; collectionName?: string; dimension?: number; onDisk?: boolean; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; } | { options?: Record; type?: "milvus"; password?: string; token?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; } | { options?: Record; type?: "faiss"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; baseStoragePath?: string; } | { path?: string; options?: Record; type?: "chroma"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "cosine" | "l2" | "euclidean" | "ip" | "dot"; headers?: Record; } | { options?: Record; type?: "pinecone"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; provider?: string; region?: string; collectionName?: string; dimension?: number; metric?: "cosine" | "euclidean" | "dotproduct"; podType?: string; replicas?: number; sourceCollection?: string; } | { options?: Record; type?: "pgvector"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; poolSize?: number; indexType?: "hnsw" | "ivfflat"; indexMetric?: "vector_l2_ops" | "vector_ip_ops" | "vector_cosine_ops"; schema?: string; } | { options?: Record; type?: "redis"; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; distance?: "IP" | "COSINE" | "L2"; } | { options?: Record; type?: "weaviate"; apiKey?: string; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; timeout?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; headers?: Record; grpcPort?: number; secure?: boolean; }, { options?: Record; type?: "in-memory"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; maxVectors?: number; } | { path?: string; options?: Record; type?: "qdrant"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; collectionName?: string; dimension?: number; onDisk?: boolean; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; } | { options?: Record; type?: "milvus"; password?: string; token?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; } | { options?: Record; type?: "faiss"; maxConnections?: number; connectionTimeoutMillis?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; baseStoragePath?: string; } | { path?: string; options?: Record; type?: "chroma"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "cosine" | "l2" | "euclidean" | "ip" | "dot"; headers?: Record; } | { options?: Record; type?: "pinecone"; apiKey?: string; maxConnections?: number; connectionTimeoutMillis?: number; provider?: string; region?: string; collectionName?: string; dimension?: number; metric?: "cosine" | "euclidean" | "dotproduct"; podType?: string; replicas?: number; sourceCollection?: string; } | { options?: Record; type?: "pgvector"; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; ssl?: boolean; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; poolSize?: number; indexType?: "hnsw" | "ivfflat"; indexMetric?: "vector_l2_ops" | "vector_ip_ops" | "vector_cosine_ops"; schema?: string; } | { options?: Record; type?: "redis"; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; collectionName?: string; dimension?: number; distance?: "IP" | "COSINE" | "L2"; } | { options?: Record; type?: "weaviate"; apiKey?: string; password?: string; maxConnections?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; timeout?: number; collectionName?: string; dimension?: number; distance?: "Cosine" | "Euclidean" | "IP"; headers?: Record; grpcPort?: number; secure?: boolean; }>; type VectorStoreConfig = z.infer; /** * Vector Storage Backend Types and Error Classes * * This module defines the core types and error classes for the vector storage system. * The vector storage system provides similarity search capabilities for high-dimensional vectors. * * @module vector_storage/backend/types */ /** * Search filters for vector queries * * Allows filtering search results based on metadata attached to vectors. * Supports exact matches and range queries. * * @example * ```typescript * const filters: SearchFilters = { * category: 'documents', * created_at: { gte: startDate, lte: endDate }, * tags: { any: ['important', 'reviewed'] } * }; * ``` */ interface SearchFilters { [key: string]: string | number | boolean | { gte?: number; gt?: number; lte?: number; lt?: number; } | { any?: Array; } | { all?: Array; }; } /** * Vector search result * * Represents a single result from a vector similarity search. * Includes the vector ID, similarity score, and associated metadata. * * @example * ```typescript * const result: VectorStoreResult = { * id: 'doc-123', // or number for Qdrant * score: 0.95, * payload: { * title: 'Important Document', * category: 'reports', * created_at: 1234567890 * } * }; * ``` */ interface VectorStoreResult { /** Unique identifier for the vector - string for in-memory, number for Qdrant */ id: string | number; /** Similarity score (higher is more similar, range depends on metric) */ score?: number; /** Vector data (only returned if explicitly requested) */ vector?: number[]; /** Metadata associated with the vector */ payload: Record; } /** * Base Vector Storage Error Class * * All vector storage-related errors extend from this base class. * Provides consistent error structure with operation context and optional cause. * * @example * ```typescript * throw new VectorStoreError('Failed to index vectors', 'insert', originalError); * ``` */ declare class VectorStoreError extends Error { message: string; /** The operation that failed (e.g., 'search', 'insert', 'delete', 'connection') */ readonly operation: string; /** The underlying error that caused this error, if any */ readonly cause?: Error; constructor(message: string, /** The operation that failed (e.g., 'search', 'insert', 'delete', 'connection') */ operation: string, /** The underlying error that caused this error, if any */ cause?: Error); } /** * Vector Store Connection Error * * Thrown when a vector store backend fails to connect or loses connection. * Includes the backend type for easier debugging. * * @example * ```typescript * throw new VectorStoreConnectionError( * 'Failed to connect to Qdrant', * 'qdrant', * qdrantError * ); * ``` */ declare class VectorStoreConnectionError extends VectorStoreError { message: string; /** The type of backend that failed to connect (e.g., 'qdrant', 'pinecone') */ readonly backendType: string; /** The underlying connection error, if any */ readonly cause?: Error; constructor(message: string, /** The type of backend that failed to connect (e.g., 'qdrant', 'pinecone') */ backendType: string, /** The underlying connection error, if any */ cause?: Error); } /** * Vector Dimension Error * * Thrown when vector dimensions don't match the configured dimension. * This is a common error when the embedding model changes. * * @example * ```typescript * throw new VectorDimensionError( * `Expected dimension ${expected}, got ${actual}`, * expected, * actual * ); * ``` */ declare class VectorDimensionError extends VectorStoreError { message: string; /** The expected vector dimension */ readonly expectedDimension: number; /** The actual vector dimension received */ readonly actualDimension: number; /** The underlying error, if any */ readonly cause?: Error; constructor(message: string, /** The expected vector dimension */ expectedDimension: number, /** The actual vector dimension received */ actualDimension: number, /** The underlying error, if any */ cause?: Error); } /** * Collection Not Found Error * * Thrown when attempting to access a collection that doesn't exist. * * @example * ```typescript * throw new CollectionNotFoundError( * `Collection '${collectionName}' does not exist`, * collectionName * ); * ``` */ declare class CollectionNotFoundError extends VectorStoreError { message: string; /** The name of the collection that was not found */ readonly collectionName: string; /** The underlying error, if any */ readonly cause?: Error; constructor(message: string, /** The name of the collection that was not found */ collectionName: string, /** The underlying error, if any */ cause?: Error); } /** * Vector Storage Manager Implementation * * Orchestrates the vector storage system with backend management. * Provides lazy loading, graceful fallbacks, and connection management. * * @module vector_storage/manager */ /** * Health check result for vector store backend */ interface HealthCheckResult$2 { backend: boolean; overall: boolean; details?: { backend?: { status: string; latency?: number; error?: string; }; }; } /** * Vector storage system information */ interface VectorStoreInfo { connected: boolean; backend: { type: string; connected: boolean; fallback: boolean; collectionName: string; dimension: number; }; connectionAttempts: number; lastError: string | undefined; } /** * Vector Storage Manager * * Manages the lifecycle of vector storage backend with lazy loading and fallback support. * Follows the factory pattern with graceful degradation to in-memory storage. * * @example * ```typescript * const manager = new VectorStoreManager(config); * const store = await manager.connect(); * * // Use vector store * await store.insert([vector], ['id1'], [{ title: 'Document' }]); * const results = await store.search(queryVector, 5); * * // Cleanup * await manager.disconnect(); * ``` */ declare class VectorStoreManager { private store; private connected; private readonly config; private readonly logger; private eventManager?; private connectionAttempts; private lastConnectionError?; private backendMetadata; private static qdrantModule?; private static inMemoryModule?; private static milvusModule?; private static chromaModule?; private static pgVectorModule?; private static pineconeModule?; private static faissModule?; private static redisModule?; private static weaviateModule?; private usedFallback; private factoryFallback; /** * Creates a new VectorStoreManager instance * * @param config - Vector storage configuration * @throws {Error} If configuration is invalid */ constructor(config: VectorStoreConfig); /** * Set the event manager for emitting memory operation events */ setEventManager(eventManager: EventManager): void; /** * Get the current vector storage configuration * * @returns The vector storage configuration */ getConfig(): Readonly; /** * Get information about the vector storage system * * @returns Vector storage system information including connection status and backend type */ getInfo(): VectorStoreInfo; /** * Get the current vector store if connected * * @returns The vector store or null if not connected */ getStore(): VectorStore | null; /** * Get an event-aware vector store for a specific session * * @param sessionId - The session ID to associate with memory operations * @returns Event-aware vector store or null if not connected */ getEventAwareStore(sessionId: string): VectorStore | null; /** * Check if the vector storage manager is connected * * @returns true if backend is connected */ isConnected(): boolean; /** * Connect to vector storage backend * * @returns The connected vector store * @throws {VectorStoreConnectionError} If backend fails to connect */ connect(): Promise; /** * Disconnect from vector storage backend */ disconnect(): Promise; /** * Perform health check on the backend * * @returns Health check results */ healthCheck(): Promise; /** * Create vector store backend based on configuration */ private createBackend; } /** * Dual Collection Vector Manager * * Manages two separate vector collections for knowledge and reflection memory. * Built on top of the existing VectorStoreManager infrastructure. */ /** * Collection type identifier */ type CollectionType = 'knowledge' | 'reflection'; /** * Information about both collections */ interface DualCollectionInfo { knowledge: { connected: boolean; collectionName: string; manager: VectorStoreManager; }; reflection: { connected: boolean; collectionName: string; manager: VectorStoreManager; enabled: boolean; }; overallConnected: boolean; } /** * Dual Collection Vector Manager * * Manages separate vector collections for knowledge and reflection memory. * Uses two VectorStoreManager instances under the hood. * * @example * ```typescript * const dualManager = new DualCollectionVectorManager(baseConfig); * await dualManager.connect(); * * // Get knowledge store * const knowledgeStore = dualManager.getStore('knowledge'); * * // Get reflection store (if enabled) * const reflectionStore = dualManager.getStore('reflection'); * ``` */ declare class DualCollectionVectorManager { private readonly knowledgeManager; private readonly reflectionManager; private readonly logger; private readonly reflectionEnabled; private eventManager?; constructor(baseConfig: VectorStoreConfig); /** * Set the event manager for emitting memory operation events */ setEventManager(eventManager: EventManager): void; /** * Connect both collections */ connect(): Promise; /** * Disconnect both collections */ disconnect(): Promise; /** * Get a vector store by collection type */ getStore(type: CollectionType): VectorStore | null; /** * Get an event-aware vector store by collection type for a specific session */ getEventAwareStore(type: CollectionType, sessionId: string): VectorStore | null; /** * Check if collections are connected */ isConnected(type?: CollectionType): boolean; /** * Get information about both collections */ getInfo(): DualCollectionInfo; /** * Get a manager by collection type (for advanced usage) */ getManager(type: CollectionType): VectorStoreManager | null; /** * Health check for both collections */ healthCheck(): Promise<{ knowledge: any; reflection: any; overall: boolean; }>; } /** * Vector Storage Factory * * Factory functions for creating and initializing the vector storage system. * Provides a simplified API for common vector storage setup patterns. * * @module vector_storage/factory */ /** * Factory result containing both the manager and vector store */ interface VectorStoreFactory { /** The vector store manager instance for lifecycle control */ manager: VectorStoreManager; /** The connected vector store ready for use */ store: VectorStore; } /** * Dual collection factory result containing dual manager and stores */ interface DualCollectionVectorFactory { /** The dual collection manager instance for lifecycle control */ manager: DualCollectionVectorManager; /** The knowledge vector store ready for use */ knowledgeStore: VectorStore; /** The reflection vector store ready for use (null if disabled) */ reflectionStore: VectorStore | null; } /** * Creates and connects vector storage backend * * This is the primary factory function for initializing the vector storage system. * It creates a VectorStoreManager, connects to the configured backend, and * returns both the manager and the connected vector store. * * @param config - Vector storage configuration * @returns Promise resolving to manager and connected vector store * @throws {VectorStoreConnectionError} If connection fails and no fallback is available * * @example * ```typescript * // Basic usage with Qdrant * const { manager, store } = await createVectorStore({ * type: 'qdrant', * host: 'localhost', * port: 6333, * collectionName: 'documents', * dimension: 1536 * }); * * // Use the vector store * await store.insert([vector], ['doc1'], [{ title: 'Document' }]); * const results = await store.search(queryVector, 5); * * // Cleanup when done * await manager.disconnect(); * ``` * * @example * ```typescript * // Development configuration with in-memory * const { manager, store } = await createVectorStore({ * type: 'in-memory', * collectionName: 'test', * dimension: 1536, * maxVectors: 1000 * }); * ``` */ declare function createVectorStore(config: VectorStoreConfig): Promise; /** * Creates vector storage with default configuration * * Convenience function that creates vector storage with in-memory backend. * Useful for testing or development environments. * * @param collectionName - Optional collection name (default: 'knowledge_memory') * @param dimension - Optional vector dimension (default: 1536) * @returns Promise resolving to manager and connected vector store * * @example * ```typescript * const { manager, store } = await createDefaultVectorStore(); * // Uses in-memory backend with default settings * * const { manager, store } = await createDefaultVectorStore('my_collection', 768); * // Uses in-memory backend with custom collection and dimension * ``` */ declare function createDefaultVectorStore(collectionName?: string, dimension?: number): Promise; /** * Creates vector storage from environment variables * * Reads vector storage configuration from environment variables and creates * the vector storage system. Falls back to in-memory if not configured. * * Environment variables: * - VECTOR_STORE_TYPE: Backend type (qdrant, in-memory) * - VECTOR_STORE_HOST: Qdrant host (if using Qdrant) * - VECTOR_STORE_PORT: Qdrant port (if using Qdrant) * - VECTOR_STORE_URL: Qdrant URL (if using Qdrant) * - VECTOR_STORE_API_KEY: Qdrant API key (if using Qdrant) * - VECTOR_STORE_COLLECTION: Collection name * - VECTOR_STORE_DIMENSION: Vector dimension * - VECTOR_STORE_DISTANCE: Distance metric for Qdrant * - VECTOR_STORE_ON_DISK: Store vectors on disk (if using Qdrant) * - VECTOR_STORE_MAX_VECTORS: Maximum vectors for in-memory storage * * @param agentConfig - Optional agent configuration to override dimension from embedding config * @returns Promise resolving to manager and connected vector store * * @example * ```typescript * // Set environment variables * process.env.VECTOR_STORE_TYPE = 'qdrant'; * process.env.VECTOR_STORE_HOST = 'localhost'; * process.env.VECTOR_STORE_COLLECTION = 'documents'; * * const { manager, store } = await createVectorStoreFromEnv(); * ``` */ declare function createVectorStoreFromEnv(agentConfig?: any): Promise; /** * Creates dual collection vector storage from environment variables * * Creates a dual collection manager that handles both knowledge and reflection * memory collections. Reflection collection is only created if REFLECTION_VECTOR_STORE_COLLECTION * is set and the model supports reasoning. * * @param agentConfig - Optional agent configuration to override dimension from embedding config * @returns Promise resolving to dual collection manager and stores * * @example * ```typescript * // Set environment variables for reasoning model with dual collections * process.env.VECTOR_STORE_TYPE = 'in-memory'; * process.env.VECTOR_STORE_COLLECTION = 'knowledge'; * process.env.REFLECTION_VECTOR_STORE_COLLECTION = 'reflection_memory'; * * const { manager, knowledgeStore, reflectionStore } = await createDualCollectionVectorStoreFromEnv(); * ``` */ declare function createDualCollectionVectorStoreFromEnv(agentConfig?: any): Promise; /** * Get vector storage configuration from environment variables * * Returns the configuration object that would be used by createVectorStoreFromEnv * without actually creating the vector store. Useful for debugging and validation. * * @param agentConfig - Optional agent configuration to override dimension from embedding config * @returns Vector storage configuration based on environment variables * * @example * ```typescript * const config = getVectorStoreConfigFromEnv(); * console.log('Vector store configuration:', config); * * // Then use the config to create the store * const { manager, store } = await createVectorStore(config); * ``` */ declare function getVectorStoreConfigFromEnv(agentConfig?: any): VectorStoreConfig; /** * Get workspace memory vector storage configuration from environment variables * * Returns the configuration object for workspace memory vector store, using * workspace-specific environment variables with fallbacks to default vector store config. * * @param agentConfig - Optional agent configuration to override dimension from embedding config * @returns Vector storage configuration based on workspace memory environment variables * * @example * ```typescript * const config = getWorkspaceVectorStoreConfigFromEnv(); * console.log('Workspace vector store configuration:', config); * * // Then use the config to create workspace store * const { manager, store } = await createVectorStore(config); * ``` */ declare function getWorkspaceVectorStoreConfigFromEnv(agentConfig?: any): VectorStoreConfig; /** * Multi Collection Vector Factory interface for workspace memory support */ interface MultiCollectionVectorFactory { /** The multi collection manager instance */ manager: any; /** The knowledge vector store ready for use */ knowledgeStore: VectorStore; /** The reflection vector store ready for use (null if disabled) */ reflectionStore: VectorStore | null; /** The workspace vector store ready for use (null if disabled) */ workspaceStore: VectorStore | null; } /** * Creates multi-collection vector storage from environment variables * * Creates a multi-collection manager that handles knowledge, reflection, and workspace * memory collections. This replaces DualCollectionVectorManager when workspace memory is enabled. * * @param agentConfig - Optional agent configuration to override dimension from embedding config * @returns Promise resolving to multi collection manager and stores */ declare function createMultiCollectionVectorStoreFromEnv(agentConfig?: any): Promise; /** * Creates workspace memory vector storage from environment variables * * Reads workspace memory vector storage configuration from environment variables and creates * the vector storage system specifically for workspace memory. Falls back to default * vector store configuration if workspace-specific variables are not set. * * Environment variables (with fallbacks to default VECTOR_STORE_* variables): * - WORKSPACE_VECTOR_STORE_TYPE: Backend type (qdrant, milvus, chroma, in-memory) * - WORKSPACE_VECTOR_STORE_HOST: Host (fallback to VECTOR_STORE_HOST) * - WORKSPACE_VECTOR_STORE_PORT: Port (fallback to VECTOR_STORE_PORT) * - WORKSPACE_VECTOR_STORE_URL: URL (fallback to VECTOR_STORE_URL) * - WORKSPACE_VECTOR_STORE_API_KEY: API key (fallback to VECTOR_STORE_API_KEY) * - WORKSPACE_VECTOR_STORE_COLLECTION: Collection name (default: workspace_memory) * - WORKSPACE_VECTOR_STORE_DIMENSION: Vector dimension (fallback to VECTOR_STORE_DIMENSION) * - WORKSPACE_VECTOR_STORE_DISTANCE: Distance metric for Qdrant (fallback to VECTOR_STORE_DISTANCE) * - WORKSPACE_VECTOR_STORE_ON_DISK: Store vectors on disk (default: false) * - WORKSPACE_VECTOR_STORE_MAX_VECTORS: Maximum vectors for in-memory storage * * @param agentConfig - Optional agent configuration to override dimension from embedding config * @returns Promise resolving to manager and connected workspace vector store * * @example * ```typescript * // Set workspace-specific environment variables * process.env.WORKSPACE_VECTOR_STORE_TYPE = 'milvus'; * process.env.WORKSPACE_VECTOR_STORE_HOST = 'localhost'; * process.env.WORKSPACE_VECTOR_STORE_COLLECTION = 'team_workspace'; * * const { manager, store } = await createWorkspaceVectorStoreFromEnv(); * ``` */ declare function createWorkspaceVectorStoreFromEnv(agentConfig?: any): Promise; /** * Type guard to check if an object is a VectorStoreFactory * * @param obj - Object to check * @returns true if the object has manager and store properties */ declare function isVectorStoreFactory(obj: unknown): obj is VectorStoreFactory; /** * Backend type identifiers */ declare const BACKEND_TYPES$2: { readonly QDRANT: "qdrant"; readonly PINECONE: "pinecone"; readonly WEAVIATE: "weaviate"; readonly CHROMA: "chroma"; readonly IN_MEMORY: "in-memory"; readonly MILVUS: "milvus"; readonly PGVECTOR: "pgvector"; readonly FAISS: "faiss"; readonly REDIS: "redis"; }; /** * Default configuration values */ declare const DEFAULTS$2: { readonly SEARCH_LIMIT: 10; readonly SEARCH_SCORE_THRESHOLD: 0; readonly DIMENSION: 1536; readonly MAX_BATCH_SIZE: 100; readonly MAX_RETRIES: 3; readonly RETRY_DELAY: 1000; readonly MAX_CONNECTIONS: 10; readonly IDLE_TIMEOUT: 30000; readonly QDRANT_PORT: 6333; readonly QDRANT_GRPC_PORT: 6334; readonly QDRANT_DISTANCE: "Cosine"; readonly CHROMA_PORT: 8000; readonly CHROMA_DISTANCE: "cosine"; readonly PINECONE_REGION: "us-east-1"; readonly PINECONE_PROVIDER: "aws"; readonly PGVECTOR_INDEXTYPE: "hnsw"; readonly PGVECTOR_INDEXMETRIC: "vector_l2_ops"; }; /** * Vector distance metrics */ declare const DISTANCE_METRICS: { readonly COSINE: "Cosine"; readonly EUCLIDEAN: "Euclidean"; readonly DOT_PRODUCT: "Dot"; readonly MANHATTAN: "Manhattan"; }; /** * Vector Storage Module * * High-performance vector storage and similarity search for embeddings. * Supports multiple backends with a unified API. * * Features: * - Multiple backend support (Qdrant, In-Memory, etc.) * - Similarity search with metadata filtering * - Batch operations for efficient indexing * - Type-safe configuration with runtime validation * - Graceful fallback to in-memory storage * * @module vector_storage * * @example * ```typescript * import { createVectorStore } from './vector_storage'; * * // Create a vector store * const { store, manager } = await createVectorStore({ * type: 'qdrant', * host: 'localhost', * port: 6333, * collectionName: 'documents', * dimension: 1536 * }); * * // Index vectors * await store.insert( * [embedding1, embedding2], * ['doc1', 'doc2'], * [{ title: 'Doc 1' }, { title: 'Doc 2' }] * ); * * // Search for similar vectors * const results = await store.search(queryEmbedding, 5); * * // Cleanup * await manager.disconnect(); * ``` */ type index$2_CollectionNotFoundError = CollectionNotFoundError; declare const index$2_CollectionNotFoundError: typeof CollectionNotFoundError; type index$2_CollectionType = CollectionType; declare const index$2_DISTANCE_METRICS: typeof DISTANCE_METRICS; type index$2_DualCollectionVectorFactory = DualCollectionVectorFactory; type index$2_DualCollectionVectorManager = DualCollectionVectorManager; declare const index$2_DualCollectionVectorManager: typeof DualCollectionVectorManager; type index$2_MultiCollectionVectorFactory = MultiCollectionVectorFactory; type index$2_SearchFilters = SearchFilters; type index$2_VectorDimensionError = VectorDimensionError; declare const index$2_VectorDimensionError: typeof VectorDimensionError; type index$2_VectorStore = VectorStore; type index$2_VectorStoreConfig = VectorStoreConfig; type index$2_VectorStoreConnectionError = VectorStoreConnectionError; declare const index$2_VectorStoreConnectionError: typeof VectorStoreConnectionError; type index$2_VectorStoreError = VectorStoreError; declare const index$2_VectorStoreError: typeof VectorStoreError; type index$2_VectorStoreFactory = VectorStoreFactory; type index$2_VectorStoreInfo = VectorStoreInfo; type index$2_VectorStoreManager = VectorStoreManager; declare const index$2_VectorStoreManager: typeof VectorStoreManager; type index$2_VectorStoreResult = VectorStoreResult; declare const index$2_createDefaultVectorStore: typeof createDefaultVectorStore; declare const index$2_createDualCollectionVectorStoreFromEnv: typeof createDualCollectionVectorStoreFromEnv; declare const index$2_createMultiCollectionVectorStoreFromEnv: typeof createMultiCollectionVectorStoreFromEnv; declare const index$2_createVectorStore: typeof createVectorStore; declare const index$2_createVectorStoreFromEnv: typeof createVectorStoreFromEnv; declare const index$2_createWorkspaceVectorStoreFromEnv: typeof createWorkspaceVectorStoreFromEnv; declare const index$2_getVectorStoreConfigFromEnv: typeof getVectorStoreConfigFromEnv; declare const index$2_getWorkspaceVectorStoreConfigFromEnv: typeof getWorkspaceVectorStoreConfigFromEnv; declare const index$2_isVectorStoreFactory: typeof isVectorStoreFactory; declare namespace index$2 { export { BACKEND_TYPES$2 as BACKEND_TYPES, type BackendConfig$2 as BackendConfig, index$2_CollectionNotFoundError as CollectionNotFoundError, type index$2_CollectionType as CollectionType, DEFAULTS$2 as DEFAULTS, index$2_DISTANCE_METRICS as DISTANCE_METRICS, type index$2_DualCollectionVectorFactory as DualCollectionVectorFactory, index$2_DualCollectionVectorManager as DualCollectionVectorManager, type HealthCheckResult$2 as HealthCheckResult, type index$2_MultiCollectionVectorFactory as MultiCollectionVectorFactory, type index$2_SearchFilters as SearchFilters, index$2_VectorDimensionError as VectorDimensionError, type index$2_VectorStore as VectorStore, type index$2_VectorStoreConfig as VectorStoreConfig, index$2_VectorStoreConnectionError as VectorStoreConnectionError, index$2_VectorStoreError as VectorStoreError, type index$2_VectorStoreFactory as VectorStoreFactory, type index$2_VectorStoreInfo as VectorStoreInfo, index$2_VectorStoreManager as VectorStoreManager, type index$2_VectorStoreResult as VectorStoreResult, index$2_createDefaultVectorStore as createDefaultVectorStore, index$2_createDualCollectionVectorStoreFromEnv as createDualCollectionVectorStoreFromEnv, index$2_createMultiCollectionVectorStoreFromEnv as createMultiCollectionVectorStoreFromEnv, index$2_createVectorStore as createVectorStore, index$2_createVectorStoreFromEnv as createVectorStoreFromEnv, index$2_createWorkspaceVectorStoreFromEnv as createWorkspaceVectorStoreFromEnv, index$2_getVectorStoreConfigFromEnv as getVectorStoreConfigFromEnv, index$2_getWorkspaceVectorStoreConfigFromEnv as getWorkspaceVectorStoreConfigFromEnv, index$2_isVectorStoreFactory as isVectorStoreFactory }; } /** * Knowledge Graph Configuration Schemas * * Provides Zod schemas for validating knowledge graph backend configurations. * These schemas ensure type safety and runtime validation of configuration objects. * * @module knowledge_graph/config */ /** * In-Memory Backend Configuration Schema * * Configuration for the in-memory knowledge graph backend. * Used for development, testing, and as a fallback option. * * @example * ```typescript * const config: InMemoryBackendConfig = { * type: 'in-memory', * maxNodes: 10000, * maxEdges: 50000, * enableIndexing: true * }; * ``` */ declare const InMemoryBackendSchema$1: z.ZodObject<{ timeout: z.ZodDefault; maxRetries: z.ZodDefault; enablePooling: z.ZodDefault; poolSize: z.ZodDefault; } & { type: z.ZodLiteral<"in-memory">; maxNodes: z.ZodDefault; maxEdges: z.ZodDefault; enableIndexing: z.ZodDefault; enableGarbageCollection: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "in-memory"; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; maxNodes?: number; maxEdges?: number; enableIndexing?: boolean; enableGarbageCollection?: boolean; }, { type?: "in-memory"; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; maxNodes?: number; maxEdges?: number; enableIndexing?: boolean; enableGarbageCollection?: boolean; }>; /** * Neo4j Backend Configuration Schema (without refinement) * * Configuration for connecting to a Neo4j graph database. * Supports both direct connection and URI-based connection. * * @example * ```typescript * // Direct connection * const config: Neo4jBackendConfig = { * type: 'neo4j', * host: 'localhost', * port: 7687, * username: 'neo4j', * password: 'password', * database: 'neo4j' * }; * * // URI-based connection * const uriConfig: Neo4jBackendConfig = { * type: 'neo4j', * uri: 'neo4j://localhost:7687', * username: 'neo4j', * password: 'password' * }; * ``` */ declare const Neo4jBackendSchema: z.ZodObject<{ timeout: z.ZodDefault; maxRetries: z.ZodDefault; enablePooling: z.ZodDefault; poolSize: z.ZodDefault; } & { type: z.ZodLiteral<"neo4j">; host: z.ZodOptional; port: z.ZodOptional; uri: z.ZodOptional; username: z.ZodString; password: z.ZodString; database: z.ZodDefault; encrypted: z.ZodDefault; trustServerCertificate: z.ZodDefault; maxTransactionRetryTime: z.ZodDefault; connectionAcquisitionTimeout: z.ZodDefault; maxConnectionLifetime: z.ZodDefault; connectionLivenessCheckTimeout: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "neo4j"; password?: string; uri?: string; database?: string; host?: string; port?: number; username?: string; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; encrypted?: boolean; trustServerCertificate?: boolean; maxTransactionRetryTime?: number; connectionAcquisitionTimeout?: number; maxConnectionLifetime?: number; connectionLivenessCheckTimeout?: number; }, { type?: "neo4j"; password?: string; uri?: string; database?: string; host?: string; port?: number; username?: string; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; encrypted?: boolean; trustServerCertificate?: boolean; maxTransactionRetryTime?: number; connectionAcquisitionTimeout?: number; maxConnectionLifetime?: number; connectionLivenessCheckTimeout?: number; }>; /** * Union schema for all supported backend configurations */ declare const BackendConfigSchema$1: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{ timeout: z.ZodDefault; maxRetries: z.ZodDefault; enablePooling: z.ZodDefault; poolSize: z.ZodDefault; } & { type: z.ZodLiteral<"in-memory">; maxNodes: z.ZodDefault; maxEdges: z.ZodDefault; enableIndexing: z.ZodDefault; enableGarbageCollection: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "in-memory"; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; maxNodes?: number; maxEdges?: number; enableIndexing?: boolean; enableGarbageCollection?: boolean; }, { type?: "in-memory"; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; maxNodes?: number; maxEdges?: number; enableIndexing?: boolean; enableGarbageCollection?: boolean; }>, z.ZodObject<{ timeout: z.ZodDefault; maxRetries: z.ZodDefault; enablePooling: z.ZodDefault; poolSize: z.ZodDefault; } & { type: z.ZodLiteral<"neo4j">; host: z.ZodOptional; port: z.ZodOptional; uri: z.ZodOptional; username: z.ZodString; password: z.ZodString; database: z.ZodDefault; encrypted: z.ZodDefault; trustServerCertificate: z.ZodDefault; maxTransactionRetryTime: z.ZodDefault; connectionAcquisitionTimeout: z.ZodDefault; maxConnectionLifetime: z.ZodDefault; connectionLivenessCheckTimeout: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "neo4j"; password?: string; uri?: string; database?: string; host?: string; port?: number; username?: string; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; encrypted?: boolean; trustServerCertificate?: boolean; maxTransactionRetryTime?: number; connectionAcquisitionTimeout?: number; maxConnectionLifetime?: number; connectionLivenessCheckTimeout?: number; }, { type?: "neo4j"; password?: string; uri?: string; database?: string; host?: string; port?: number; username?: string; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; encrypted?: boolean; trustServerCertificate?: boolean; maxTransactionRetryTime?: number; connectionAcquisitionTimeout?: number; maxConnectionLifetime?: number; connectionLivenessCheckTimeout?: number; }>]>; /** * Knowledge Graph System Configuration Schema * * Top-level configuration for the knowledge graph system. * Includes backend configuration and system-level settings. * * @example * ```typescript * const config: KnowledgeGraphConfig = { * type: 'neo4j', * host: 'localhost', * port: 7687, * username: 'neo4j', * password: 'password', * database: 'knowledge', * enableAutoIndexing: true, * enableMetrics: true * }; * ``` */ declare const KnowledgeGraphSchema: z.ZodIntersection; maxRetries: z.ZodDefault; enablePooling: z.ZodDefault; poolSize: z.ZodDefault; } & { type: z.ZodLiteral<"in-memory">; maxNodes: z.ZodDefault; maxEdges: z.ZodDefault; enableIndexing: z.ZodDefault; enableGarbageCollection: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "in-memory"; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; maxNodes?: number; maxEdges?: number; enableIndexing?: boolean; enableGarbageCollection?: boolean; }, { type?: "in-memory"; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; maxNodes?: number; maxEdges?: number; enableIndexing?: boolean; enableGarbageCollection?: boolean; }>, z.ZodObject<{ timeout: z.ZodDefault; maxRetries: z.ZodDefault; enablePooling: z.ZodDefault; poolSize: z.ZodDefault; } & { type: z.ZodLiteral<"neo4j">; host: z.ZodOptional; port: z.ZodOptional; uri: z.ZodOptional; username: z.ZodString; password: z.ZodString; database: z.ZodDefault; encrypted: z.ZodDefault; trustServerCertificate: z.ZodDefault; maxTransactionRetryTime: z.ZodDefault; connectionAcquisitionTimeout: z.ZodDefault; maxConnectionLifetime: z.ZodDefault; connectionLivenessCheckTimeout: z.ZodDefault; }, "strip", z.ZodTypeAny, { type?: "neo4j"; password?: string; uri?: string; database?: string; host?: string; port?: number; username?: string; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; encrypted?: boolean; trustServerCertificate?: boolean; maxTransactionRetryTime?: number; connectionAcquisitionTimeout?: number; maxConnectionLifetime?: number; connectionLivenessCheckTimeout?: number; }, { type?: "neo4j"; password?: string; uri?: string; database?: string; host?: string; port?: number; username?: string; timeout?: number; maxRetries?: number; poolSize?: number; enablePooling?: boolean; encrypted?: boolean; trustServerCertificate?: boolean; maxTransactionRetryTime?: number; connectionAcquisitionTimeout?: number; maxConnectionLifetime?: number; connectionLivenessCheckTimeout?: number; }>]>, z.ZodObject<{ /** Whether to enable automatic indexing of node properties */ enableAutoIndexing: z.ZodDefault; /** Whether to enable performance metrics collection */ enableMetrics: z.ZodDefault; /** Whether to enable query caching (if supported by backend) */ enableQueryCache: z.ZodDefault; /** Query cache TTL in milliseconds */ queryCacheTTL: z.ZodDefault; /** Whether to enable schema validation for nodes and edges */ enableSchemaValidation: z.ZodDefault; /** Default batch size for bulk operations */ defaultBatchSize: z.ZodDefault; }, "strip", z.ZodTypeAny, { enableAutoIndexing?: boolean; enableMetrics?: boolean; enableQueryCache?: boolean; queryCacheTTL?: number; enableSchemaValidation?: boolean; defaultBatchSize?: number; }, { enableAutoIndexing?: boolean; enableMetrics?: boolean; enableQueryCache?: boolean; queryCacheTTL?: number; enableSchemaValidation?: boolean; defaultBatchSize?: number; }>>; /** * Environment-based configuration schema * * Defines how to load knowledge graph configuration from environment variables. */ declare const KnowledgeGraphEnvConfigSchema: z.ZodObject<{ /** Whether knowledge graph is enabled */ KNOWLEDGE_GRAPH_ENABLED: z.ZodDefault; /** Backend type */ KNOWLEDGE_GRAPH_TYPE: z.ZodDefault>; /** Neo4j host */ KNOWLEDGE_GRAPH_HOST: z.ZodOptional; /** Neo4j port */ KNOWLEDGE_GRAPH_PORT: z.ZodOptional; /** Neo4j URI */ KNOWLEDGE_GRAPH_URI: z.ZodOptional; /** Neo4j username */ KNOWLEDGE_GRAPH_USERNAME: z.ZodOptional; /** Neo4j password */ KNOWLEDGE_GRAPH_PASSWORD: z.ZodOptional; /** Neo4j database name */ KNOWLEDGE_GRAPH_DATABASE: z.ZodDefault; }, "strip", z.ZodTypeAny, { KNOWLEDGE_GRAPH_ENABLED?: boolean; KNOWLEDGE_GRAPH_TYPE?: "in-memory" | "neo4j"; KNOWLEDGE_GRAPH_HOST?: string; KNOWLEDGE_GRAPH_PORT?: number; KNOWLEDGE_GRAPH_URI?: string; KNOWLEDGE_GRAPH_USERNAME?: string; KNOWLEDGE_GRAPH_PASSWORD?: string; KNOWLEDGE_GRAPH_DATABASE?: string; }, { KNOWLEDGE_GRAPH_ENABLED?: boolean; KNOWLEDGE_GRAPH_TYPE?: "in-memory" | "neo4j"; KNOWLEDGE_GRAPH_HOST?: string; KNOWLEDGE_GRAPH_PORT?: number; KNOWLEDGE_GRAPH_URI?: string; KNOWLEDGE_GRAPH_USERNAME?: string; KNOWLEDGE_GRAPH_PASSWORD?: string; KNOWLEDGE_GRAPH_DATABASE?: string; }>; type InMemoryBackendConfig$1 = z.infer; type Neo4jBackendConfig = z.infer; type BackendConfig$1 = z.infer; type KnowledgeGraphConfig = z.infer; type KnowledgeGraphEnvConfig = z.infer; /** * Parse and validate knowledge graph configuration * * @param config - Raw configuration object to validate * @returns Parsed and validated configuration * @throws {z.ZodError} If configuration is invalid * * @example * ```typescript * const config = parseKnowledgeGraphConfig({ * type: 'neo4j', * host: 'localhost', * port: 7687, * username: 'neo4j', * password: 'password' * }); * ``` */ declare function parseKnowledgeGraphConfig(config: unknown): KnowledgeGraphConfig; /** * Parse knowledge graph configuration from environment variables * * @param env - Environment variables object (defaults to process.env) * @returns Parsed configuration or null if knowledge graph is disabled * * @example * ```typescript * const config = parseKnowledgeGraphConfigFromEnv(); * if (config) { * // Knowledge graph is enabled * const graph = await createKnowledgeGraph(config); * } * ``` */ declare function parseKnowledgeGraphConfigFromEnv(env?: Record): KnowledgeGraphConfig | null; /** * Validate knowledge graph configuration without throwing * * @param config - Configuration object to validate * @returns Validation result with success flag and errors * * @example * ```typescript * const { success, data, errors } = validateKnowledgeGraphConfig(config); * if (success) { * // Use data * } else { * console.error('Configuration errors:', errors); * } * ``` */ declare function validateKnowledgeGraphConfig(config: unknown): { success: boolean; data?: KnowledgeGraphConfig; errors?: z.ZodError; }; /** * Knowledge Graph Backend Types and Error Classes * * This module defines the core types and error classes for the knowledge graph system. * The knowledge graph system provides entity-relationship storage and graph traversal capabilities. * * @module knowledge_graph/backend/types */ /** * Filters for node searches * * Supports various comparison operations for filtering nodes by properties. * * @example * ```typescript * const filters: NodeFilters = { * type: 'Function', * name: { any: ['getData', 'setData'] }, * created_at: { gte: Date.now() - 86400000 } * }; * ``` */ interface NodeFilters { [key: string]: string | number | boolean | { gte?: number; gt?: number; lte?: number; lt?: number; } | { any?: Array; } | { all?: Array; }; } /** * Filters for edge searches * * Similar to NodeFilters but for relationship filtering. * * @example * ```typescript * const edgeFilters: EdgeFilters = { * type: 'DEPENDS_ON', * strength: { gte: 0.8 } * }; * ``` */ interface EdgeFilters { [key: string]: string | number | boolean | { gte?: number; gt?: number; lte?: number; lt?: number; } | { any?: Array; } | { all?: Array; }; } /** * Graph node representation * * Represents an entity in the knowledge graph with properties and metadata. * * @example * ```typescript * const functionNode: GraphNode = { * id: 'func_123', * labels: ['Function', 'Code'], * properties: { * name: 'calculateTotal', * language: 'typescript', * file_path: 'src/utils.ts', * created_at: Date.now() * } * }; * ``` */ interface GraphNode { /** Unique identifier for the node */ id: string; /** Array of labels/types for the node */ labels: string[]; /** Properties/attributes of the node */ properties: Record; } /** * Graph edge/relationship representation * * Represents a relationship between two nodes in the knowledge graph. * * @example * ```typescript * const dependency: GraphEdge = { * id: 'rel_456', * type: 'DEPENDS_ON', * startNodeId: 'func_123', * endNodeId: 'func_456', * properties: { * strength: 0.9, * context: 'function call', * created_at: Date.now() * } * }; * ``` */ interface GraphEdge { /** Unique identifier for the edge */ id: string; /** Type/label of the relationship */ type: string; /** ID of the source node */ startNodeId: string; /** ID of the target node */ endNodeId: string; /** Properties/attributes of the relationship */ properties: Record; } /** * Graph query structure * * Defines different types of queries that can be executed on the knowledge graph. * * @example * ```typescript * // Find nodes by pattern * const nodeQuery: GraphQuery = { * type: 'node', * pattern: { * labels: ['Function'], * properties: { language: 'typescript' } * }, * limit: 10 * }; * * // Find relationships * const edgeQuery: GraphQuery = { * type: 'edge', * pattern: { * type: 'DEPENDS_ON', * properties: { strength: { gte: 0.8 } } * } * }; * * // Custom Cypher query for Neo4j * const cypherQuery: GraphQuery = { * type: 'cypher', * query: 'MATCH (n:Function)-[r:DEPENDS_ON]->(m:Function) RETURN n, r, m', * parameters: {} * }; * ``` */ interface GraphQuery { /** Type of query to execute */ type: 'node' | 'edge' | 'path' | 'cypher'; /** Query pattern (for structured queries) */ pattern?: { labels?: string[]; type?: string; properties?: Record; startNode?: Partial; endNode?: Partial; }; /** Raw query string (for cypher queries) */ query?: string; /** Query parameters */ parameters?: Record; /** Maximum number of results to return */ limit?: number; /** Number of results to skip (for pagination) */ skip?: number; } /** * Graph query result * * Contains the results of a graph query operation. * * @example * ```typescript * const result: GraphResult = { * nodes: [functionNode], * edges: [dependency], * paths: [], * metadata: { * totalCount: 1, * executionTime: 15, * queryType: 'node' * } * }; * ``` */ interface GraphResult { /** Nodes returned by the query */ nodes: GraphNode[]; /** Edges returned by the query */ edges: GraphEdge[]; /** Paths returned by the query (for path queries) */ paths?: Array<{ nodes: GraphNode[]; edges: GraphEdge[]; length: number; }>; /** Query execution metadata */ metadata: { /** Total count of available results */ totalCount?: number; /** Query execution time in milliseconds */ executionTime?: number; /** Type of query that was executed */ queryType: string; /** Additional backend-specific metadata */ [key: string]: any; }; } /** * Knowledge graph error base class * * Base error class for all knowledge graph related errors. */ declare class KnowledgeGraphError extends Error { message: string; /** The operation that failed (e.g., 'addNode', 'query', 'connect') */ readonly operation: string; /** The underlying error that caused this error, if any */ readonly cause?: Error; constructor(message: string, /** The operation that failed (e.g., 'addNode', 'query', 'connect') */ operation: string, /** The underlying error that caused this error, if any */ cause?: Error); } /** * Knowledge graph connection error * * Thrown when connection to the knowledge graph backend fails. */ declare class KnowledgeGraphConnectionError extends KnowledgeGraphError { message: string; /** The type of backend that failed to connect (e.g., 'neo4j', 'in-memory') */ readonly backendType: string; /** The underlying connection error, if any */ readonly cause?: Error; constructor(message: string, /** The type of backend that failed to connect (e.g., 'neo4j', 'in-memory') */ backendType: string, /** The underlying connection error, if any */ cause?: Error); } /** * Node not found error * * Thrown when a requested node cannot be found in the knowledge graph. */ declare class NodeNotFoundError extends KnowledgeGraphError { message: string; /** The ID of the node that was not found */ readonly nodeId: string; /** The underlying error, if any */ readonly cause?: Error; constructor(message: string, /** The ID of the node that was not found */ nodeId: string, /** The underlying error, if any */ cause?: Error); } /** * Edge not found error * * Thrown when a requested edge cannot be found in the knowledge graph. */ declare class EdgeNotFoundError extends KnowledgeGraphError { message: string; /** The ID of the edge that was not found */ readonly edgeId: string; /** The underlying error, if any */ readonly cause?: Error; constructor(message: string, /** The ID of the edge that was not found */ edgeId: string, /** The underlying error, if any */ cause?: Error); } /** * Invalid query error * * Thrown when a graph query is malformed or invalid. */ declare class InvalidQueryError extends KnowledgeGraphError { message: string; /** The invalid query that caused the error */ readonly query: string | GraphQuery; /** The underlying error, if any */ readonly cause?: Error; constructor(message: string, /** The invalid query that caused the error */ query: string | GraphQuery, /** The underlying error, if any */ cause?: Error); } /** * Graph validation error * * Thrown when graph data fails validation (e.g., duplicate nodes, invalid relationships). */ declare class GraphValidationError extends KnowledgeGraphError { message: string; /** The type of validation that failed */ readonly validationType: 'node' | 'edge' | 'schema'; /** The underlying error, if any */ readonly cause?: Error; constructor(message: string, /** The type of validation that failed */ validationType: 'node' | 'edge' | 'schema', /** The underlying error, if any */ cause?: Error); } /** * Knowledge Graph Interface * * Defines the contract for knowledge graph implementations. * Knowledge graphs are optimized for entity-relationship storage and graph traversal operations. * * Implementations can include: * - Neo4j: Production-grade graph database * - ArangoDB: Multi-model database with graph capabilities * - In-Memory: Fast local storage for development/testing * * @module knowledge_graph/backend/knowledge-graph */ /** * KnowledgeGraph Interface * * Provides a unified API for different knowledge graph implementations. * All methods are asynchronous to support both local and network-based backends. * * @example * ```typescript * class Neo4jBackend implements KnowledgeGraph { * async addNode(node: GraphNode): Promise { * const session = this.driver.session(); * await session.run( * 'CREATE (n:' + node.labels.join(':') + ' {properties})', * { properties: node.properties } * ); * await session.close(); * } * // ... other methods * } * ``` */ interface KnowledgeGraph { /** * Add a new node to the knowledge graph * * @param node - The node to add with labels and properties * @throws {GraphValidationError} If node data is invalid * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * await graph.addNode({ * id: 'func_123', * labels: ['Function', 'Code'], * properties: { * name: 'calculateTotal', * language: 'typescript' * } * }); * ``` */ addNode(node: GraphNode): Promise; /** * Add multiple nodes to the knowledge graph in batch * * @param nodes - Array of nodes to add * @throws {GraphValidationError} If any node data is invalid * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * await graph.addNodes([node1, node2, node3]); * ``` */ addNodes(nodes: GraphNode[]): Promise; /** * Get a node by its ID * * @param nodeId - The unique identifier of the node * @returns The node if found, null otherwise * * @example * ```typescript * const node = await graph.getNode('func_123'); * if (node) { * console.log(node.properties.name); * } * ``` */ getNode(nodeId: string): Promise; /** * Update a node's properties * * @param nodeId - The unique identifier of the node * @param properties - New properties to set (merged with existing) * @param labels - Optional new labels to set * @throws {NodeNotFoundError} If node doesn't exist * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * await graph.updateNode('func_123', { * updated_at: Date.now(), * complexity: 'high' * }, ['Function', 'Code', 'Complex']); * ``` */ updateNode(nodeId: string, properties: Record, labels?: string[]): Promise; /** * Delete a node and all its relationships * * @param nodeId - The unique identifier of the node to delete * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * await graph.deleteNode('func_123'); * ``` */ deleteNode(nodeId: string): Promise; /** * Find nodes matching the given filters * * @param filters - Property filters to apply * @param labels - Optional labels to filter by * @param limit - Maximum number of results to return * @returns Array of matching nodes * * @example * ```typescript * const functions = await graph.findNodes( * { language: 'typescript' }, * ['Function'], * 10 * ); * ``` */ findNodes(filters?: NodeFilters, labels?: string[], limit?: number): Promise; /** * Add a new edge (relationship) to the knowledge graph * * @param edge - The edge to add with type and properties * @throws {GraphValidationError} If edge data is invalid * @throws {NodeNotFoundError} If start or end node doesn't exist * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * await graph.addEdge({ * id: 'rel_456', * type: 'DEPENDS_ON', * startNodeId: 'func_123', * endNodeId: 'func_456', * properties: { strength: 0.9 } * }); * ``` */ addEdge(edge: GraphEdge): Promise; /** * Add multiple edges to the knowledge graph in batch * * @param edges - Array of edges to add * @throws {GraphValidationError} If any edge data is invalid * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * await graph.addEdges([edge1, edge2, edge3]); * ``` */ addEdges(edges: GraphEdge[]): Promise; /** * Get an edge by its ID * * @param edgeId - The unique identifier of the edge * @returns The edge if found, null otherwise * * @example * ```typescript * const edge = await graph.getEdge('rel_456'); * if (edge) { * console.log(edge.properties.strength); * } * ``` */ getEdge(edgeId: string): Promise; /** * Update an edge's properties * * @param edgeId - The unique identifier of the edge * @param properties - New properties to set (merged with existing) * @throws {EdgeNotFoundError} If edge doesn't exist * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * await graph.updateEdge('rel_456', { * updated_at: Date.now(), * strength: 0.95 * }); * ``` */ updateEdge(edgeId: string, properties: Record): Promise; /** * Delete an edge * * @param edgeId - The unique identifier of the edge to delete * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * await graph.deleteEdge('rel_456'); * ``` */ deleteEdge(edgeId: string): Promise; /** * Find edges matching the given filters * * @param filters - Property filters to apply * @param edgeType - Optional edge type to filter by * @param limit - Maximum number of results to return * @returns Array of matching edges * * @example * ```typescript * const dependencies = await graph.findEdges( * { strength: { gte: 0.8 } }, * 'DEPENDS_ON', * 20 * ); * ``` */ findEdges(filters?: EdgeFilters, edgeType?: string, limit?: number): Promise; /** * Execute a complex graph query * * @param query - The graph query to execute * @returns Query results containing nodes, edges, and metadata * @throws {InvalidQueryError} If query is malformed * @throws {KnowledgeGraphError} If the operation fails * * @example * ```typescript * const result = await graph.query({ * type: 'cypher', * query: 'MATCH (n:Function)-[r:DEPENDS_ON]->(m:Function) RETURN n, r, m', * limit: 100 * }); * ``` */ query(query: GraphQuery): Promise; /** * Get neighbors of a node (nodes connected by edges) * * @param nodeId - The node to get neighbors for * @param direction - Direction of relationships ('in', 'out', 'both') * @param edgeTypes - Optional edge types to filter by * @param limit - Maximum number of neighbors to return * @returns Array of neighbor nodes with their connecting edges * * @example * ```typescript * const neighbors = await graph.getNeighbors( * 'func_123', * 'out', * ['DEPENDS_ON', 'CALLS'], * 10 * ); * ``` */ getNeighbors(nodeId: string, direction?: 'in' | 'out' | 'both', edgeTypes?: string[], limit?: number): Promise>; /** * Find shortest path between two nodes * * @param startNodeId - Starting node ID * @param endNodeId - Target node ID * @param maxDepth - Maximum path length to search * @param edgeTypes - Optional edge types to traverse * @returns Path if found, null otherwise * * @example * ```typescript * const path = await graph.findPath('func_123', 'func_789', 5); * if (path) { * console.log(`Path length: ${path.edges.length}`); * } * ``` */ findPath(startNodeId: string, endNodeId: string, maxDepth?: number, edgeTypes?: string[]): Promise<{ nodes: GraphNode[]; edges: GraphEdge[]; } | null>; /** * Clear all nodes and edges from the graph * * WARNING: This will permanently delete all graph data. * * @example * ```typescript * // Use with caution! * await graph.clearGraph(); * ``` */ clearGraph(): Promise; /** * Get statistics about the graph * * @returns Object containing graph statistics * * @example * ```typescript * const stats = await graph.getStatistics(); * console.log(`Nodes: ${stats.nodeCount}, Edges: ${stats.edgeCount}`); * ``` */ getStatistics(): Promise<{ nodeCount: number; edgeCount: number; labelCounts: Record; edgeTypeCounts: Record; }>; /** * Establishes connection to the knowledge graph backend * * Should be called before performing any operations. * Implementations should handle reconnection logic internally. * * @throws {KnowledgeGraphConnectionError} If connection fails * * @example * ```typescript * const graph = new Neo4jBackend(config); * await graph.connect(); * // Now ready to use * ``` */ connect(): Promise; /** * Gracefully closes the connection to the knowledge graph * * Should clean up resources and close any open connections. * After disconnect, connect() must be called again before use. * * @example * ```typescript * // Clean shutdown * await graph.disconnect(); * ``` */ disconnect(): Promise; /** * Checks if the backend is currently connected and ready * * @returns true if connected and operational, false otherwise * * @example * ```typescript * if (!graph.isConnected()) { * await graph.connect(); * } * ``` */ isConnected(): boolean; /** * Returns the backend type identifier * * Useful for logging, monitoring, and conditional logic based on backend type. * * @returns Backend type string (e.g., 'neo4j', 'in-memory') * * @example * ```typescript * console.log(`Using ${graph.getBackendType()} for knowledge graph`); * ``` */ getBackendType(): string; } /** * Knowledge Graph Manager * * Manages the lifecycle of knowledge graph backends and provides a unified interface * for knowledge graph operations. Handles connection management, health checks, * fallback scenarios, and statistics tracking. * * @module knowledge_graph/manager */ /** * Health check result for knowledge graph */ interface HealthCheckResult$1 { backend: boolean; overall: boolean; details?: { backend?: { status: string; latency?: number; error?: string; }; }; } /** * Knowledge graph information for monitoring */ interface KnowledgeGraphInfo { connected: boolean; backend: { type: string; connected: boolean; fallback: boolean; }; connectionAttempts: number; lastError: string | undefined; } /** * Statistics for knowledge graph operations */ interface KnowledgeGraphStats { totalNodes: number; totalEdges: number; totalQueries: number; totalOperations: number; averageQueryTime: number; lastOperationTime: number; connectionUptime: number; } /** * Knowledge Graph Manager * * Provides a high-level interface for managing knowledge graph operations. * Handles backend lifecycle, connection management, and error recovery. * * @example * ```typescript * const manager = new KnowledgeGraphManager(config); * await manager.connect(); * * const graph = manager.getGraph(); * await graph.addNode({ * id: 'node1', * labels: ['Function'], * properties: { name: 'myFunction' } * }); * ``` */ declare class KnowledgeGraphManager { private graph; private connected; private readonly config; private readonly logger; private connectionAttempts; private lastConnectionError?; private connectionStartTime; private backendMetadata; private stats; private static neo4jModule?; private static inMemoryModule?; private readonly healthCheckInterval; private healthCheckTimer?; /** * Creates a new Knowledge Graph Manager * * @param config - Knowledge graph configuration */ constructor(config: KnowledgeGraphConfig); /** * Get the current configuration */ getConfig(): Readonly; /** * Get manager information for monitoring */ getInfo(): KnowledgeGraphInfo; /** * Get the knowledge graph instance */ getGraph(): KnowledgeGraph | null; /** * Check if the manager is connected and ready */ isConnected(): boolean; /** * Connect to the knowledge graph backend */ connect(): Promise; /** * Disconnect from the knowledge graph backend */ disconnect(): Promise; /** * Perform health check on the knowledge graph backend */ healthCheck(): Promise; /** * Get current statistics */ getStats(): KnowledgeGraphStats; /** * Reset statistics */ resetStats(): void; /** * Execute a knowledge graph operation with statistics tracking */ executeOperation(operation: (graph: KnowledgeGraph) => Promise, operationType?: 'read' | 'write' | 'query'): Promise; /** * Get backend-specific debug information */ getDebugInfo(): Record; private createBackend; private createNeo4jBackend; private createInMemoryBackend; private createInMemoryFallback; private updateStatistics; private updateOperationStats; private startHealthMonitoring; private stopHealthMonitoring; /** * Create a new manager instance from environment configuration */ static createFromEnv(): Promise; /** * Create a default in-memory manager for testing/development */ static createDefault(): KnowledgeGraphManager; } /** * Core types and interfaces for the internal tools system. * * This module defines the type system for internal tools that work alongside * MCP tools to provide built-in agent capabilities like memory management, * session control, and system operations. */ /** * Categories for organizing internal tools */ type InternalToolCategory = 'memory' | 'session' | 'system' | 'knowledge_graph'; /** * Internal tool handler function signature */ type InternalToolHandler = (args: T, context?: InternalToolContext) => Promise; /** * Internal tool definition extending the base Tool interface */ interface InternalTool extends Tool { /** * Unique name for the tool (should be prefixed with 'cipher_') */ name: string; /** * Category for organizing tools */ category: InternalToolCategory; /** * Marker to identify this as an internal tool */ internal: true; /** * Whether this tool should be accessible to agents * - true: Tool can be called by agents (e.g., search tools) * - false: Tool is internal-only, used for background processing (e.g., extraction, storage) * @default true */ agentAccessible?: boolean; /** * Handler function that executes the tool */ handler: InternalToolHandler; /** * Optional version for tool evolution */ version?: string; /** * Human-readable description */ description: string; /** * JSON schema for parameters */ parameters: { type: 'object'; properties: Record; required?: string[]; }; } /** * Collection of internal tools indexed by their names */ interface InternalToolSet { [toolName: string]: InternalTool; } /** * Configuration for the internal tool manager */ interface InternalToolManagerConfig { /** * Whether to enable internal tools * @default true */ enabled?: boolean; /** * Maximum execution timeout for internal tools in milliseconds * @default 30000 (30 seconds) */ timeout?: number; /** * Whether to cache tool lookups for performance * @default true */ enableCache?: boolean; /** * Cache timeout in milliseconds * @default 300000 (5 minutes) */ cacheTimeout?: number; } /** * Tool execution context provided to handlers */ interface InternalToolContext { /** * Tool name being executed */ toolName: string; /** * Execution start time */ startTime: number; /** * Optional session ID if available */ sessionId: string | undefined; /** * Any additional metadata */ metadata: Record | undefined; /** * Optional agent services for advanced tool operations */ services?: { /** * Embedding manager for text embeddings */ embeddingManager?: EmbeddingManager; /** * Vector storage manager for similarity search */ vectorStoreManager?: VectorStoreManager; /** * LLM service for intelligent reasoning (Phase 3) */ llmService?: ILLMService; /** * Knowledge graph manager for graph operations */ knowledgeGraphManager?: KnowledgeGraphManager; }; /** * User ID for personalized behavior */ userId?: string; } /** * Statistics for internal tool usage */ interface ToolExecutionStats { /** * Tool name */ toolName: string; /** * Total executions */ totalExecutions: number; /** * Successful executions */ successfulExecutions: number; /** * Failed executions */ failedExecutions: number; /** * Average execution time in milliseconds */ averageExecutionTime: number; /** * Last execution timestamp */ lastExecution?: string; /** * Last error message */ lastError?: string; } /** * Interface for internal tool manager */ interface IInternalToolManager { /** * Initialize the internal tool manager */ initialize(): Promise; /** * Register a new internal tool */ registerTool(tool: InternalTool): { success: boolean; message: string; conflictedWith?: string; }; /** * Unregister an internal tool */ unregisterTool(toolName: string): boolean; /** * Get all registered internal tools */ getAllTools(): InternalToolSet; /** * Get a specific internal tool by name */ getTool(toolName: string): InternalTool | undefined; /** * Check if a tool name is an internal tool */ isInternalTool(toolName: string): boolean; /** * Execute an internal tool */ executeTool(toolName: string, args: any, context?: Partial): Promise; /** * Get tools by category */ getToolsByCategory(category: InternalToolCategory): InternalToolSet; /** * Get execution statistics for a tool */ getToolStats(toolName: string): ToolExecutionStats | undefined; /** * Get overall manager statistics */ getManagerStats(): { totalTools: number; toolsByCategory: Record; totalExecutions: number; }; /** * Clear all execution statistics */ clearStats(): void; /** * Shutdown the internal tool manager */ shutdown(): Promise; } /** * Internal Tool Manager * * Manages execution of internal tools with caching, statistics tracking, * and integration with the broader agent architecture. */ /** * Internal Tool Manager implementation */ declare class InternalToolManager implements IInternalToolManager { private config; private registry; private initialized; private stats; private readonly maxExecutionHistorySize; private eventManager?; private services?; constructor(config?: InternalToolManagerConfig); /** * Initialize the internal tool manager */ initialize(): Promise; /** * Register a new internal tool */ registerTool(tool: InternalTool): { success: boolean; message: string; conflictedWith?: string; }; /** * Unregister an internal tool */ unregisterTool(toolName: string): boolean; /** * Get all registered internal tools */ getAllTools(): InternalToolSet; /** * Get a specific internal tool by name */ getTool(toolName: string): InternalTool | undefined; /** * Check if a tool name is an internal tool */ isInternalTool(toolName: string): boolean; /** * Execute an internal tool */ executeTool(toolName: string, args: any, context?: Partial): Promise; /** * Get tools by category */ getToolsByCategory(category: InternalToolCategory): InternalToolSet; /** * Get execution statistics for a tool */ getToolStats(toolName: string): ToolExecutionStats | undefined; /** * Get overall manager statistics */ getManagerStats(): { totalTools: number; toolsByCategory: Record; totalExecutions: number; }; /** * Get all tool statistics */ getStatistics(): Record; /** * Get available tools list */ getAvailableTools(): Promise>; /** * Clear all execution statistics */ clearStats(): void; /** * Shutdown the internal tool manager */ shutdown(): Promise; /** * Execute tool with timeout handling */ private executeWithTimeout; /** * Record tool execution statistics */ private recordExecution; /** * Initialize statistics for a tool */ private initializeToolStats; /** * Create a new stats entry */ private createStatsEntry; /** * Ensure the manager is initialized */ private ensureInitialized; /** * Get configuration */ getConfig(): Required; /** * Check if manager is initialized */ isInitialized(): boolean; /** * Check if manager is enabled */ isEnabled(): boolean; /** * Set agent services for tools that need access to them */ setServices(services: { embeddingManager?: any; vectorStoreManager?: any; llmService?: any; knowledgeGraphManager?: any; }): void; /** * Set the event manager for emitting tool execution events */ setEventManager(eventManager: EventManager): void; } /** * Unified Tool Manager * * Combines MCP tools and internal tools into a single interface for LLM services. * Handles tool routing, execution, and conflict resolution between different tool sources. */ /** * Configuration for the unified tool manager */ interface UnifiedToolManagerConfig { /** * Whether to enable internal tools * @default true */ enableInternalTools?: boolean; /** * Whether to enable MCP tools * @default true */ enableMcpTools?: boolean; /** * How to handle tool name conflicts * @default 'prefix-internal' */ conflictResolution?: 'prefix-internal' | 'prefer-internal' | 'prefer-mcp' | 'error'; /** * Timeout for tool execution in milliseconds * @default 30000 */ executionTimeout?: number; /** * Operating mode - affects which tools are exposed * - 'cli': Only search tools exposed to Cipher's LLM (background tools still executable) * - 'default': Only ask_cipher tool exposed to external MCP clients * - 'aggregator': All tools exposed to external MCP clients * - 'api': Similar to CLI mode * @default 'default' */ mode?: 'cli' | 'default' | 'aggregator' | 'api'; } /** * Combined tool information for LLM services */ interface CombinedToolSet { [toolName: string]: { description: string; parameters: any; source: 'internal' | 'mcp'; }; } /** * Unified Tool Manager that combines MCP and internal tools */ declare class UnifiedToolManager { private mcpManager; private internalToolManager; private config; private eventManager?; private toolsAlreadyLogged; private embeddingManager?; constructor(mcpManager: MCPManager, internalToolManager: InternalToolManager, config?: UnifiedToolManagerConfig); /** * Set the event manager for emitting tool execution events */ setEventManager(eventManager: EventManager): void; /** * Set the embedding manager for checking embedding status */ setEmbeddingManager(embeddingManager: any): void; /** * Check if embeddings are disabled globally */ private areEmbeddingsDisabled; /** * Check if a tool is embedding-related and should be excluded when embeddings are disabled */ private isEmbeddingRelatedTool; /** * Get all available tools from both sources * Filters tools based on mode: * - CLI mode: Only search tools + MCP tools (background tools excluded from agent access) * - Default MCP mode: Only ask_cipher tool * - Aggregator MCP mode: All tools */ getAllTools(): Promise; /** * Execute a tool by routing to the appropriate manager */ executeTool(toolName: string, args: any, sessionId?: string): Promise; /** * Execute a tool without triggering redundant tool loading (for background operations) * This method bypasses the normal tool loading process when tools are already loaded */ executeToolWithoutLoading(toolName: string, args: any, sessionId?: string): Promise; /** * Check if a background tool exists (for internal execution, not agent access) */ isBackgroundToolAvailable(toolName: string): boolean; /** * Check if a tool is available (to agents) based on current mode */ isToolAvailable(toolName: string): Promise; /** * Get tool source (internal or mcp) for agent-accessible tools */ getToolSource(toolName: string): Promise<'internal' | 'mcp' | null>; /** * Get tools formatted for specific LLM providers */ getToolsForProvider(provider: 'openai' | 'anthropic' | 'openrouter' | 'aws' | 'azure' | 'qwen' | 'gemini'): Promise; /** * Get manager statistics */ getStats(): { internalTools: any; mcpTools: any; config: Required; }; /** * Handle tool name conflicts */ private handleToolConflict; /** * Format tools for OpenAI/OpenRouter (function calling format) */ private formatToolsForOpenAI; /** * Format tools for Anthropic (tool use format) */ private formatToolsForAnthropic; /** * Format tools for Gemini (function calling format - same as OpenAI) */ private formatToolsForGemini; } declare class OpenRouterService implements ILLMService { private client; private model; private mcpManager; private unifiedToolManager; private contextManager; private maxIterations; private eventManager?; constructor(client: OpenAI, model: string, mcpManager: MCPManager, contextManager: ContextManager, maxIterations?: number, unifiedToolManager?: UnifiedToolManager); setEventManager(eventManager: EventManager): void; generate(userInput: string, imageData?: ImageData): Promise; /** * Direct generate method that bypasses conversation context * Used for internal tool operations that shouldn't pollute conversation history * @param userInput - The input to generate a response for * @param systemPrompt - Optional system prompt to use * @returns Promise - The generated response */ directGenerate(userInput: string, systemPrompt?: string): Promise; getAllTools(): Promise; getConfig(): LLMServiceConfig; private getAIResponseWithRetries; private formatToolsForOpenRouter; } declare class OllamaService implements ILLMService { private openai; private model; private mcpManager; private unifiedToolManager; private contextManager; private maxIterations; private eventManager?; constructor(openai: OpenAI, model: string, mcpManager: MCPManager, contextManager: ContextManager, maxIterations?: number, unifiedToolManager?: UnifiedToolManager); /** * Set the event manager for emitting LLM response events */ setEventManager(eventManager: EventManager): void; generate(userInput: string, imageData?: ImageData): Promise; /** * Direct generate method that bypasses conversation context * Used for internal tool operations that shouldn't pollute conversation history * @param userInput - The input to generate a response for * @param systemPrompt - Optional system prompt to use * @returns Promise - The generated response */ directGenerate(userInput: string, systemPrompt?: string): Promise; getAllTools(): Promise; getConfig(): LLMServiceConfig; private getAIResponseWithRetries; private formatToolsForOpenAI; } declare class LMStudioService implements ILLMService { private openai; private model; private mcpManager; private unifiedToolManager; private contextManager; private maxIterations; private eventManager?; constructor(openai: OpenAI, model: string, mcpManager: MCPManager, contextManager: ContextManager, maxIterations?: number, unifiedToolManager?: UnifiedToolManager); setEventManager(eventManager: EventManager): void; generate(userInput: string, imageData?: ImageData): Promise; /** * Direct generate method that bypasses conversation context * Used for internal tool operations that shouldn't pollute conversation history * @param userInput - The input to generate a response for * @param systemPrompt - Optional system prompt to use * @returns Promise - The generated response */ directGenerate(userInput: string, systemPrompt?: string): Promise; getAllTools(): Promise; getConfig(): LLMServiceConfig; private getAIResponseWithRetries; private formatToolsForLMStudio; } declare class AwsService implements ILLMService { private client; private model; private mcpManager; private unifiedToolManager; private contextManager; private maxIterations; private modelFamily; private inferenceProfileArn; private formatter; private eventManager?; constructor(model: string, mcpManager: MCPManager, contextManager: ContextManager, unifiedToolManager?: UnifiedToolManager, maxIterations?: number, awsConfig?: AwsConfig); setEventManager(eventManager: EventManager): void; private detectModelFamily; generate(userInput: string, imageData?: ImageData): Promise; directGenerate(userInput: string, systemPrompt?: string): Promise; getAllTools(): Promise; getConfig(): LLMServiceConfig; private getAIResponse; private parseResponse; private parseAnthropicResponse; private parseLlamaResponse; private parseTitanResponse; private parseAI21Response; private parseDeepSeekResponse; private formatToolsForBedrock; } declare class AzureService implements ILLMService { private client; private model; private mcpManager; private unifiedToolManager; private contextManager; private maxIterations; private deploymentName; private eventManager?; constructor(model: string, mcpManager: MCPManager, contextManager: ContextManager, unifiedToolManager?: UnifiedToolManager, maxIterations?: number, azureConfig?: AzureConfig); setEventManager(eventManager: EventManager): void; generate(userInput: string, imageData?: ImageData): Promise; /** * Direct generate method that bypasses conversation context * Used for internal tool operations that shouldn't pollute conversation history * @param userInput - The input to generate a response for * @param systemPrompt - Optional system prompt to use * @returns Promise - The generated response */ directGenerate(userInput: string, systemPrompt?: string): Promise; getAllTools(): Promise; getConfig(): LLMServiceConfig; private getAIResponseWithRetries; private formatToolsForAzure; } declare class CantInferProviderError extends Error { constructor(model: string); } /** * Cache Backend Interface * * Defines the contract for cache storage implementations. * Cache backends are optimized for fast, ephemeral storage with optional TTL support. * * Implementations can include: * - Redis: Distributed caching with network access * - In-Memory: Fast local caching with no persistence * - Memcached: Distributed memory caching system * * @module storage/backend/cache-backend */ /** * CacheBackend Interface * * Provides a unified API for different cache storage implementations. * All methods are asynchronous to support both local and network-based backends. * * @example * ```typescript * class RedisBackend implements CacheBackend { * async get(key: string): Promise { * const value = await this.redis.get(key); * return value ? JSON.parse(value) : undefined; * } * // ... other methods * } * ``` */ interface CacheBackend { /** * Retrieves a value from the cache by key * * @template T - The type of the cached value * @param key - The cache key to retrieve * @returns The cached value if found, undefined otherwise * * @example * ```typescript * const user = await cache.get('user:123'); * if (!user) { * // Cache miss - fetch from database * } * ``` */ get(key: string): Promise; /** * Stores a value in the cache with optional TTL * * @template T - The type of the value to cache * @param key - The cache key * @param value - The value to cache (will be serialized) * @param ttlSeconds - Optional time-to-live in seconds * * @example * ```typescript * // Cache for 1 hour * await cache.set('user:123', userData, 3600); * * // Cache indefinitely * await cache.set('config', configData); * ``` */ set(key: string, value: T, ttlSeconds?: number): Promise; /** * Removes a value from the cache * * @param key - The cache key to delete * * @example * ```typescript * // Invalidate user cache after update * await cache.delete('user:123'); * ``` */ delete(key: string): Promise; /** * Establishes connection to the cache backend * * Should be called before performing any operations. * Implementations should handle reconnection logic internally. * * @throws {StorageConnectionError} If connection fails * * @example * ```typescript * const cache = new RedisBackend(config); * await cache.connect(); * // Now ready to use * ``` */ connect(): Promise; /** * Gracefully closes the connection to the cache backend * * Should clean up resources and close any open connections. * After disconnect, connect() must be called again before use. * * @example * ```typescript * // Clean shutdown * await cache.disconnect(); * ``` */ disconnect(): Promise; /** * Checks if the backend is currently connected and ready * * @returns true if connected and operational, false otherwise * * @example * ```typescript * if (!cache.isConnected()) { * await cache.connect(); * } * ``` */ isConnected(): boolean; /** * Returns the backend type identifier * * Useful for logging, monitoring, and conditional logic based on backend type. * * @returns Backend type string (e.g., 'redis', 'memory', 'memcached') * * @example * ```typescript * console.log(`Using ${cache.getBackendType()} for caching`); * ``` */ getBackendType(): string; } /** * Database Backend Interface * * Defines the contract for persistent storage implementations. * Database backends are optimized for reliable, long-term data storage. * * Implementations can include: * - SQLite: Lightweight, file-based database * - PostgreSQL: Full-featured relational database * - In-Memory: For testing or temporary persistence * * @module storage/backend/database-backend */ /** * DatabaseBackend Interface * * Provides a unified API for different database storage implementations. * Extends basic key-value operations with list operations for collections. * * @example * ```typescript * class SqliteBackend implements DatabaseBackend { * async get(key: string): Promise { * const row = await this.db.get('SELECT value FROM store WHERE key = ?', key); * return row ? JSON.parse(row.value) : undefined; * } * // ... other methods * } * ``` */ interface DatabaseBackend { /** * Retrieves a value from the database by key * * @template T - The type of the stored value * @param key - The storage key to retrieve * @returns The stored value if found, undefined otherwise * * @example * ```typescript * const settings = await db.get('app:settings'); * ``` */ get(key: string): Promise; /** * Stores a value in the database * * Unlike cache, database storage is persistent and doesn't support TTL. * * @template T - The type of the value to store * @param key - The storage key * @param value - The value to store (will be serialized) * * @example * ```typescript * await db.set('user:123', userData); * ``` */ set(key: string, value: T): Promise; /** * Removes a value from the database * * @param key - The storage key to delete * * @example * ```typescript * await db.delete('user:123'); * ``` */ delete(key: string): Promise; /** * Lists all keys matching a prefix * * Useful for finding related data or implementing namespaces. * * @param prefix - The key prefix to search for * @returns Array of keys matching the prefix * * @example * ```typescript * // Get all user keys * const userKeys = await db.list('user:'); * // Returns: ['user:123', 'user:456', ...] * ``` */ list(prefix: string): Promise; /** * Appends an item to a list stored at the given key * * Creates the list if it doesn't exist. Useful for logs, history, etc. * * @template T - The type of items in the list * @param key - The storage key for the list * @param item - The item to append * * @example * ```typescript * // Add to user's activity log * await db.append('activity:user:123', { * action: 'login', * timestamp: Date.now() * }); * ``` */ append(key: string, item: T): Promise; /** * Retrieves a range of items from a list * * Supports pagination through stored lists. * * @template T - The type of items in the list * @param key - The storage key for the list * @param start - Starting index (0-based) * @param count - Number of items to retrieve * @returns Array of items in the specified range * * @example * ```typescript * // Get latest 10 activities * const activities = await db.getRange('activity:user:123', 0, 10); * ``` */ getRange(key: string, start: number, count: number): Promise; /** * Establishes connection to the database backend * * Should be called before performing any operations. * May create database schema/tables if needed. * * @throws {StorageConnectionError} If connection fails * * @example * ```typescript * const db = new SqliteBackend(config); * await db.connect(); * ``` */ connect(): Promise; /** * Gracefully closes the database connection * * Should ensure all pending writes are completed before closing. * * @example * ```typescript * await db.disconnect(); * ``` */ disconnect(): Promise; /** * Checks if the backend is currently connected * * @returns true if connected and operational, false otherwise */ isConnected(): boolean; /** * Returns the backend type identifier * * @returns Backend type string (e.g., 'sqlite', 'postgresql', 'memory') */ getBackendType(): string; } /** * Storage Configuration Module * * Defines the configuration schemas for the storage system using Zod for * runtime validation and type safety. Supports multiple backend types * with different configuration requirements. * * The storage system uses a dual-backend architecture: * - Cache Backend: For fast, ephemeral storage * - Database Backend: For persistent, reliable storage * * Supported backends: * - In-Memory: Fast local storage for development/testing * - Redis: Distributed cache for production use * - SQLite: Lightweight file-based database * - PostgreSQL: Full-featured relational database (planned) * * @module storage/config */ /** * In-Memory Backend Configuration * * Simple in-memory storage for development and testing. * Data is lost when the process exits. * * @example * ```typescript * const config: InMemoryBackendConfig = { * type: 'in-memory', * maxConnections: 1, * options: { maxSize: '100mb' } * }; * ``` */ declare const InMemoryBackendSchema: z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"in-memory">; }, "strict", z.ZodTypeAny, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }>; type InMemoryBackendConfig = z.infer; /** * Redis Backend Configuration * * Configuration for Redis-based cache backend. * Supports both direct connection parameters and connection URLs. * * @example * ```typescript * // Using connection URL * const config: RedisBackendConfig = { * type: 'redis', * url: 'redis://user:pass@localhost:6379/0' * }; * * // Using individual parameters * const config: RedisBackendConfig = { * type: 'redis', * host: 'localhost', * port: 6379, * password: 'secret', * database: 0 * }; * ``` */ declare const RedisBackendSchema: z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"redis">; /** Redis connection URL (redis://...) - overrides individual params if provided */ url: z.ZodOptional; /** Redis server hostname */ host: z.ZodOptional; /** Redis server port (default: 6379) */ port: z.ZodOptional; /** Redis authentication username */ username: z.ZodOptional; /** Redis authentication password */ password: z.ZodOptional; /** Redis database number (0-15, default: 0) */ database: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; }, { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; }>; type RedisBackendConfig = z.infer; /** * SQLite Backend Configuration * * Configuration for SQLite file-based database backend. * Supports automatic path resolution if path is not provided. * * @example * ```typescript * const config: SqliteBackendConfig = { * type: 'sqlite', * path: './data', // Directory for database file * database: 'myapp.db', // Database filename * connectionTimeoutMillis: 5000 * }; * ``` */ declare const SqliteBackendSchema: z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"sqlite">; /** * SQLite database file path. * If not provided, will auto-detect using the path resolver. */ path: z.ZodOptional; /** Database filename (default: cipher.db) */ database: z.ZodOptional; }, "strict", z.ZodTypeAny, { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }, { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }>; type SqliteBackendConfig = z.infer; /** * PostgreSQL Backend Configuration * * Configuration for PostgreSQL database backend. * Supports both connection URL and individual connection parameters. * * @example * ```typescript * // Using connection URL * const config: PostgresBackendConfig = { * type: 'postgres', * url: 'postgresql://user:password@localhost:5432/mydb' * }; * * // Using individual parameters * const config: PostgresBackendConfig = { * type: 'postgres', * host: 'localhost', * port: 5432, * database: 'mydb', * user: 'postgres', * password: 'secret' * }; * ``` */ declare const PostgresBackendSchema: z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"postgres">; /** PostgreSQL connection URL (postgresql://...) - overrides individual params if provided */ url: z.ZodOptional; /** PostgreSQL server hostname */ host: z.ZodOptional; /** PostgreSQL server port (default: 5432) */ port: z.ZodOptional; /** Database name */ database: z.ZodOptional; /** Username for authentication */ user: z.ZodOptional; /** Password for authentication */ password: z.ZodOptional; /** Enable SSL connection (default: false) */ ssl: z.ZodOptional; /** Connection pool settings */ pool: z.ZodOptional; /** Maximum number of connections in pool */ max: z.ZodOptional; /** Connection idle timeout in ms */ idleTimeoutMillis: z.ZodOptional; /** Connection acquire timeout in ms */ acquireTimeoutMillis: z.ZodOptional; }, "strip", z.ZodTypeAny, { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }, { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }>>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }, { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }>; type PostgresBackendConfig = z.infer; /** * Backend Configuration Union Schema * * Discriminated union of all supported backend configurations. * Uses the 'type' field to determine which configuration schema to apply. * * Includes custom validation to ensure Redis backends have required connection info. */ declare const BackendConfigSchema: z.ZodEffects; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"in-memory">; }, "strict", z.ZodTypeAny, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"redis">; /** Redis connection URL (redis://...) - overrides individual params if provided */ url: z.ZodOptional; /** Redis server hostname */ host: z.ZodOptional; /** Redis server port (default: 6379) */ port: z.ZodOptional; /** Redis authentication username */ username: z.ZodOptional; /** Redis authentication password */ password: z.ZodOptional; /** Redis database number (0-15, default: 0) */ database: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; }, { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"sqlite">; /** * SQLite database file path. * If not provided, will auto-detect using the path resolver. */ path: z.ZodOptional; /** Database filename (default: cipher.db) */ database: z.ZodOptional; }, "strict", z.ZodTypeAny, { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }, { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"postgres">; /** PostgreSQL connection URL (postgresql://...) - overrides individual params if provided */ url: z.ZodOptional; /** PostgreSQL server hostname */ host: z.ZodOptional; /** PostgreSQL server port (default: 5432) */ port: z.ZodOptional; /** Database name */ database: z.ZodOptional; /** Username for authentication */ user: z.ZodOptional; /** Password for authentication */ password: z.ZodOptional; /** Enable SSL connection (default: false) */ ssl: z.ZodOptional; /** Connection pool settings */ pool: z.ZodOptional; /** Maximum number of connections in pool */ max: z.ZodOptional; /** Connection idle timeout in ms */ idleTimeoutMillis: z.ZodOptional; /** Connection acquire timeout in ms */ acquireTimeoutMillis: z.ZodOptional; }, "strip", z.ZodTypeAny, { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }, { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }>>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }, { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }>]>, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }>; type BackendConfig = z.infer; /** * Storage System Configuration Schema * * Top-level configuration for the dual-backend storage system. * Requires configuration for both cache and database backends. * * @example * ```typescript * const storageConfig: StorageConfig = { * cache: { * type: 'redis', * host: 'localhost', * port: 6379 * }, * database: { * type: 'sqlite', * path: './data', * database: 'app.db' * } * }; * ``` */ declare const StorageSchema: z.ZodObject<{ /** Cache backend for fast, ephemeral storage (Redis, In-Memory) */ cache: z.ZodEffects; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"in-memory">; }, "strict", z.ZodTypeAny, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"redis">; /** Redis connection URL (redis://...) - overrides individual params if provided */ url: z.ZodOptional; /** Redis server hostname */ host: z.ZodOptional; /** Redis server port (default: 6379) */ port: z.ZodOptional; /** Redis authentication username */ username: z.ZodOptional; /** Redis authentication password */ password: z.ZodOptional; /** Redis database number (0-15, default: 0) */ database: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; }, { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"sqlite">; /** * SQLite database file path. * If not provided, will auto-detect using the path resolver. */ path: z.ZodOptional; /** Database filename (default: cipher.db) */ database: z.ZodOptional; }, "strict", z.ZodTypeAny, { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }, { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"postgres">; /** PostgreSQL connection URL (postgresql://...) - overrides individual params if provided */ url: z.ZodOptional; /** PostgreSQL server hostname */ host: z.ZodOptional; /** PostgreSQL server port (default: 5432) */ port: z.ZodOptional; /** Database name */ database: z.ZodOptional; /** Username for authentication */ user: z.ZodOptional; /** Password for authentication */ password: z.ZodOptional; /** Enable SSL connection (default: false) */ ssl: z.ZodOptional; /** Connection pool settings */ pool: z.ZodOptional; /** Maximum number of connections in pool */ max: z.ZodOptional; /** Connection idle timeout in ms */ idleTimeoutMillis: z.ZodOptional; /** Connection acquire timeout in ms */ acquireTimeoutMillis: z.ZodOptional; }, "strip", z.ZodTypeAny, { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }, { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }>>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }, { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }>]>, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }>; /** Database backend for persistent, reliable storage (SQLite, PostgreSQL) */ database: z.ZodEffects; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"in-memory">; }, "strict", z.ZodTypeAny, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"redis">; /** Redis connection URL (redis://...) - overrides individual params if provided */ url: z.ZodOptional; /** Redis server hostname */ host: z.ZodOptional; /** Redis server port (default: 6379) */ port: z.ZodOptional; /** Redis authentication username */ username: z.ZodOptional; /** Redis authentication password */ password: z.ZodOptional; /** Redis database number (0-15, default: 0) */ database: z.ZodOptional; }, "strict", z.ZodTypeAny, { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; }, { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"sqlite">; /** * SQLite database file path. * If not provided, will auto-detect using the path resolver. */ path: z.ZodOptional; /** Database filename (default: cipher.db) */ database: z.ZodOptional; }, "strict", z.ZodTypeAny, { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }, { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; }>, z.ZodObject<{ /** Maximum number of concurrent connections to the backend */ maxConnections: z.ZodOptional; /** Time in milliseconds before an idle connection is closed */ idleTimeoutMillis: z.ZodOptional; /** Time in milliseconds to wait for a connection to be established */ connectionTimeoutMillis: z.ZodOptional; /** Backend-specific options that vary by implementation */ options: z.ZodOptional>; } & { type: z.ZodLiteral<"postgres">; /** PostgreSQL connection URL (postgresql://...) - overrides individual params if provided */ url: z.ZodOptional; /** PostgreSQL server hostname */ host: z.ZodOptional; /** PostgreSQL server port (default: 5432) */ port: z.ZodOptional; /** Database name */ database: z.ZodOptional; /** Username for authentication */ user: z.ZodOptional; /** Password for authentication */ password: z.ZodOptional; /** Enable SSL connection (default: false) */ ssl: z.ZodOptional; /** Connection pool settings */ pool: z.ZodOptional; /** Maximum number of connections in pool */ max: z.ZodOptional; /** Connection idle timeout in ms */ idleTimeoutMillis: z.ZodOptional; /** Connection acquire timeout in ms */ acquireTimeoutMillis: z.ZodOptional; }, "strip", z.ZodTypeAny, { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }, { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }>>; }, "strict", z.ZodTypeAny, { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }, { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }>]>, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }, { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }>; }, "strict", z.ZodTypeAny, { database?: { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }; cache?: { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }; }, { database?: { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }; cache?: { options?: Record; type?: "in-memory"; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "redis"; password?: string; database?: number; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; username?: string; } | { path?: string; options?: Record; type?: "sqlite"; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; } | { options?: Record; type?: "postgres"; password?: string; user?: string; database?: string; maxConnections?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number; url?: string; host?: string; port?: number; ssl?: boolean; pool?: { idleTimeoutMillis?: number; min?: number; max?: number; acquireTimeoutMillis?: number; }; }; }>; type StorageConfig = z.infer; /** * Storage Backend Types and Error Classes * * This module defines the core types and error classes for the storage system. * The storage system uses a dual-backend architecture: * - Cache Backend: For fast, ephemeral storage (e.g., Redis, in-memory) * - Database Backend: For persistent, reliable storage (e.g., SQLite, PostgreSQL) * * @module storage/backend/types */ /** * StorageBackends Interface * * Represents the dual-backend storage system with separate backends for * different use cases: * - cache: Fast access for temporary data, session storage, etc. * - database: Persistent storage for long-term data, user data, etc. * * @example * ```typescript * const storage: StorageBackends = { * cache: new RedisBackend(redisConfig), * database: new SqliteBackend(sqliteConfig) * }; * ``` */ interface StorageBackends { /** Fast, ephemeral storage backend (Redis, Memory) for caching and temporary data */ cache: CacheBackend; /** Persistent, reliable storage backend (PostgreSQL, SQLite, Memory) for long-term data */ database: DatabaseBackend; } /** * Base Storage Error Class * * All storage-related errors extend from this base class. * Provides consistent error structure with operation context and optional cause. * * @example * ```typescript * throw new StorageError('Failed to save data', 'set', originalError); * ``` */ declare class StorageError extends Error { /** The operation that failed (e.g., 'get', 'set', 'delete', 'connection') */ readonly operation: string; /** The underlying error that caused this error, if any */ readonly cause?: Error; constructor(message: string, /** The operation that failed (e.g., 'get', 'set', 'delete', 'connection') */ operation: string, /** The underlying error that caused this error, if any */ cause?: Error); } /** * Storage Connection Error * * Thrown when a storage backend fails to connect or loses connection. * Includes the backend type for easier debugging. * * @example * ```typescript * throw new StorageConnectionError( * 'Failed to connect to Redis', * 'redis', * redisError * ); * ``` */ declare class StorageConnectionError extends StorageError { message: string; /** The type of backend that failed to connect (e.g., 'redis', 'sqlite') */ readonly backendType: string; /** The underlying connection error, if any */ readonly cause?: Error; constructor(message: string, /** The type of backend that failed to connect (e.g., 'redis', 'sqlite') */ backendType: string, /** The underlying connection error, if any */ cause?: Error); } /** * Storage Not Found Error * * Thrown when attempting to retrieve a key that doesn't exist in storage. * Useful for distinguishing between actual errors and missing data. * * @example * ```typescript * const value = await cache.get(key); * if (!value) { * throw new StorageNotFoundError(`Key not found: ${key}`, key); * } * ``` */ declare class StorageNotFoundError extends StorageError { message: string; /** The key that was not found */ readonly key: string; /** The underlying error, if any */ readonly cause?: Error; constructor(message: string, /** The key that was not found */ key: string, /** The underlying error, if any */ cause?: Error); } /** * Storage Manager Implementation * * Orchestrates the dual-backend storage system with cache and database backends. * Provides lazy loading, graceful fallbacks, and connection management. * * @module storage/manager */ /** * Health check result for storage backends */ interface HealthCheckResult { cache: boolean; database: boolean; overall: boolean; details?: { cache?: { status: string; latency?: number; error?: string; }; database?: { status: string; latency?: number; error?: string; }; }; } /** * Storage system information */ interface StorageInfo { connected: boolean; backends: { cache: { type: string; connected: boolean; fallback: boolean; }; database: { type: string; connected: boolean; fallback: boolean; }; }; connectionAttempts: number; lastError: string | undefined; } /** * Storage Manager * * Manages the lifecycle of storage backends with lazy loading and fallback support. * Follows the factory pattern with graceful degradation to in-memory storage. * * @example * ```typescript * const manager = new StorageManager(config); * const { cache, database } = await manager.connect(); * * // Use backends * await cache.set('key', value, 300); * await database.set('user:123', userData); * * // Cleanup * await manager.disconnect(); * ``` */ declare class StorageManager { private cache; private database; private connected; private readonly config; private readonly logger; private connectionAttempts; private lastConnectionError?; private cacheMetadata; private databaseMetadata; private static redisModule?; private static sqliteModule?; private static postgresModule?; private readonly healthCheckKey; private readonly healthCheckTimeout; /** * Creates a new StorageManager instance * * @param config - Storage configuration with cache and database backend configs * @throws {Error} If configuration is invalid */ constructor(config: StorageConfig); /** * Get the current storage configuration * * @returns The storage configuration */ getConfig(): Readonly; /** * Get information about the storage system * * @returns Storage system information including connection status and backend types */ getInfo(): StorageInfo; /** * Get the current storage backends if connected * * @returns The storage backends or null if not connected */ getBackends(): StorageBackends | null; /** * Check if the storage manager is connected * * @returns true if both backends are connected */ isConnected(): boolean; /** * Connect to storage backends * * @returns The connected storage backends * @throws {StorageConnectionError} If strict backends fail to connect */ connect(): Promise; /** * Disconnect from all storage backends */ disconnect(): Promise; /** * Perform health check on all backends * * @returns Health check results for each backend */ healthCheck(): Promise; /** * Create cache backend based on configuration */ private createCacheBackend; /** * Create database backend based on configuration */ private createDatabaseBackend; } /** * Session Persistence Types * * Defines the types and interfaces for serializing and deserializing * conversation sessions and their complete state for persistence. * * @module session/persistence-types */ /** * Serialized form of a ConversationSession for storage */ interface SerializedSession { /** Unique session identifier */ id: string; /** Session metadata */ metadata: { /** When the session was created */ createdAt: number; /** Last activity timestamp */ lastActivity: number; /** Session-specific memory metadata if any */ sessionMemoryMetadata?: Record; /** History settings */ historyEnabled: boolean; historyBackend: 'database' | 'memory'; }; /** Complete conversation history */ conversationHistory: InternalMessage[]; /** Session configuration options */ options?: { hadMetadataSchema?: boolean; }; /** Version for schema evolution */ version: string; /** When this serialization was created */ serializedAt: number; } /** * Session persistence statistics */ interface SessionPersistenceStats { /** Total number of sessions processed */ totalSessions: number; /** Number of sessions successfully saved */ savedSessions: number; /** Number of sessions that failed to save */ failedSessions: number; /** Total time taken for persistence operation (ms) */ persistenceTime: number; /** Session IDs that failed to persist (for debugging) */ failedSessionIds: string[]; /** Any error messages encountered */ errors: string[]; } /** * Session restoration statistics */ interface SessionRestorationStats { /** Total number of sessions found in storage */ totalSessions: number; /** Number of sessions successfully restored */ restoredSessions: number; /** Number of sessions that failed to restore */ failedSessions: number; /** Total time taken for restoration operation (ms) */ restorationTime: number; /** Session IDs that failed to restore (for debugging) */ failedSessionIds: string[]; /** Any error messages encountered */ errors: string[]; } /** * Configuration for session persistence behavior */ interface SessionPersistenceConfig { /** Storage key prefix for session data */ storageKeyPrefix?: string; /** Maximum number of sessions to persist */ maxSessionsToSave?: number; /** Maximum age of sessions to restore (ms) */ maxSessionAge?: number; /** Whether to compress session data */ compress?: boolean; /** Timeout for save operations (ms) */ saveTimeout?: number; /** Timeout for load operations (ms) */ loadTimeout?: number; /** Whether to validate restored sessions */ validateOnRestore?: boolean; } declare class ConversationSession { private services; readonly id: string; private contextManager; private _llmService?; private reasoningDetector?; private searchContextManager?; private _historyProvider?; private _storageManager?; private historyEnabled; private historyBackend; private sessionMemoryMetadata?; private mergeMetadata?; private metadataSchema?; private beforeMemoryExtraction?; private _servicesInitialized; private _llmServiceInitialized; private _storageInitialized; /** * @param services - Required dependencies for the session, including unifiedToolManager * @param id - Session identifier * @param options - Optional advanced metadata options */ constructor(services: { stateManager: MemAgentStateManager; promptManager: EnhancedPromptManager; contextManager: ContextManager; mcpManager: MCPManager; unifiedToolManager: UnifiedToolManager; embeddingManager?: any; eventManager?: any; }, id: string, options?: { sessionMemoryMetadata?: Record; mergeMetadata?: (sessionMeta: Record, runMeta: Record) => Record; metadataSchema?: ZodSchema; beforeMemoryExtraction?: (meta: Record, context: Record) => void; historyEnabled?: boolean; historyBackend?: 'database' | 'memory'; sharedStorageManager?: StorageManager; }); /** * Update session-level memory metadata after construction. */ updateSessionMetadata(newMeta: Record): void; /** * Initialize all services for the session, including history provider. */ init(): Promise; /** * Initializes the services for the session, including the history provider. */ private initializeServices; /** * Get the appropriate formatter for the provider */ private getFormatterForProvider; /** * Lazy initialization of LLM service */ private getLLMServiceLazy; /** * Lazy initialization of storage manager and history provider with PostgreSQL/SQLite support */ private getStorageManagerLazy; /** * Lazy initialization of history provider */ private getHistoryProviderLazy; /** * Restore history when history provider is lazy-loaded */ private restoreHistoryLazy; /** * Extract session-level metadata, merging defaults, session, and per-run metadata. * Uses custom merge and validation if provided. * Now supports environment and extensible context. */ private getSessionMetadata; /** * Optionally override to provide additional session context for metadata. */ protected getSessionContext(): Record; /** * Run a conversation session with input, optional image data, streaming, and custom options. * @param input - User input string * @param imageDataInput - Optional image data * @param stream - Optional stream flag * @param options - Optional parameters for memory extraction: * - memoryMetadata: Custom metadata to attach to memory extraction (merged with session defaults) * - contextOverrides: Overrides for context fields passed to memory extraction * - historyTracking: Enable/disable history tracking * @returns An object containing the response and a promise for background operations */ run(input: string, imageDataInput?: { image: string; mimeType: string; }, stream?: boolean, options?: { memoryMetadata?: Record; contextOverrides?: Record; historyTracking?: boolean; }): Promise<{ response: string; backgroundOperations: Promise; }>; /** * Programmatically enforce memory extraction after each user interaction (runs in background) * This ensures the extract_and_operate_memory tool is always called, regardless of AI decisions * NOTE: This method runs asynchronously in the background to avoid delaying the user response */ private enforceMemoryExtraction; /** * Initialize reasoning services (content detector and search context manager) */ private initializeReasoningServices; /** * Programmatically enforce reflection memory processing after each interaction (runs in background) * This automatically extracts, evaluates, and stores reasoning patterns in the background * NOTE: This method is called from enforceMemoryExtraction which already runs asynchronously * @param userInput - The user input string * @param aiResponse - The AI response string * @param allTools - Pre-loaded tools to avoid redundant loading */ private enforceReflectionMemoryProcessing; /** * Extract comprehensive interaction data including tool calls and results * This captures the complete technical workflow, not just user input and final response */ private extractComprehensiveInteractionData; /** * Summarize tool arguments for memory storage */ private summarizeToolArguments; /** * Summarize tool results for memory storage */ private summarizeToolResult; /** * Format tool result summary based on tool type */ private formatToolResultSummary; /** * Disconnects the history provider if it exists (for session teardown). */ disconnect(): Promise; getContextManager(): ContextManager; /** * Get LLM service with lazy initialization */ getLLMService(): Promise; getUnifiedToolManager(): UnifiedToolManager; /** * Get the storageManager with lazy initialization */ getStorageManager(): Promise; /** * Get the history provider with lazy initialization */ getHistoryProvider(): Promise; /** * Force refresh conversation history from the database */ refreshConversationHistory(): Promise; /** * Get the current conversation history for debugging */ getConversationHistory(): Promise; /** * Get the current conversation history from context manager */ getContextHistory(): any[]; /** * Serialize the current session state for persistence * @returns SerializedSession containing all necessary data to restore this session */ serialize(): Promise; /** * Deserialize and restore a session from serialized data * @param data - Serialized session data * @param services - Service dependencies required for session creation * @returns A new ConversationSession instance restored from the data */ static deserialize(data: SerializedSession, services: { stateManager: MemAgentStateManager; promptManager: EnhancedPromptManager; mcpManager: MCPManager; unifiedToolManager: UnifiedToolManager; embeddingManager?: any; }): Promise; } interface SessionManagerConfig { maxSessions?: number; sessionTTL?: number; persistence?: SessionPersistenceConfig; } declare class SessionManager { private services; private sessions; private readonly maxSessions; private readonly sessionTTL; private initialized; private cleanupInterval?; private initializationPromise; private readonly pendingCreations; private readonly sessionMetadataCache; private readonly messageCountCache; private readonly requestDeduplicator; private readonly CACHE_TTL; private readonly BATCH_SIZE; private performanceMetrics; private readonly persistenceConfig; private storageManager?; constructor(services: { stateManager: MemAgentStateManager; promptManager: EnhancedPromptManager; contextManager: any; mcpManager: MCPManager; unifiedToolManager: UnifiedToolManager; eventManager: EventManager; embeddingManager?: any; }, config?: SessionManagerConfig); init(): Promise; private ensureInitialized; createSession(sessionId?: string): Promise; private createSessionInternal; private updateSessionActivity; getSession(sessionId: string): Promise; removeSession(sessionId: string): Promise; getAllSessions(): Promise; /** * Optimized session listing with parallel processing and caching */ getActiveSessionIds(): Promise; /** * Internal method to fetch active session IDs with optimized queries */ private fetchActiveSessionIds; getSessionCount(): Promise; /** * Get detailed session statistics for monitoring */ getSessionStats(): Promise<{ activeSessions: number; storageConnected: boolean; storageType: string; persistenceEnabled: boolean; performanceMetrics: { cacheHitRate: number; parallelLoadRatio: number; averageLoadTime: number; cacheSize: number; }; }>; private isSessionExpired; private evictOldestSession; private cleanupExpiredSessions; private startCleanupInterval; /** * Save all active sessions to persistent storage * @returns Statistics about the save operation */ saveAllSessions(): Promise; /** * Load all sessions from persistent storage * @returns Statistics about the load operation */ loadAllSessions(): Promise; /** * Initialize storage manager for session persistence */ private initializePersistenceStorage; /** * Initialize SQLite storage as fallback */ private initializeSqliteStorage; /** * Save a single session to storage */ private saveSession; /** * Load a single session from storage */ private loadSession; /** * Get all session keys from storage with optimized batch processing */ private getAllSessionKeys; /** * Get all message keys from storage for session discovery */ private getAllMessageKeys; /** * Get the storage key for a session */ private getSessionStorageKey; /** * Extract session ID from storage key */ private extractSessionIdFromKey; /** * Validate a serialized session object */ private validateSerializedSession; shutdown(): Promise; /** * Get the storageManager for a given session (if available) */ getStorageManagerForSession(sessionId: string): any; /** * Performance optimization: Cache management methods */ private getCachedResult; private setCacheResult; private cleanupExpiredCache; private updateAverageLoadTime; /** * Clear session from all caches to prevent phantom sessions */ private clearSessionFromAllCaches; /** * Filter out invalid sessions (empty sessions with 0 messages) */ private filterValidSessions; /** * Clean up phantom sessions that have no messages */ private cleanupPhantomSession; /** * Get batch session metadata with parallel processing and caching */ getBatchSessionMetadata(sessionIds: string[]): Promise>; /** * Get session message count with caching */ private getSessionMessageCount; /** * Get session metadata from storage */ private getSessionMetadataFromStorage; } type AgentServices = { [key: string]: any; mcpManager: MCPManager; promptManager: EnhancedPromptManager; stateManager: MemAgentStateManager; sessionManager: SessionManager; internalToolManager: InternalToolManager; unifiedToolManager: UnifiedToolManager; embeddingManager?: EmbeddingManager; vectorStoreManager: VectorStoreManager | DualCollectionVectorManager; eventManager: EventManager; llmService?: ILLMService; contextManager?: any; knowledgeGraphManager?: KnowledgeGraphManager; }; declare function createAgentServices(agentConfig: AgentConfig, appMode?: 'cli' | 'mcp' | 'api'): Promise; declare class MemAgent { readonly mcpManager: MCPManager; readonly promptManager: EnhancedPromptManager; readonly stateManager: MemAgentStateManager; readonly sessionManager: SessionManager; readonly internalToolManager: any; readonly unifiedToolManager: any; readonly services: AgentServices; private defaultSession; private currentDefaultSessionId; private currentActiveSessionId; private isStarted; private isStopped; private config; private appMode; constructor(config: AgentConfig, appMode?: 'cli' | 'mcp' | 'api'); /** * Generate a unique session ID for API/MCP modes * CLI mode uses the default session for persistence */ private generateUniqueSessionId; /** * Start the MemAgent */ start(): Promise; /** * Stop the MemAgent */ stop(): Promise; /** * Get the status of the MemAgent */ getIsStarted(): boolean; /** * Get the status of the MemAgent */ getIsStopped(): boolean; private ensureStarted; /** * Run the MemAgent */ run(userInput: string, imageDataInput?: { image: string; mimeType: string; }, sessionId?: string, stream?: boolean, options?: { memoryMetadata?: Record; sessionOptions?: Record; }): Promise<{ response: string | null; backgroundOperations: Promise; }>; createSession(sessionId?: string): Promise; getSession(sessionId: string): Promise; /** * Get the current active session ID */ getCurrentSessionId(): string; /** * Load conversation history for a specific session */ loadSessionHistory(sessionId: string): Promise; /** * Load (switch to) a specific session */ loadSession(sessionId: string): Promise; /** * Get all active session IDs */ listSessions(): Promise; /** * Remove a session */ removeSession(sessionId: string): Promise; /** * Get session metadata including message count */ getSessionMetadata(sessionId: string): Promise<{ id: string; createdAt?: number; lastActivity?: number; messageCount?: number; } | null>; /** * Get conversation history for the current session */ getCurrentSessionHistory(): Promise; /** * Get conversation history for a specific session */ getSessionHistory(sessionId: string): Promise; getCurrentLLMConfig(): LLMConfig; connectMcpServer(name: string, config: McpServerConfig): Promise; removeMcpServer(name: string): Promise; executeMcpTool(toolName: string, args: any): Promise; getAllMcpTools(): Promise; getMcpClients(): Map; getMcpFailedConnections(): Record; getAllMcpServers(): Array<{ id: string; name: string; status: string; error?: string; }>; getEffectiveConfig(sessionId?: string): Readonly; getCurrentActiveSessionId(): string; /** * Manually save all sessions to persistent storage */ saveAllSessions(): Promise<{ saved: number; failed: number; total: number; }>; /** * Manually load all sessions from persistent storage */ loadAllSessions(): Promise<{ restored: number; failed: number; total: number; }>; } /** * Content-Based Reasoning Detection Service * * Analyzes user input to determine if it contains reasoning content that should * trigger reflection memory tools. This replaces the model-based activation mechanism. */ interface ReasoningDetectionResult { containsReasoning: boolean; confidence: number; detectedPatterns: string[]; explanation?: string; } interface ReasoningDetectionOptions { confidenceThreshold?: number; maxPatterns?: number; enableDetailedAnalysis?: boolean; } /** * Reasoning content detector that analyzes user input to determine * if it contains reasoning patterns that should trigger reflection tools. */ declare class ReasoningContentDetector { private llmService?; private promptManager; private mcpManager; private unifiedToolManager; private options; private evalLlmConfig; constructor(promptManager: EnhancedPromptManager, mcpManager: MCPManager, unifiedToolManager: UnifiedToolManager, evalLlmConfig: LLMConfig, options?: ReasoningDetectionOptions); /** * Initialize the LLM service for reasoning analysis */ private initializeLLMService; /** * Detect if user input contains reasoning content */ detectReasoningContent(userInput: string, context?: { sessionId?: string; recentMessages?: string[]; taskType?: string; }): Promise; /** * Detect reasoning content using LLM analysis */ private detectReasoningByLLM; /** * Update detection options */ updateOptions(newOptions: Partial): void; /** * Get current detection options */ getOptions(): Required; } /** * Search Context Manager * * Handles multiple search tool calls and provides well-sorted context * to feed into the agent. This ensures efficient use of search results * from cipher_search_graph, cipher_memory_search, and cipher_search_reasoning_patterns. */ interface SearchResult { source: 'graph' | 'memory' | 'reasoning_patterns'; content: string; relevance: number; metadata?: Record; timestamp?: string; } interface SortedContext { primaryResults: SearchResult[]; secondaryResults: SearchResult[]; summary: string; totalResults: number; sourcesUsed: string[]; } interface SearchContextOptions { maxPrimaryResults?: number; maxSecondaryResults?: number; relevanceThreshold?: number; enableDeduplication?: boolean; enableSummarization?: boolean; sortByRelevance?: boolean; } /** * Manages multiple search tool results and provides well-sorted context */ declare class SearchContextManager { private options; private recentSearches; constructor(options?: SearchContextOptions); /** * Process multiple search tool results and return well-sorted context */ processSearchResults(searchResults: { graph?: any[]; memory?: any[]; reasoning_patterns?: any[]; }, query?: string): Promise; /** * Normalize search results from different sources */ private normalizeSearchResults; /** * Extract content from search result based on source */ private extractContent; /** * Extract relevance score from search result */ private extractRelevance; /** * Extract metadata from search result */ private extractMetadata; /** * Extract timestamp from search result */ private extractTimestamp; /** * Deduplicate search results based on content similarity */ private deduplicateResults; /** * Sort results by relevance score */ private sortByRelevance; /** * Filter results by relevance threshold */ private filterByRelevance; /** * Split results into primary and secondary based on relevance and limits */ private splitResults; /** * Generate a summary of the primary search results */ private generateSummary; /** * Generate a basic summary without LLM processing */ private generateBasicSummary; /** * Count results by source */ private countResultsBySource; /** * Get list of sources used in results */ private getSourcesUsed; /** * Cache search results for future reference */ private cacheSearchResults; /** * Get cached search results for a query */ getCachedResults(query: string): SearchResult[] | null; /** * Update search context options */ updateOptions(newOptions: Partial): void; /** * Get current search context options */ getOptions(): Required; /** * Clear search cache */ clearCache(): void; } /** * The default path to the agent config file */ declare const DEFAULT_CONFIG_PATH = "memAgent/cipher.yml"; /** * Resolve the configuration file path. * - If it's absolute, return as-is. * - If it's the default config, resolve relative to the package installation root. * - Otherwise resolve relative to the current working directory. * * @param configPath - The config path to resolve * @returns The resolved absolute path to the config file */ declare function resolveConfigPath(configPath: string): string; declare const envSchema: z.ZodObject<{ NODE_ENV: z.ZodDefault>; CIPHER_LOG_LEVEL: z.ZodDefault>; REDACT_SECRETS: z.ZodDefault; OPENAI_API_KEY: z.ZodOptional; ANTHROPIC_API_KEY: z.ZodOptional; OPENROUTER_API_KEY: z.ZodOptional; QWEN_API_KEY: z.ZodOptional; OPENAI_BASE_URL: z.ZodOptional; OLLAMA_BASE_URL: z.ZodOptional; LMSTUDIO_BASE_URL: z.ZodOptional; OPENAI_ORG_ID: z.ZodOptional; EMBEDDING_PROVIDER: z.ZodOptional; EMBEDDING_MODEL: z.ZodOptional; EMBEDDING_TIMEOUT: z.ZodOptional; EMBEDDING_MAX_RETRIES: z.ZodOptional; EMBEDDING_DIMENSIONS: z.ZodOptional; DISABLE_EMBEDDINGS: z.ZodDefault; EMBEDDING_DISABLED: z.ZodDefault; GEMINI_API_KEY: z.ZodOptional; GEMINI_BASE_URL: z.ZodOptional; STORAGE_CACHE_TYPE: z.ZodDefault>; STORAGE_CACHE_HOST: z.ZodOptional; STORAGE_CACHE_PORT: z.ZodOptional; STORAGE_CACHE_USERNAME: z.ZodOptional; STORAGE_CACHE_PASSWORD: z.ZodOptional; STORAGE_CACHE_DATABASE: z.ZodOptional; STORAGE_DATABASE_TYPE: z.ZodDefault>; STORAGE_DATABASE_PATH: z.ZodOptional; STORAGE_DATABASE_NAME: z.ZodOptional; CIPHER_PG_URL: z.ZodOptional; STORAGE_DATABASE_HOST: z.ZodOptional; STORAGE_DATABASE_PORT: z.ZodOptional; STORAGE_DATABASE_USER: z.ZodOptional; STORAGE_DATABASE_PASSWORD: z.ZodOptional; STORAGE_DATABASE_SSL: z.ZodDefault; VECTOR_STORE_TYPE: z.ZodDefault>; VECTOR_STORE_HOST: z.ZodOptional; VECTOR_STORE_PORT: z.ZodOptional; VECTOR_STORE_URL: z.ZodOptional; VECTOR_STORE_API_KEY: z.ZodOptional; VECTOR_STORE_USERNAME: z.ZodOptional; VECTOR_STORE_PASSWORD: z.ZodOptional; VECTOR_STORE_COLLECTION: z.ZodDefault; VECTOR_STORE_DIMENSION: z.ZodDefault; VECTOR_STORE_DISTANCE: z.ZodDefault>; VECTOR_STORE_ON_DISK: z.ZodDefault; VECTOR_STORE_MAX_VECTORS: z.ZodDefault; PINECONE_PROVIDER: z.ZodDefault; PINECONE_REGION: z.ZodDefault; PGVECTOR_INDEXTYPE: z.ZodDefault>; PGVECTOR_INDEXMETRIC: z.ZodDefault>; PINECONE_NAMESPACE: z.ZodDefault; FAISS_BASE_STORAGE_PATH: z.ZodOptional; KNOWLEDGE_GRAPH_ENABLED: z.ZodDefault; KNOWLEDGE_GRAPH_TYPE: z.ZodDefault>; KNOWLEDGE_GRAPH_HOST: z.ZodOptional; KNOWLEDGE_GRAPH_PORT: z.ZodOptional; KNOWLEDGE_GRAPH_URI: z.ZodOptional; KNOWLEDGE_GRAPH_USERNAME: z.ZodOptional; KNOWLEDGE_GRAPH_PASSWORD: z.ZodOptional; KNOWLEDGE_GRAPH_DATABASE: z.ZodDefault; SEARCH_MEMORY_TYPE: z.ZodDefault>; REFLECTION_VECTOR_STORE_COLLECTION: z.ZodDefault; DISABLE_REFLECTION_MEMORY: z.ZodDefault; EVENT_PERSISTENCE_ENABLED: z.ZodDefault; EVENT_PERSISTENCE_PATH: z.ZodOptional; ENABLE_LAZY_LOADING: z.ZodOptional; LAZY_LOADING_ENABLED: z.ZodOptional; SKIP_HEAVY_SERVICES: z.ZodOptional; LAZY_EMBEDDING: z.ZodOptional; LAZY_VECTOR_STORE: z.ZodOptional; LAZY_MEMORY_OPERATIONS: z.ZodOptional; DISABLE_BACKGROUND_PRELOAD: z.ZodOptional; LAZY_INIT_TIMEOUT: z.ZodOptional; BACKGROUND_PRELOAD_DELAY: z.ZodOptional; USE_WORKSPACE_MEMORY: z.ZodDefault; WORKSPACE_SEARCH_THRESHOLD: z.ZodDefault; DISABLE_DEFAULT_MEMORY: z.ZodDefault; WORKSPACE_VECTOR_STORE_TYPE: z.ZodOptional>; WORKSPACE_VECTOR_STORE_HOST: z.ZodOptional; WORKSPACE_VECTOR_STORE_PORT: z.ZodOptional; WORKSPACE_VECTOR_STORE_URL: z.ZodOptional; WORKSPACE_VECTOR_STORE_API_KEY: z.ZodOptional; WORKSPACE_VECTOR_STORE_USERNAME: z.ZodOptional; WORKSPACE_VECTOR_STORE_PASSWORD: z.ZodOptional; WORKSPACE_VECTOR_STORE_COLLECTION: z.ZodDefault; WORKSPACE_VECTOR_STORE_DIMENSION: z.ZodOptional; WORKSPACE_VECTOR_STORE_DISTANCE: z.ZodOptional>; WORKSPACE_VECTOR_STORE_ON_DISK: z.ZodOptional; WORKSPACE_VECTOR_STORE_MAX_VECTORS: z.ZodOptional; WORKSPACE_REDIS_DATABASE: z.ZodOptional; WORKSPACE_PINECONE_PROVIDER: z.ZodOptional; WORKSPACE_PINECONE_REGION: z.ZodOptional; WORKSPACE_PINECONE_NAMESPACE: z.ZodOptional; ENABLE_QUERY_REFINEMENT: z.ZodDefault; CIPHER_USER_ID: z.ZodOptional; CIPHER_PROJECT_NAME: z.ZodOptional; CIPHER_WORKSPACE_MODE: z.ZodDefault>; USE_ASK_CIPHER: z.ZodDefault; }, "strip", z.ZodTypeAny, { NODE_ENV?: "development" | "production" | "test"; CIPHER_LOG_LEVEL?: "error" | "warn" | "info" | "debug" | "silly"; REDACT_SECRETS?: boolean; OPENAI_API_KEY?: string; ANTHROPIC_API_KEY?: string; OPENROUTER_API_KEY?: string; QWEN_API_KEY?: string; OPENAI_BASE_URL?: string; OLLAMA_BASE_URL?: string; LMSTUDIO_BASE_URL?: string; OPENAI_ORG_ID?: string; EMBEDDING_PROVIDER?: string; EMBEDDING_MODEL?: string; EMBEDDING_TIMEOUT?: number; EMBEDDING_MAX_RETRIES?: number; EMBEDDING_DIMENSIONS?: number; DISABLE_EMBEDDINGS?: boolean; EMBEDDING_DISABLED?: boolean; GEMINI_API_KEY?: string; GEMINI_BASE_URL?: string; STORAGE_CACHE_TYPE?: "in-memory" | "redis"; STORAGE_CACHE_HOST?: string; STORAGE_CACHE_PORT?: number; STORAGE_CACHE_USERNAME?: string; STORAGE_CACHE_PASSWORD?: string; STORAGE_CACHE_DATABASE?: number; STORAGE_DATABASE_TYPE?: "in-memory" | "sqlite" | "postgres"; STORAGE_DATABASE_PATH?: string; STORAGE_DATABASE_NAME?: string; CIPHER_PG_URL?: string; STORAGE_DATABASE_HOST?: string; STORAGE_DATABASE_PORT?: number; STORAGE_DATABASE_USER?: string; STORAGE_DATABASE_PASSWORD?: string; STORAGE_DATABASE_SSL?: boolean; VECTOR_STORE_TYPE?: "in-memory" | "qdrant" | "milvus" | "chroma" | "pinecone" | "faiss"; VECTOR_STORE_HOST?: string; VECTOR_STORE_PORT?: number; VECTOR_STORE_URL?: string; VECTOR_STORE_API_KEY?: string; VECTOR_STORE_USERNAME?: string; VECTOR_STORE_PASSWORD?: string; VECTOR_STORE_COLLECTION?: string; VECTOR_STORE_DIMENSION?: number; VECTOR_STORE_DISTANCE?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; VECTOR_STORE_ON_DISK?: boolean; VECTOR_STORE_MAX_VECTORS?: number; PINECONE_PROVIDER?: string; PINECONE_REGION?: string; PGVECTOR_INDEXTYPE?: "hnsw" | "ivfflat"; PGVECTOR_INDEXMETRIC?: "vector_l2_ops" | "vector_ip_ops"; PINECONE_NAMESPACE?: string; FAISS_BASE_STORAGE_PATH?: string; KNOWLEDGE_GRAPH_ENABLED?: boolean; KNOWLEDGE_GRAPH_TYPE?: "in-memory" | "neo4j"; KNOWLEDGE_GRAPH_HOST?: string; KNOWLEDGE_GRAPH_PORT?: number; KNOWLEDGE_GRAPH_URI?: string; KNOWLEDGE_GRAPH_USERNAME?: string; KNOWLEDGE_GRAPH_PASSWORD?: string; KNOWLEDGE_GRAPH_DATABASE?: string; SEARCH_MEMORY_TYPE?: "knowledge" | "reflection" | "both"; REFLECTION_VECTOR_STORE_COLLECTION?: string; DISABLE_REFLECTION_MEMORY?: boolean; EVENT_PERSISTENCE_ENABLED?: boolean; EVENT_PERSISTENCE_PATH?: string; ENABLE_LAZY_LOADING?: string; LAZY_LOADING_ENABLED?: string; SKIP_HEAVY_SERVICES?: string; LAZY_EMBEDDING?: string; LAZY_VECTOR_STORE?: string; LAZY_MEMORY_OPERATIONS?: string; DISABLE_BACKGROUND_PRELOAD?: string; LAZY_INIT_TIMEOUT?: string; BACKGROUND_PRELOAD_DELAY?: string; USE_WORKSPACE_MEMORY?: boolean; WORKSPACE_SEARCH_THRESHOLD?: number; DISABLE_DEFAULT_MEMORY?: boolean; WORKSPACE_VECTOR_STORE_TYPE?: "in-memory" | "qdrant" | "milvus" | "chroma" | "pinecone" | "pgvector"; WORKSPACE_VECTOR_STORE_HOST?: string; WORKSPACE_VECTOR_STORE_PORT?: number; WORKSPACE_VECTOR_STORE_URL?: string; WORKSPACE_VECTOR_STORE_API_KEY?: string; WORKSPACE_VECTOR_STORE_USERNAME?: string; WORKSPACE_VECTOR_STORE_PASSWORD?: string; WORKSPACE_VECTOR_STORE_COLLECTION?: string; WORKSPACE_VECTOR_STORE_DIMENSION?: number; WORKSPACE_VECTOR_STORE_DISTANCE?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; WORKSPACE_VECTOR_STORE_ON_DISK?: boolean; WORKSPACE_VECTOR_STORE_MAX_VECTORS?: number; WORKSPACE_REDIS_DATABASE?: number; WORKSPACE_PINECONE_PROVIDER?: string; WORKSPACE_PINECONE_REGION?: string; WORKSPACE_PINECONE_NAMESPACE?: string; ENABLE_QUERY_REFINEMENT?: boolean; CIPHER_USER_ID?: string; CIPHER_PROJECT_NAME?: string; CIPHER_WORKSPACE_MODE?: "shared" | "isolated"; USE_ASK_CIPHER?: boolean; }, { NODE_ENV?: "development" | "production" | "test"; CIPHER_LOG_LEVEL?: "error" | "warn" | "info" | "debug" | "silly"; REDACT_SECRETS?: boolean; OPENAI_API_KEY?: string; ANTHROPIC_API_KEY?: string; OPENROUTER_API_KEY?: string; QWEN_API_KEY?: string; OPENAI_BASE_URL?: string; OLLAMA_BASE_URL?: string; LMSTUDIO_BASE_URL?: string; OPENAI_ORG_ID?: string; EMBEDDING_PROVIDER?: string; EMBEDDING_MODEL?: string; EMBEDDING_TIMEOUT?: number; EMBEDDING_MAX_RETRIES?: number; EMBEDDING_DIMENSIONS?: number; DISABLE_EMBEDDINGS?: boolean; EMBEDDING_DISABLED?: boolean; GEMINI_API_KEY?: string; GEMINI_BASE_URL?: string; STORAGE_CACHE_TYPE?: "in-memory" | "redis"; STORAGE_CACHE_HOST?: string; STORAGE_CACHE_PORT?: number; STORAGE_CACHE_USERNAME?: string; STORAGE_CACHE_PASSWORD?: string; STORAGE_CACHE_DATABASE?: number; STORAGE_DATABASE_TYPE?: "in-memory" | "sqlite" | "postgres"; STORAGE_DATABASE_PATH?: string; STORAGE_DATABASE_NAME?: string; CIPHER_PG_URL?: string; STORAGE_DATABASE_HOST?: string; STORAGE_DATABASE_PORT?: number; STORAGE_DATABASE_USER?: string; STORAGE_DATABASE_PASSWORD?: string; STORAGE_DATABASE_SSL?: boolean; VECTOR_STORE_TYPE?: "in-memory" | "qdrant" | "milvus" | "chroma" | "pinecone" | "faiss"; VECTOR_STORE_HOST?: string; VECTOR_STORE_PORT?: number; VECTOR_STORE_URL?: string; VECTOR_STORE_API_KEY?: string; VECTOR_STORE_USERNAME?: string; VECTOR_STORE_PASSWORD?: string; VECTOR_STORE_COLLECTION?: string; VECTOR_STORE_DIMENSION?: number; VECTOR_STORE_DISTANCE?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; VECTOR_STORE_ON_DISK?: boolean; VECTOR_STORE_MAX_VECTORS?: number; PINECONE_PROVIDER?: string; PINECONE_REGION?: string; PGVECTOR_INDEXTYPE?: "hnsw" | "ivfflat"; PGVECTOR_INDEXMETRIC?: "vector_l2_ops" | "vector_ip_ops"; PINECONE_NAMESPACE?: string; FAISS_BASE_STORAGE_PATH?: string; KNOWLEDGE_GRAPH_ENABLED?: boolean; KNOWLEDGE_GRAPH_TYPE?: "in-memory" | "neo4j"; KNOWLEDGE_GRAPH_HOST?: string; KNOWLEDGE_GRAPH_PORT?: number; KNOWLEDGE_GRAPH_URI?: string; KNOWLEDGE_GRAPH_USERNAME?: string; KNOWLEDGE_GRAPH_PASSWORD?: string; KNOWLEDGE_GRAPH_DATABASE?: string; SEARCH_MEMORY_TYPE?: "knowledge" | "reflection" | "both"; REFLECTION_VECTOR_STORE_COLLECTION?: string; DISABLE_REFLECTION_MEMORY?: boolean; EVENT_PERSISTENCE_ENABLED?: boolean; EVENT_PERSISTENCE_PATH?: string; ENABLE_LAZY_LOADING?: string; LAZY_LOADING_ENABLED?: string; SKIP_HEAVY_SERVICES?: string; LAZY_EMBEDDING?: string; LAZY_VECTOR_STORE?: string; LAZY_MEMORY_OPERATIONS?: string; DISABLE_BACKGROUND_PRELOAD?: string; LAZY_INIT_TIMEOUT?: string; BACKGROUND_PRELOAD_DELAY?: string; USE_WORKSPACE_MEMORY?: boolean; WORKSPACE_SEARCH_THRESHOLD?: number; DISABLE_DEFAULT_MEMORY?: boolean; WORKSPACE_VECTOR_STORE_TYPE?: "in-memory" | "qdrant" | "milvus" | "chroma" | "pinecone" | "pgvector"; WORKSPACE_VECTOR_STORE_HOST?: string; WORKSPACE_VECTOR_STORE_PORT?: number; WORKSPACE_VECTOR_STORE_URL?: string; WORKSPACE_VECTOR_STORE_API_KEY?: string; WORKSPACE_VECTOR_STORE_USERNAME?: string; WORKSPACE_VECTOR_STORE_PASSWORD?: string; WORKSPACE_VECTOR_STORE_COLLECTION?: string; WORKSPACE_VECTOR_STORE_DIMENSION?: number; WORKSPACE_VECTOR_STORE_DISTANCE?: "Cosine" | "Euclidean" | "Dot" | "Manhattan"; WORKSPACE_VECTOR_STORE_ON_DISK?: boolean; WORKSPACE_VECTOR_STORE_MAX_VECTORS?: number; WORKSPACE_REDIS_DATABASE?: number; WORKSPACE_PINECONE_PROVIDER?: string; WORKSPACE_PINECONE_REGION?: string; WORKSPACE_PINECONE_NAMESPACE?: string; ENABLE_QUERY_REFINEMENT?: boolean; CIPHER_USER_ID?: string; CIPHER_PROJECT_NAME?: string; CIPHER_WORKSPACE_MODE?: "shared" | "isolated"; USE_ASK_CIPHER?: boolean; }>; type EnvSchema = z.infer; declare const env: EnvSchema; declare const validateEnv: () => boolean; /** * Storage Module Constants * * Central location for all storage-related constants including * error messages, log prefixes, timeouts, and configuration defaults. * * @module storage/constants */ /** * Log prefixes for consistent logging across the storage module */ declare const LOG_PREFIXES$1: { readonly MANAGER: "[StorageManager]"; readonly CACHE: "[StorageManager:Cache]"; readonly DATABASE: "[StorageManager:Database]"; readonly HEALTH: "[StorageManager:Health]"; readonly FACTORY: "[StorageFactory]"; readonly BACKEND: "[StorageBackend]"; }; /** * Error messages for the storage module */ declare const ERROR_MESSAGES$1: { readonly CACHE_CONNECTION_FAILED: "Failed to connect to cache backend"; readonly DATABASE_CONNECTION_FAILED: "Failed to connect to database backend"; readonly ALREADY_CONNECTED: "Storage manager is already connected"; readonly NOT_CONNECTED: "Storage manager is not connected"; readonly BACKEND_NOT_FOUND: "Storage backend not found"; readonly INVALID_BACKEND_TYPE: "Invalid backend type specified"; readonly MODULE_LOAD_FAILED: "Failed to load backend module"; readonly HEALTH_CHECK_FAILED: "Health check failed"; readonly OPERATION_TIMEOUT: "Storage operation timed out"; readonly SERIALIZATION_ERROR: "Failed to serialize/deserialize data"; readonly INVALID_CONFIG: "Invalid storage configuration"; readonly MISSING_REQUIRED_CONFIG: "Missing required configuration"; }; /** * Storage operation timeouts (in milliseconds) */ declare const TIMEOUTS$1: { readonly CONNECTION: 10000; readonly HEALTH_CHECK: 5000; readonly OPERATION: 30000; readonly SHUTDOWN: 5000; }; /** * Health check constants */ declare const HEALTH_CHECK: { readonly KEY: "storage_manager_health_check"; readonly VALUE: "ok"; readonly TTL_SECONDS: 10; }; /** * Backend type identifiers */ declare const BACKEND_TYPES$1: { readonly REDIS: "redis"; readonly MEMCACHED: "memcached"; readonly IN_MEMORY: "in-memory"; readonly SQLITE: "sqlite"; readonly POSTGRES: "postgres"; readonly MYSQL: "mysql"; }; /** * Default configuration values */ declare const DEFAULTS$1: { readonly MAX_RETRIES: 3; readonly RETRY_DELAY: 1000; readonly CACHE_TTL: 3600; readonly MAX_CONNECTIONS: 10; readonly IDLE_TIMEOUT: 30000; }; /** * In-Memory Backend Implementation * * Provides a memory-based storage backend that implements both CacheBackend * and DatabaseBackend interfaces. Useful for development, testing, and as * a fallback when external backends are unavailable. * * Features: * - TTL support for cache operations * - List/collection operations for database functionality * - Automatic cleanup of expired entries * - No external dependencies * * @module storage/backend/in-memory */ /** * In-Memory Storage Backend * * Implements both CacheBackend and DatabaseBackend interfaces using * JavaScript Maps for storage. All data is lost when the process exits. * * @example * ```typescript * // As cache backend * const cache = new InMemoryBackend(); * await cache.connect(); * await cache.set('key', value, 300); // 5 minute TTL * * // As database backend * const db = new InMemoryBackend(); * await db.connect(); * await db.append('log', { message: 'Hello' }); * ``` */ declare class InMemoryBackend$1 implements CacheBackend, DatabaseBackend { private store; private lists; private connected; private cleanupInterval; private readonly cleanupIntervalMs; private readonly logger; private stats; constructor(); /** * Connect to the in-memory backend * * For in-memory backend, this just sets the connected flag and * starts the cleanup interval for expired entries. */ connect(): Promise; /** * Disconnect from the in-memory backend * * Clears all data and stops the cleanup interval. */ disconnect(): Promise; /** * Check if backend is connected */ isConnected(): boolean; /** * Get backend type identifier */ getBackendType(): string; /** * Get a value by key * * Checks expiration and removes expired entries. */ get(key: string): Promise; /** * Set a value with optional TTL (for CacheBackend) */ set(key: string, value: T, ttlSeconds?: number): Promise; /** * Delete a value by key */ delete(key: string): Promise; /** * List all keys matching a prefix */ list(prefix: string): Promise; /** * Append an item to a list */ append(key: string, item: T): Promise; /** * Get a range of items from a list */ getRange(key: string, start: number, count: number): Promise; /** * Check if backend is connected * @throws {StorageError} If not connected */ private checkConnection; /** * Clone a value to prevent reference issues * * Uses JSON serialization for deep cloning. * This also ensures consistency with network-based backends * that serialize data. */ private cloneValue; /** * Clear all stored data */ private clear; /** * Start the cleanup interval for expired entries */ private startCleanupInterval; /** * Stop the cleanup interval */ private stopCleanupInterval; /** * Remove expired entries from the store */ private cleanupExpired; /** * Get storage statistics */ getStats(): Readonly; /** * Get current storage size */ getSize(): { keys: number; lists: number; total: number; }; /** * Manually trigger cleanup of expired entries */ cleanup(): Promise; } /** * Memory History Types * * Type definitions for the memory history storage service. * Defines interfaces for memory operation tracking and audit trails. * * @module storage/memory-history/types */ /** * Memory operation types */ type MemoryOperation = 'ADD' | 'UPDATE' | 'DELETE' | 'SEARCH' | 'RETRIEVE'; /** * Memory history entry interface */ interface MemoryHistoryEntry { /** Unique identifier (UUID) */ id: string; /** Project scope identifier */ projectId: string; /** Reference to memory entry */ memoryId: string; /** Descriptive operation name */ name: string; /** Categorization tags */ tags: string[]; /** User identifier (optional) */ userId?: string; /** Operation type */ operation: MemoryOperation; /** ISO timestamp */ timestamp: string; /** Flexible metadata storage */ metadata: Record; /** Operation success status */ success: boolean; /** Error details if failed */ error?: string; /** Session correlation */ sessionId?: string; /** Operation duration in ms */ duration?: number; } /** * Query options for filtering and pagination */ interface QueryOptions { /** Maximum number of results to return */ limit?: number; /** Number of results to skip */ offset?: number; /** Sort order (asc/desc) */ sortOrder?: 'asc' | 'desc'; /** Field to sort by */ sortBy?: keyof MemoryHistoryEntry; /** Include only successful operations */ successOnly?: boolean; /** Include only failed operations */ errorsOnly?: boolean; } /** * History filters for querying */ interface HistoryFilters { /** Filter by project ID */ projectId?: string; /** Filter by user ID */ userId?: string; /** Filter by memory ID */ memoryId?: string; /** Filter by operation type */ operation?: MemoryOperation | MemoryOperation[]; /** Filter by tags (must include all specified tags) */ tags?: string[]; /** Filter by session ID */ sessionId?: string; /** Filter by success status */ success?: boolean; /** Filter by time range - start time (ISO string) */ startTime?: string; /** Filter by time range - end time (ISO string) */ endTime?: string; /** Additional query options */ options?: QueryOptions; } /** * Operation statistics */ interface OperationStats { /** Total number of operations */ totalOperations: number; /** Count by operation type */ operationCounts: Record; /** Success count */ successCount: number; /** Error count */ errorCount: number; /** Average operation duration */ averageDuration?: number; /** Most common tags */ topTags: Array<{ tag: string; count: number; }>; /** Date range of data */ dateRange: { earliest: string; latest: string; }; } /** * Memory history service interface */ interface MemoryHistoryService { recordOperation(entry: MemoryHistoryEntry): Promise; getHistory(filters: HistoryFilters): Promise; getByProjectId(projectId: string, options?: QueryOptions): Promise; getByUserId(userId: string, options?: QueryOptions): Promise; getByTags(tags: string[], options?: QueryOptions): Promise; getByTimeRange(startTime: string, endTime: string, options?: QueryOptions): Promise; getOperationStats(projectId?: string, userId?: string): Promise; getSuccessRate(projectId?: string, userId?: string): Promise; connect(): Promise; disconnect(): Promise; isConnected(): boolean; } /** * Memory History Storage Service * * Core service implementation for tracking memory operations history. * Integrates with the existing dual-backend storage architecture. * * @module storage/memory-history/service */ /** * Memory History Service Implementation * * Provides persistence for memory operation audit trails with support for * multi-tenant and project-scoped storage using the existing storage infrastructure. */ declare class MemoryHistoryStorageService implements MemoryHistoryService { private readonly logger; private storageManager; private connected; private schemaInitialized; constructor(); /** * Initialize connection to storage backend */ connect(): Promise; /** * Disconnect from storage backend */ disconnect(): Promise; /** * Check if service is connected */ isConnected(): boolean; /** * Record a memory operation in history */ recordOperation(entry: MemoryHistoryEntry): Promise; /** * Get memory operation history with filters */ getHistory(filters: HistoryFilters): Promise; /** * Get history by project ID */ getByProjectId(projectId: string, options?: QueryOptions): Promise; /** * Get history by user ID */ getByUserId(userId: string, options?: QueryOptions): Promise; /** * Get history by tags */ getByTags(tags: string[], options?: QueryOptions): Promise; /** * Get history by time range */ getByTimeRange(startTime: string, endTime: string, options?: QueryOptions): Promise; /** * Get operation statistics */ getOperationStats(projectId?: string, userId?: string): Promise; /** * Get success rate for operations */ getSuccessRate(projectId?: string, userId?: string): Promise; /** * Initialize database schema */ private initializeSchema; /** * Ensure schema is initialized */ private ensureSchemaInitialized; /** * Validate memory history entry */ private validateEntry; /** * Query history with filters */ private queryHistory; /** * Update recent history cache */ private updateRecentHistoryCache; /** * Calculate statistics from entries */ private calculateStats; /** * Sanitize filters for logging (remove sensitive data) */ private sanitizeFilters; } /** * Memory History Storage Module * * Main export point for the memory history storage service. * Provides tracking and audit trails for memory operations. * * @module storage/memory-history */ /** * Create a new memory history service instance * * @returns A new MemoryHistoryStorageService instance * * @example * ```typescript * import { createMemoryHistoryService } from './storage/memory-history'; * * const historyService = createMemoryHistoryService(); * await historyService.connect(); * * await historyService.recordOperation({ * id: 'op-123', * projectId: 'project-1', * memoryId: 'mem-456', * name: 'Add knowledge about React hooks', * tags: ['react', 'hooks', 'javascript'], * operation: 'ADD', * timestamp: new Date().toISOString(), * metadata: { source: 'cli' }, * success: true * }); * ``` */ declare function createMemoryHistoryService(): MemoryHistoryStorageService; /** * Helper function to create a memory history entry * * @param params - Partial entry parameters * @returns Complete memory history entry with generated ID and timestamp * * @example * ```typescript * import { createMemoryHistoryEntry } from './storage/memory-history'; * * const entry = createMemoryHistoryEntry({ * projectId: 'project-1', * memoryId: 'mem-456', * name: 'Search for React patterns', * operation: 'SEARCH', * tags: ['react', 'patterns'], * success: true, * metadata: { query: 'react hooks patterns' } * }); * ``` */ declare function createMemoryHistoryEntry(params: Omit & { id?: string; timestamp?: string; }): MemoryHistoryEntry; /** * Storage Factory * * Factory functions for creating and initializing the storage system. * Provides a simplified API for common storage setup patterns. * * @module storage/factory */ /** * Factory result containing both the manager and backends */ interface StorageFactory { /** The storage manager instance for lifecycle control */ manager: StorageManager; /** The connected storage backends ready for use */ backends: StorageBackends; } /** * Creates and connects storage backends * * This is the primary factory function for initializing the storage system. * It creates a StorageManager, connects to the configured backends, and * returns both the manager and the connected backends. * * @param config - Storage configuration * @returns Promise resolving to manager and connected backends * @throws {StorageConnectionError} If connection fails and no fallback is available * * @example * ```typescript * // Basic usage * const { manager, backends } = await createStorageBackends({ * cache: { type: 'redis', host: 'localhost' }, * database: { type: 'sqlite', path: './data' } * }); * * // Use the backends * await backends.cache.set('key', 'value', 300); * await backends.database.set('user:1', userData); * * // Cleanup when done * await manager.disconnect(); * ``` * * @example * ```typescript * // Development configuration * const { manager, backends } = await createStorageBackends({ * cache: { type: 'in-memory' }, * database: { type: 'in-memory' } * }); * ``` */ declare function createStorageBackends(config: StorageConfig): Promise; /** * Creates storage backends with default configuration * * Convenience function that creates storage with in-memory backends. * Useful for testing or development environments. * * @returns Promise resolving to manager and connected backends * * @example * ```typescript * const { manager, backends } = await createDefaultStorage(); * // Uses in-memory backends for both cache and database * ``` */ declare function createDefaultStorage(): Promise; /** * Creates storage backends from environment variables * * Reads storage configuration from environment variables and creates * the storage system. Falls back to in-memory if not configured. * * Environment variables: * - STORAGE_CACHE_TYPE: Cache backend type (redis, in-memory) * - STORAGE_CACHE_HOST: Redis host (if using Redis) * - STORAGE_CACHE_PORT: Redis port (if using Redis) * - STORAGE_CACHE_USERNAME: Redis username (if using Redis) * - STORAGE_CACHE_PASSWORD: Redis password (if using Redis) * - STORAGE_DATABASE_TYPE: Database backend type (sqlite, in-memory) * - STORAGE_DATABASE_PATH: SQLite database path (if using SQLite) * * @returns Promise resolving to manager and connected backends * * @example * ```typescript * // Set environment variables * process.env.STORAGE_CACHE_TYPE = 'redis'; * process.env.STORAGE_CACHE_HOST = 'localhost'; * * const { manager, backends } = await createStorageFromEnv(); * ``` */ declare function createStorageFromEnv(): Promise; /** * Type guard to check if an object is a StorageFactory * * @param obj - Object to check * @returns true if the object has manager and backends properties */ declare function isStorageFactory(obj: unknown): obj is StorageFactory; /** * Storage Module Public API * * This module provides a flexible dual-backend storage system with: * - Cache backend for fast, ephemeral storage * - Database backend for persistent, reliable storage * * Features: * - Lazy loading of external backends (Redis, SQLite, etc.) * - Graceful fallback to in-memory storage * - Health monitoring and connection management * - Type-safe configuration with runtime validation * * @module storage */ type index$1_BackendConfig = BackendConfig; type index$1_CacheBackend = CacheBackend; type index$1_DatabaseBackend = DatabaseBackend; declare const index$1_HEALTH_CHECK: typeof HEALTH_CHECK; type index$1_HealthCheckResult = HealthCheckResult; type index$1_HistoryFilters = HistoryFilters; type index$1_InMemoryBackendConfig = InMemoryBackendConfig; type index$1_MemoryHistoryEntry = MemoryHistoryEntry; type index$1_MemoryHistoryService = MemoryHistoryService; type index$1_MemoryHistoryStorageService = MemoryHistoryStorageService; declare const index$1_MemoryHistoryStorageService: typeof MemoryHistoryStorageService; type index$1_MemoryOperation = MemoryOperation; type index$1_OperationStats = OperationStats; type index$1_PostgresBackendConfig = PostgresBackendConfig; type index$1_QueryOptions = QueryOptions; type index$1_RedisBackendConfig = RedisBackendConfig; type index$1_SqliteBackendConfig = SqliteBackendConfig; type index$1_StorageBackends = StorageBackends; type index$1_StorageConfig = StorageConfig; type index$1_StorageConnectionError = StorageConnectionError; declare const index$1_StorageConnectionError: typeof StorageConnectionError; type index$1_StorageError = StorageError; declare const index$1_StorageError: typeof StorageError; type index$1_StorageFactory = StorageFactory; type index$1_StorageInfo = StorageInfo; type index$1_StorageManager = StorageManager; declare const index$1_StorageManager: typeof StorageManager; type index$1_StorageNotFoundError = StorageNotFoundError; declare const index$1_StorageNotFoundError: typeof StorageNotFoundError; declare const index$1_StorageSchema: typeof StorageSchema; declare const index$1_createDefaultStorage: typeof createDefaultStorage; declare const index$1_createMemoryHistoryEntry: typeof createMemoryHistoryEntry; declare const index$1_createMemoryHistoryService: typeof createMemoryHistoryService; declare const index$1_createStorageBackends: typeof createStorageBackends; declare const index$1_createStorageFromEnv: typeof createStorageFromEnv; declare const index$1_isStorageFactory: typeof isStorageFactory; declare namespace index$1 { export { BACKEND_TYPES$1 as BACKEND_TYPES, type index$1_BackendConfig as BackendConfig, type index$1_CacheBackend as CacheBackend, DEFAULTS$1 as DEFAULTS, type index$1_DatabaseBackend as DatabaseBackend, ERROR_MESSAGES$1 as ERROR_MESSAGES, index$1_HEALTH_CHECK as HEALTH_CHECK, type index$1_HealthCheckResult as HealthCheckResult, type index$1_HistoryFilters as HistoryFilters, InMemoryBackend$1 as InMemoryBackend, type index$1_InMemoryBackendConfig as InMemoryBackendConfig, LOG_PREFIXES$1 as LOG_PREFIXES, type index$1_MemoryHistoryEntry as MemoryHistoryEntry, type index$1_MemoryHistoryService as MemoryHistoryService, index$1_MemoryHistoryStorageService as MemoryHistoryStorageService, type index$1_MemoryOperation as MemoryOperation, type index$1_OperationStats as OperationStats, type index$1_PostgresBackendConfig as PostgresBackendConfig, type index$1_QueryOptions as QueryOptions, type index$1_RedisBackendConfig as RedisBackendConfig, type index$1_SqliteBackendConfig as SqliteBackendConfig, type index$1_StorageBackends as StorageBackends, type index$1_StorageConfig as StorageConfig, index$1_StorageConnectionError as StorageConnectionError, index$1_StorageError as StorageError, type index$1_StorageFactory as StorageFactory, type index$1_StorageInfo as StorageInfo, index$1_StorageManager as StorageManager, index$1_StorageNotFoundError as StorageNotFoundError, index$1_StorageSchema as StorageSchema, TIMEOUTS$1 as TIMEOUTS, index$1_createDefaultStorage as createDefaultStorage, index$1_createMemoryHistoryEntry as createMemoryHistoryEntry, index$1_createMemoryHistoryService as createMemoryHistoryService, index$1_createStorageBackends as createStorageBackends, index$1_createStorageFromEnv as createStorageFromEnv, index$1_isStorageFactory as isStorageFactory }; } /** * Knowledge Graph Factory * * Factory functions for creating and initializing knowledge graph instances. * Provides a simplified API for common knowledge graph setup patterns. * * @module knowledge_graph/factory */ /** * Factory result containing both the manager and knowledge graph */ interface KnowledgeGraphFactory { /** The knowledge graph manager instance for lifecycle control */ manager: KnowledgeGraphManager; /** The connected knowledge graph ready for use */ graph: KnowledgeGraph; } /** * Creates and connects knowledge graph backend * * This is the primary factory function for initializing the knowledge graph system. * It creates a KnowledgeGraphManager, connects to the configured backend, and * returns both the manager and the connected knowledge graph. * * @param config - Knowledge graph configuration * @returns Promise resolving to manager and connected knowledge graph * @throws {KnowledgeGraphConnectionError} If connection fails and no fallback is available * * @example * ```typescript * // Basic usage with Neo4j * const { manager, graph } = await createKnowledgeGraph({ * type: 'neo4j', * host: 'localhost', * port: 7687, * username: 'neo4j', * password: 'password', * database: 'knowledge' * }); * * // Use the knowledge graph * await graph.addNode({ * id: 'entity1', * labels: ['Person'], * properties: { name: 'John Doe' } * }); * * // Cleanup when done * await manager.disconnect(); * ``` * * @example * ```typescript * // Development configuration with in-memory * const { manager, graph } = await createKnowledgeGraph({ * type: 'in-memory', * maxNodes: 1000, * maxEdges: 5000, * enableIndexing: true * }); * ``` */ declare function createKnowledgeGraph(config: KnowledgeGraphConfig): Promise; /** * Creates knowledge graph with default configuration * * Convenience function that creates knowledge graph with in-memory backend. * Useful for testing or development environments. * * @param maxNodes - Optional maximum nodes (default: 10000) * @param maxEdges - Optional maximum edges (default: 50000) * @returns Promise resolving to manager and connected knowledge graph * * @example * ```typescript * const { manager, graph } = await createDefaultKnowledgeGraph(); * // Uses in-memory backend with default settings * * const { manager, graph } = await createDefaultKnowledgeGraph(1000, 5000); * // Uses in-memory backend with custom limits * ``` */ declare function createDefaultKnowledgeGraph(maxNodes?: number, maxEdges?: number): Promise; /** * Creates knowledge graph from environment variables * * Reads knowledge graph configuration from environment variables and creates * the knowledge graph system. Returns null if knowledge graph is disabled. * * Environment variables: * - KNOWLEDGE_GRAPH_ENABLED: Whether knowledge graph is enabled (true/false) * - KNOWLEDGE_GRAPH_TYPE: Backend type (neo4j, in-memory) * - KNOWLEDGE_GRAPH_HOST: Neo4j host (if using Neo4j) * - KNOWLEDGE_GRAPH_PORT: Neo4j port (if using Neo4j) * - KNOWLEDGE_GRAPH_URI: Neo4j URI (if using Neo4j) * - KNOWLEDGE_GRAPH_USERNAME: Neo4j username (if using Neo4j) * - KNOWLEDGE_GRAPH_PASSWORD: Neo4j password (if using Neo4j) * - KNOWLEDGE_GRAPH_DATABASE: Neo4j database name * * @returns Promise resolving to manager and connected knowledge graph, or null if disabled * * @example * ```typescript * // Set environment variables * process.env.KNOWLEDGE_GRAPH_ENABLED = 'true'; * process.env.KNOWLEDGE_GRAPH_TYPE = 'neo4j'; * process.env.KNOWLEDGE_GRAPH_HOST = 'localhost'; * process.env.KNOWLEDGE_GRAPH_USERNAME = 'neo4j'; * process.env.KNOWLEDGE_GRAPH_PASSWORD = 'password'; * * const result = await createKnowledgeGraphFromEnv(); * if (result) { * const { manager, graph } = result; * // Use the knowledge graph * } else { * console.log('Knowledge graph is disabled'); * } * ``` */ declare function createKnowledgeGraphFromEnv(): Promise; /** * Creates Neo4j knowledge graph with specific configuration * * Convenience function for creating Neo4j backend with commonly used settings. * * @param connectionConfig - Neo4j connection configuration * @param options - Optional system configuration * @returns Promise resolving to manager and connected knowledge graph * * @example * ```typescript * const { manager, graph } = await createNeo4jKnowledgeGraph({ * host: 'localhost', * port: 7687, * username: 'neo4j', * password: 'password', * database: 'knowledge' * }); * ``` * * @example * ```typescript * // Using URI connection * const { manager, graph } = await createNeo4jKnowledgeGraph({ * uri: 'neo4j://localhost:7687', * username: 'neo4j', * password: 'password', * database: 'knowledge' * }); * ``` */ declare function createNeo4jKnowledgeGraph(connectionConfig: { uri?: string; host?: string; port?: number; username: string; password: string; database?: string; encrypted?: boolean; trustServerCertificate?: boolean; connectionTimeout?: number; maxPoolSize?: number; }, options?: { enableAutoIndexing?: boolean; enableMetrics?: boolean; enableQueryCache?: boolean; queryCacheTTL?: number; enableSchemaValidation?: boolean; defaultBatchSize?: number; }): Promise; /** * Creates in-memory knowledge graph with specific configuration * * Convenience function for creating in-memory backend with commonly used settings. * * @param options - Optional configuration options * @returns Promise resolving to manager and connected knowledge graph * * @example * ```typescript * const { manager, graph } = await createInMemoryKnowledgeGraph({ * maxNodes: 5000, * maxEdges: 25000, * enableIndexing: true, * enableGarbageCollection: true * }); * ``` */ declare function createInMemoryKnowledgeGraph(options?: { maxNodes?: number; maxEdges?: number; enableIndexing?: boolean; enableGarbageCollection?: boolean; enableAutoIndexing?: boolean; enableMetrics?: boolean; enableQueryCache?: boolean; queryCacheTTL?: number; enableSchemaValidation?: boolean; defaultBatchSize?: number; }): Promise; /** * Get knowledge graph configuration from environment variables * * Returns the configuration object that would be used by createKnowledgeGraphFromEnv * without actually creating the knowledge graph. Useful for debugging and validation. * * @returns Knowledge graph configuration based on environment variables, or null if disabled * * @example * ```typescript * const config = getKnowledgeGraphConfigFromEnv(); * if (config) { * console.log('Knowledge graph configuration:', config); * // Then use the config to create the graph * const { manager, graph } = await createKnowledgeGraph(config); * } else { * console.log('Knowledge graph is disabled'); * } * ``` */ declare function getKnowledgeGraphConfigFromEnv(): KnowledgeGraphConfig | null; /** * Type guard to check if an object is a KnowledgeGraphFactory * * @param obj - Object to check * @returns True if the object is a KnowledgeGraphFactory * * @example * ```typescript * const factory = await createKnowledgeGraph(config); * if (isKnowledgeGraphFactory(factory)) { * // TypeScript knows factory has manager and graph properties * console.log('Manager connected:', factory.manager.isConnected()); * } * ``` */ declare function isKnowledgeGraphFactory(obj: unknown): obj is KnowledgeGraphFactory; /** * Check if Neo4j configuration is available in environment * * @returns True if Neo4j connection can be configured from environment variables * * @example * ```typescript * if (isNeo4jConfigAvailable()) { * console.log('Neo4j configuration is available'); * const factory = await createKnowledgeGraphFromEnv(); * } else { * console.log('Using fallback configuration'); * const factory = await createDefaultKnowledgeGraph(); * } * ``` */ declare function isNeo4jConfigAvailable(): boolean; /** * Check if knowledge graph is enabled in environment * * @returns True if knowledge graph is enabled in environment variables * * @example * ```typescript * if (isKnowledgeGraphEnabled()) { * const factory = await createKnowledgeGraphFromEnv(); * // Knowledge graph is available * } else { * // Skip knowledge graph functionality * } * ``` */ declare function isKnowledgeGraphEnabled(): boolean; /** * Knowledge Graph Constants * * Centralized constants for the knowledge graph system. * Includes defaults, error messages, timeouts, and other configuration values. * * @module knowledge_graph/constants */ /** * Supported backend types */ declare const BACKEND_TYPES: { readonly NEO4J: "neo4j"; readonly IN_MEMORY: "in-memory"; }; /** * Default values for knowledge graph operations */ declare const DEFAULTS: { readonly CONNECTION_TIMEOUT: 30000; readonly MAX_RETRIES: 3; readonly POOL_SIZE: 10; readonly QUERY_LIMIT: 100; readonly QUERY_TIMEOUT: 60000; readonly BATCH_SIZE: 1000; readonly MAX_NODES: 10000; readonly MAX_EDGES: 50000; readonly NEO4J_PORT: 7687; readonly NEO4J_DATABASE: "neo4j"; readonly NEO4J_MAX_TRANSACTION_RETRY_TIME: 30000; readonly NEO4J_CONNECTION_ACQUISITION_TIMEOUT: 60000; readonly NEO4J_MAX_CONNECTION_LIFETIME: 3600000; readonly NEO4J_CONNECTION_LIVENESS_CHECK_TIMEOUT: 30000; readonly QUERY_CACHE_TTL: 300000; readonly SCHEMA_CACHE_TTL: 600000; readonly MAX_PATH_DEPTH: 10; readonly MAX_NEIGHBORS: 50; }; /** * Error messages for different failure scenarios */ declare const ERROR_MESSAGES: { readonly NOT_CONNECTED: "Knowledge graph backend is not connected"; readonly CONNECTION_FAILED: "Failed to connect to knowledge graph backend"; readonly CONNECTION_TIMEOUT: "Connection to knowledge graph backend timed out"; readonly AUTHENTICATION_FAILED: "Authentication failed for knowledge graph backend"; readonly NODE_NOT_FOUND: "Node not found in knowledge graph"; readonly INVALID_NODE_DATA: "Invalid node data provided"; readonly DUPLICATE_NODE_ID: "Node with this ID already exists"; readonly NODE_VALIDATION_FAILED: "Node validation failed"; readonly EDGE_NOT_FOUND: "Edge not found in knowledge graph"; readonly INVALID_EDGE_DATA: "Invalid edge data provided"; readonly DUPLICATE_EDGE_ID: "Edge with this ID already exists"; readonly EDGE_VALIDATION_FAILED: "Edge validation failed"; readonly NODES_NOT_FOUND_FOR_EDGE: "Start or end node not found for edge"; readonly INVALID_QUERY: "Invalid graph query provided"; readonly QUERY_EXECUTION_FAILED: "Graph query execution failed"; readonly QUERY_TIMEOUT: "Graph query timed out"; readonly UNSUPPORTED_QUERY_TYPE: "Unsupported query type"; readonly BACKEND_NOT_SUPPORTED: "Knowledge graph backend type not supported"; readonly BACKEND_INITIALIZATION_FAILED: "Failed to initialize knowledge graph backend"; readonly BACKEND_OPERATION_FAILED: "Knowledge graph backend operation failed"; readonly SCHEMA_VALIDATION_FAILED: "Schema validation failed"; readonly CONFIGURATION_INVALID: "Knowledge graph configuration is invalid"; readonly PROPERTY_VALIDATION_FAILED: "Property validation failed"; readonly TRANSACTION_FAILED: "Graph transaction failed"; readonly TRANSACTION_TIMEOUT: "Graph transaction timed out"; readonly CONCURRENT_MODIFICATION: "Concurrent modification detected"; readonly MEMORY_LIMIT_EXCEEDED: "Memory limit exceeded for in-memory backend"; readonly NODE_LIMIT_EXCEEDED: "Maximum number of nodes exceeded"; readonly EDGE_LIMIT_EXCEEDED: "Maximum number of edges exceeded"; }; /** * Timeout values for different operations */ declare const TIMEOUTS: { readonly CONNECTION: 30000; readonly HEALTH_CHECK: 5000; readonly DISCONNECTION: 10000; readonly QUERY: 60000; readonly TRANSACTION: 30000; readonly BATCH_OPERATION: 120000; readonly QUERY_CACHE: 300000; readonly SCHEMA_CACHE: 600000; readonly METRICS_CACHE: 60000; }; /** * Log prefixes for consistent logging */ declare const LOG_PREFIXES: { readonly MANAGER: "[KG-Manager]"; readonly BACKEND: "[KG-Backend]"; readonly NEO4J: "[KG-Neo4j]"; readonly IN_MEMORY: "[KG-Memory]"; readonly QUERY: "[KG-Query]"; readonly TRANSACTION: "[KG-Tx]"; readonly FACTORY: "[KG-Factory]"; readonly VALIDATION: "[KG-Validation]"; }; /** * Metrics and monitoring event names */ declare const METRICS_EVENTS: { readonly CONNECTION_ESTABLISHED: "kg.connection.established"; readonly CONNECTION_FAILED: "kg.connection.failed"; readonly CONNECTION_CLOSED: "kg.connection.closed"; readonly NODE_CREATED: "kg.node.created"; readonly NODE_UPDATED: "kg.node.updated"; readonly NODE_DELETED: "kg.node.deleted"; readonly EDGE_CREATED: "kg.edge.created"; readonly EDGE_UPDATED: "kg.edge.updated"; readonly EDGE_DELETED: "kg.edge.deleted"; readonly QUERY_EXECUTED: "kg.query.executed"; readonly QUERY_FAILED: "kg.query.failed"; readonly QUERY_CACHED: "kg.query.cached"; readonly OPERATION_DURATION: "kg.operation.duration"; readonly BATCH_OPERATION_DURATION: "kg.batch.duration"; readonly QUERY_DURATION: "kg.query.duration"; readonly HEALTH_CHECK_SUCCESS: "kg.health.success"; readonly HEALTH_CHECK_FAILURE: "kg.health.failure"; }; /** * Graph schema constants */ declare const SCHEMA: { readonly NODE_LABELS: { readonly FUNCTION: "Function"; readonly CLASS: "Class"; readonly VARIABLE: "Variable"; readonly MODULE: "Module"; readonly FILE: "File"; readonly CONCEPT: "Concept"; readonly ENTITY: "Entity"; }; readonly EDGE_TYPES: { readonly DEPENDS_ON: "DEPENDS_ON"; readonly CALLS: "CALLS"; readonly USES: "USES"; readonly BELONGS_TO: "BELONGS_TO"; readonly EXTENDS: "EXTENDS"; readonly IMPLEMENTS: "IMPLEMENTS"; readonly CONTAINS: "CONTAINS"; readonly REFERENCES: "REFERENCES"; readonly RELATES_TO: "RELATES_TO"; }; readonly PROPERTIES: { readonly ID: "id"; readonly NAME: "name"; readonly TYPE: "type"; readonly CREATED_AT: "created_at"; readonly UPDATED_AT: "updated_at"; readonly SOURCE: "source"; readonly CONFIDENCE: "confidence"; readonly LANGUAGE: "language"; readonly FILE_PATH: "file_path"; readonly LINE_NUMBER: "line_number"; readonly FUNCTION_NAME: "function_name"; readonly CLASS_NAME: "class_name"; readonly MODULE_NAME: "module_name"; readonly STRENGTH: "strength"; readonly CONTEXT: "context"; readonly FREQUENCY: "frequency"; readonly WEIGHT: "weight"; }; }; /** * Query templates for common operations */ declare const QUERY_TEMPLATES: { readonly CREATE_NODE: "CREATE (n:{labels} {properties}) RETURN n"; readonly GET_NODE: "MATCH (n) WHERE n.id = $id RETURN n"; readonly UPDATE_NODE: "MATCH (n) WHERE n.id = $id SET n += $properties RETURN n"; readonly DELETE_NODE: "MATCH (n) WHERE n.id = $id DETACH DELETE n"; readonly CREATE_EDGE: "MATCH (a), (b) WHERE a.id = $startId AND b.id = $endId CREATE (a)-[r:{type} {properties}]->(b) RETURN r"; readonly GET_EDGE: "MATCH ()-[r]-() WHERE r.id = $id RETURN r"; readonly UPDATE_EDGE: "MATCH ()-[r]-() WHERE r.id = $id SET r += $properties RETURN r"; readonly DELETE_EDGE: "MATCH ()-[r]-() WHERE r.id = $id DELETE r"; readonly FIND_NODES: "MATCH (n:{labels}) WHERE {filters} RETURN n LIMIT $limit"; readonly FIND_EDGES: "MATCH ()-[r:{type}]-() WHERE {filters} RETURN r LIMIT $limit"; readonly GET_NEIGHBORS: "MATCH (n)-[r:{types}]-(m) WHERE n.id = $id RETURN m, r LIMIT $limit"; readonly FIND_PATH: "MATCH path = shortestPath((a)-[*..{maxDepth}]-(b)) WHERE a.id = $startId AND b.id = $endId RETURN path"; readonly COUNT_NODES: "MATCH (n) RETURN count(n) as count"; readonly COUNT_EDGES: "MATCH ()-[r]-() RETURN count(r) as count"; readonly GET_LABELS: "CALL db.labels() YIELD label RETURN collect(label) as labels"; readonly GET_RELATIONSHIP_TYPES: "CALL db.relationshipTypes() YIELD relationshipType RETURN collect(relationshipType) as types"; }; /** * Index templates for performance optimization */ declare const INDEX_TEMPLATES: { readonly NODE_ID_INDEX: "CREATE INDEX node_id_index IF NOT EXISTS FOR (n:{label}) ON (n.id)"; readonly NODE_NAME_INDEX: "CREATE INDEX node_name_index IF NOT EXISTS FOR (n:{label}) ON (n.name)"; readonly NODE_TYPE_INDEX: "CREATE INDEX node_type_index IF NOT EXISTS FOR (n:{label}) ON (n.type)"; readonly EDGE_ID_INDEX: "CREATE INDEX edge_id_index IF NOT EXISTS FOR ()-[r:{type}]-() ON (r.id)"; readonly EDGE_TYPE_INDEX: "CREATE INDEX edge_type_index IF NOT EXISTS FOR ()-[r:{type}]-() ON (r.type)"; readonly NODE_COMPOUND_INDEX: "CREATE INDEX node_compound_index IF NOT EXISTS FOR (n:{label}) ON (n.id, n.type)"; readonly EDGE_COMPOUND_INDEX: "CREATE INDEX edge_compound_index IF NOT EXISTS FOR ()-[r:{type}]-() ON (r.id, r.type)"; }; /** * Neo4j Knowledge Graph Backend * * Production-grade graph database implementation using Neo4j. * Provides full Cipher query support and advanced graph operations. * * @module knowledge_graph/backend/neo4j */ /** * Neo4j Knowledge Graph Backend * * Provides a production-grade implementation using Neo4j graph database. * Supports Cypher queries, transactions, and advanced graph operations. * * @example * ```typescript * const backend = new Neo4jBackend({ * type: 'neo4j', * host: 'localhost', * port: 7687, * username: 'neo4j', * password: 'password', * database: 'neo4j' * }); * * await backend.connect(); * await backend.addNode({ * id: 'node1', * labels: ['Function'], * properties: { name: 'myFunction' } * }); * ``` */ declare class Neo4jBackend implements KnowledgeGraph { private readonly config; private readonly logger; private driver; private connected; constructor(config: Neo4jBackendConfig); connect(): Promise; disconnect(): Promise; isConnected(): boolean; getBackendType(): string; addNode(node: GraphNode): Promise; addNodes(nodes: GraphNode[]): Promise; getNode(nodeId: string): Promise; updateNode(nodeId: string, properties: Record, labels?: string[]): Promise; deleteNode(nodeId: string): Promise; findNodes(filters?: NodeFilters, labels?: string[], limit?: number): Promise; addEdge(edge: GraphEdge): Promise; addEdges(edges: GraphEdge[]): Promise; getEdge(edgeId: string): Promise; updateEdge(edgeId: string, properties: Record): Promise; deleteEdge(edgeId: string): Promise; findEdges(filters?: EdgeFilters, edgeType?: string, limit?: number): Promise; query(query: GraphQuery): Promise; getNeighbors(nodeId: string, direction?: 'in' | 'out' | 'both', edgeTypes?: string[], limit?: number): Promise>; findPath(startNodeId: string, endNodeId: string, maxDepth?: number, edgeTypes?: string[]): Promise<{ nodes: GraphNode[]; edges: GraphEdge[]; } | null>; clearGraph(): Promise; getStatistics(): Promise<{ nodeCount: number; edgeCount: number; labelCounts: Record; edgeTypeCounts: Record; }>; private ensureConnected; private getSession; private buildConnectionUri; private validateNode; private validateEdge; private convertNeo4jProperties; private buildFilterConstraints; private createIndexes; private executeNodeQuery; private executeEdgeQuery; private executePathQuery; private executeCypherQuery; } /** * In-Memory Knowledge Graph Backend * * Fast local storage implementation for development, testing, and small datasets. * All data is stored in memory using Map structures with optional indexing for performance. * * @module knowledge_graph/backend/in-memory */ /** * In-Memory Knowledge Graph Backend * * Provides a fast, local implementation of the knowledge graph interface. * All data is stored in memory and lost when the process terminates. * * @example * ```typescript * const backend = new InMemoryBackend({ * type: 'in-memory', * maxNodes: 10000, * maxEdges: 50000, * enableIndexing: true * }); * * await backend.connect(); * await backend.addNode({ * id: 'node1', * labels: ['Function'], * properties: { name: 'myFunction' } * }); * ``` */ declare class InMemoryBackend implements KnowledgeGraph { private readonly config; private readonly logger; private connected; private nodes; private edges; private outgoingEdges; private incomingEdges; private nodeIndex; private edgeIndex; private stats; constructor(config: InMemoryBackendConfig$1); connect(): Promise; disconnect(): Promise; isConnected(): boolean; getBackendType(): string; addNode(node: GraphNode): Promise; addNodes(nodes: GraphNode[]): Promise; getNode(nodeId: string): Promise; updateNode(nodeId: string, properties: Record, labels?: string[]): Promise; deleteNode(nodeId: string): Promise; findNodes(filters?: NodeFilters, labels?: string[], limit?: number): Promise; addEdge(edge: GraphEdge): Promise; addEdges(edges: GraphEdge[]): Promise; getEdge(edgeId: string): Promise; updateEdge(edgeId: string, properties: Record): Promise; deleteEdge(edgeId: string): Promise; findEdges(filters?: EdgeFilters, edgeType?: string, limit?: number): Promise; query(query: GraphQuery): Promise; getNeighbors(nodeId: string, direction?: 'in' | 'out' | 'both', edgeTypes?: string[], limit?: number): Promise>; findPath(startNodeId: string, endNodeId: string, maxDepth?: number, edgeTypes?: string[]): Promise<{ nodes: GraphNode[]; edges: GraphEdge[]; } | null>; clearGraph(): Promise; getStatistics(): Promise<{ nodeCount: number; edgeCount: number; labelCounts: Record; edgeTypeCounts: Record; }>; private ensureConnected; private validateNode; private validateEdge; private deepClone; private clear; private clearIndexes; private updateNodeIndex; private updateEdgeIndex; private matchesNodeFilters; private matchesEdgeFilters; private matchesFilter; private executeNodeQuery; private executeEdgeQuery; private executePathQuery; getInternalStats(): { memoryUsage: { nodes: number; edges: number; outgoingEdges: number; incomingEdges: number; }; indexSizes: { nodeLabels: number; nodeProperties: number; edgeTypes: number; edgeProperties: number; }; nodeCount: number; edgeCount: number; operations: number; queriesExecuted: number; lastOperation: number; }; } declare const index_BACKEND_TYPES: typeof BACKEND_TYPES; declare const index_DEFAULTS: typeof DEFAULTS; declare const index_ERROR_MESSAGES: typeof ERROR_MESSAGES; type index_EdgeFilters = EdgeFilters; type index_EdgeNotFoundError = EdgeNotFoundError; declare const index_EdgeNotFoundError: typeof EdgeNotFoundError; type index_GraphEdge = GraphEdge; type index_GraphNode = GraphNode; type index_GraphQuery = GraphQuery; type index_GraphResult = GraphResult; type index_GraphValidationError = GraphValidationError; declare const index_GraphValidationError: typeof GraphValidationError; declare const index_INDEX_TEMPLATES: typeof INDEX_TEMPLATES; type index_InMemoryBackend = InMemoryBackend; declare const index_InMemoryBackend: typeof InMemoryBackend; type index_InvalidQueryError = InvalidQueryError; declare const index_InvalidQueryError: typeof InvalidQueryError; type index_KnowledgeGraph = KnowledgeGraph; type index_KnowledgeGraphConfig = KnowledgeGraphConfig; type index_KnowledgeGraphConnectionError = KnowledgeGraphConnectionError; declare const index_KnowledgeGraphConnectionError: typeof KnowledgeGraphConnectionError; type index_KnowledgeGraphEnvConfig = KnowledgeGraphEnvConfig; declare const index_KnowledgeGraphEnvConfigSchema: typeof KnowledgeGraphEnvConfigSchema; type index_KnowledgeGraphError = KnowledgeGraphError; declare const index_KnowledgeGraphError: typeof KnowledgeGraphError; type index_KnowledgeGraphFactory = KnowledgeGraphFactory; type index_KnowledgeGraphInfo = KnowledgeGraphInfo; type index_KnowledgeGraphManager = KnowledgeGraphManager; declare const index_KnowledgeGraphManager: typeof KnowledgeGraphManager; declare const index_KnowledgeGraphSchema: typeof KnowledgeGraphSchema; type index_KnowledgeGraphStats = KnowledgeGraphStats; declare const index_LOG_PREFIXES: typeof LOG_PREFIXES; declare const index_METRICS_EVENTS: typeof METRICS_EVENTS; type index_Neo4jBackend = Neo4jBackend; declare const index_Neo4jBackend: typeof Neo4jBackend; type index_Neo4jBackendConfig = Neo4jBackendConfig; declare const index_Neo4jBackendSchema: typeof Neo4jBackendSchema; type index_NodeFilters = NodeFilters; type index_NodeNotFoundError = NodeNotFoundError; declare const index_NodeNotFoundError: typeof NodeNotFoundError; declare const index_QUERY_TEMPLATES: typeof QUERY_TEMPLATES; declare const index_SCHEMA: typeof SCHEMA; declare const index_TIMEOUTS: typeof TIMEOUTS; declare const index_createDefaultKnowledgeGraph: typeof createDefaultKnowledgeGraph; declare const index_createInMemoryKnowledgeGraph: typeof createInMemoryKnowledgeGraph; declare const index_createKnowledgeGraph: typeof createKnowledgeGraph; declare const index_createKnowledgeGraphFromEnv: typeof createKnowledgeGraphFromEnv; declare const index_createNeo4jKnowledgeGraph: typeof createNeo4jKnowledgeGraph; declare const index_getKnowledgeGraphConfigFromEnv: typeof getKnowledgeGraphConfigFromEnv; declare const index_isKnowledgeGraphEnabled: typeof isKnowledgeGraphEnabled; declare const index_isKnowledgeGraphFactory: typeof isKnowledgeGraphFactory; declare const index_isNeo4jConfigAvailable: typeof isNeo4jConfigAvailable; declare const index_parseKnowledgeGraphConfig: typeof parseKnowledgeGraphConfig; declare const index_parseKnowledgeGraphConfigFromEnv: typeof parseKnowledgeGraphConfigFromEnv; declare const index_validateKnowledgeGraphConfig: typeof validateKnowledgeGraphConfig; declare namespace index { export { index_BACKEND_TYPES as BACKEND_TYPES, type BackendConfig$1 as BackendConfig, BackendConfigSchema$1 as BackendConfigSchema, index_DEFAULTS as DEFAULTS, index_ERROR_MESSAGES as ERROR_MESSAGES, type index_EdgeFilters as EdgeFilters, index_EdgeNotFoundError as EdgeNotFoundError, type index_GraphEdge as GraphEdge, type index_GraphNode as GraphNode, type index_GraphQuery as GraphQuery, type index_GraphResult as GraphResult, index_GraphValidationError as GraphValidationError, type HealthCheckResult$1 as HealthCheckResult, index_INDEX_TEMPLATES as INDEX_TEMPLATES, index_InMemoryBackend as InMemoryBackend, type InMemoryBackendConfig$1 as InMemoryBackendConfig, InMemoryBackendSchema$1 as InMemoryBackendSchema, index_InvalidQueryError as InvalidQueryError, type index_KnowledgeGraph as KnowledgeGraph, type index_KnowledgeGraphConfig as KnowledgeGraphConfig, index_KnowledgeGraphConnectionError as KnowledgeGraphConnectionError, type index_KnowledgeGraphEnvConfig as KnowledgeGraphEnvConfig, index_KnowledgeGraphEnvConfigSchema as KnowledgeGraphEnvConfigSchema, index_KnowledgeGraphError as KnowledgeGraphError, type index_KnowledgeGraphFactory as KnowledgeGraphFactory, type index_KnowledgeGraphInfo as KnowledgeGraphInfo, index_KnowledgeGraphManager as KnowledgeGraphManager, index_KnowledgeGraphSchema as KnowledgeGraphSchema, type index_KnowledgeGraphStats as KnowledgeGraphStats, index_LOG_PREFIXES as LOG_PREFIXES, index_METRICS_EVENTS as METRICS_EVENTS, index_Neo4jBackend as Neo4jBackend, type index_Neo4jBackendConfig as Neo4jBackendConfig, index_Neo4jBackendSchema as Neo4jBackendSchema, type index_NodeFilters as NodeFilters, index_NodeNotFoundError as NodeNotFoundError, index_QUERY_TEMPLATES as QUERY_TEMPLATES, index_SCHEMA as SCHEMA, index_TIMEOUTS as TIMEOUTS, index_createDefaultKnowledgeGraph as createDefaultKnowledgeGraph, index_createInMemoryKnowledgeGraph as createInMemoryKnowledgeGraph, index_createKnowledgeGraph as createKnowledgeGraph, index_createKnowledgeGraphFromEnv as createKnowledgeGraphFromEnv, index_createNeo4jKnowledgeGraph as createNeo4jKnowledgeGraph, index_getKnowledgeGraphConfigFromEnv as getKnowledgeGraphConfigFromEnv, index_isKnowledgeGraphEnabled as isKnowledgeGraphEnabled, index_isKnowledgeGraphFactory as isKnowledgeGraphFactory, index_isNeo4jConfigAvailable as isNeo4jConfigAvailable, index_parseKnowledgeGraphConfig as parseKnowledgeGraphConfig, index_parseKnowledgeGraphConfigFromEnv as parseKnowledgeGraphConfigFromEnv, index_validateKnowledgeGraphConfig as validateKnowledgeGraphConfig }; } export { type AgentConfig, AgentConfigSchema, type AgentServices, type AwsConfig, AwsService, type AzureConfig, AzureService, CONNECTION_MODES, CantInferProviderError, type ChalkColor, ContextManager, ConversationSession, DEFAULT_CONFIG_PATH, DEFAULT_CONNECTION_MODE, DEFAULT_TIMEOUT_MS, ENV_VARS, ERROR_MESSAGES$2 as ERROR_MESSAGES, type ILLMService, type ImageData, type ImageSegment, type InternalMessage, index as KnowledgeGraph, type LLMConfig, LLMConfigSchema, type LLMServiceConfig, LMStudioService, LOG_PREFIXES$2 as LOG_PREFIXES, Logger, type LoggerOptions, MAX_TIMEOUT_MS, MCPClient, MCPManager, MIN_TIMEOUT_MS, MemAgent, OllamaService, OpenRouterService, ReasoningContentDetector, type ReasoningDetectionOptions, type ReasoningDetectionResult, SearchContextManager, type SearchContextOptions, type SearchResult, SessionManager, type SortedContext, index$1 as Storage, TRANSPORT_TYPES, type TextSegment, index$2 as VectorStorage, createAgentServices, createLogger, env, getGlobalLogLevel, logger, resolveConfigPath, setGlobalLogLevel, validateEnv };