UNPKG

@astreus-ai/astreus

Version:

Open-source AI agent framework for building autonomous systems that solve real-world tasks effectively.

1,584 lines (1,561 loc) 76.1 kB
import { Knex } from 'knex'; import { ChildProcess } from 'child_process'; /** * Common types used throughout the Astreus codebase */ /** * Primitive types that can be stored as metadata values */ type MetadataPrimitive = string | number | boolean | Date | null; /** * Complex metadata value that can contain primitives, arrays, or nested objects */ type MetadataValue = MetadataPrimitive | MetadataPrimitive[] | { [key: string]: MetadataValue; }; /** * Type for metadata objects used throughout the application. * Provides type safety while maintaining flexibility for various metadata use cases. */ type MetadataObject = Record<string, MetadataValue>; interface ToolParameter { name: string; type: 'string' | 'number' | 'boolean' | 'object' | 'array'; description: string; required?: boolean; enum?: Array<string | number>; properties?: Record<string, ToolParameter>; items?: ToolParameter; } interface ToolDefinition { name: string; description: string; parameters: Record<string, ToolParameter>; handler: ToolHandler; } /** * Primitive values that can be passed as tool parameters */ type ToolParameterPrimitive = string | number | boolean | null; /** * Complex tool parameter value that can contain primitives, arrays, or nested objects */ type ToolParameterValue = ToolParameterPrimitive | ToolParameterPrimitive[] | { [key: string]: ToolParameterValue; }; interface ToolHandler { (params: Record<string, ToolParameterValue>, context?: ToolContext): Promise<ToolResult>; } interface ToolContext { agentId: string; taskId?: string; agent?: { hasKnowledge(): boolean; searchKnowledge?(query: string, limit: number, threshold: number): Promise<Array<{ content: string; metadata: MetadataObject; similarity: number; }>>; expandKnowledgeContext?(documentId: string, // UUID chunkIndex: number, expandBefore?: number, expandAfter?: number): Promise<string[]>; }; userId?: string; metadata?: MetadataObject; executionId?: string; toolName?: string; callTimestamp?: Date; } interface ToolResult { success: boolean; data?: ToolParameterValue; error?: string; metadata?: MetadataObject; } interface ToolCall$1 { id: string; name: string; parameters: Record<string, ToolParameterValue>; } interface ToolCallResult { id: string; name: string; result: ToolResult; executionTime: number; } interface Plugin$1 { name: string; version: string; description: string; tools: ToolDefinition[]; initialize?: (config?: Record<string, ToolParameterValue>) => Promise<void>; cleanup?: () => Promise<void>; } interface PluginConfig { name: string; enabled: boolean; config?: Record<string, ToolParameterValue>; } interface PluginManager { registerPlugin(plugin: Plugin$1, config?: PluginConfig): Promise<void>; unregisterPlugin(name: string): Promise<void>; getPlugin(name: string): Plugin$1 | undefined; getTools(): ToolDefinition[]; getTool(name: string): ToolDefinition | undefined; executeTool(toolCall: ToolCall$1, context?: ToolContext): Promise<ToolCallResult>; listPlugins(): Plugin$1[]; } type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'success' | 'silent'; /** * Primitive values that can be logged (including undefined for optional properties) */ type LogDataPrimitive = string | number | boolean | null | undefined | Date; /** * Complex log data that can contain primitives, arrays, or nested objects */ type LogData = LogDataPrimitive | LogDataPrimitive[] | { [key: string]: LogData; }; interface LoggerConfig { level: LogLevel; debug: boolean; enableConsole: boolean; enableFile?: boolean; filePath?: string; maxFileSize?: number; maxFiles?: number; agentName?: string; } interface Logger$1 { debug(message: string, data?: LogData, agentName?: string): void; info(message: string, data?: LogData, agentName?: string): void; warn(message: string, data?: LogData, agentName?: string): void; error(message: string, error?: Error, data?: LogData, agentName?: string): void; success(message: string, data?: LogData, agentName?: string): void; log(level: LogLevel, message: string, module: string, data?: LogData, error?: Error, agentName?: string): void; setLevel(level: LogLevel): void; setDebug(debug: boolean): void; flush(): Promise<void>; dispose(): void; readonly config: LoggerConfig; } interface LLMMessageContentPart { type: 'text' | 'image_url'; text?: string; image_url?: { url: string; detail?: 'low' | 'high' | 'auto'; }; } type LLMMessageContent = string | LLMMessageContentPart[]; interface LLMMessage { role: 'system' | 'user' | 'assistant' | 'tool'; content: LLMMessageContent; tool_call_id?: string; tool_calls?: ToolCall[]; } interface ToolCall { id: string; type: 'function'; function: { name: string; arguments: Record<string, string | number | boolean | null>; }; } interface Tool { type: 'function'; function: { name: string; description: string; parameters: { type: 'object'; properties: Record<string, { type: 'string' | 'number' | 'boolean' | 'object' | 'array'; description?: string; enum?: Array<string | number>; items?: { type: string; }; properties?: Record<string, { type: 'string' | 'number' | 'boolean' | 'object' | 'array'; description?: string; }>; }>; required?: string[]; }; }; } interface LLMRequestOptions { model: string; messages: LLMMessage[]; temperature?: number; maxTokens?: number; stream?: boolean; systemPrompt?: string; tools?: Tool[]; } interface LLMUsage { promptTokens: number; completionTokens: number; totalTokens: number; cost?: number; } interface LLMResponse { content: string; model: string; toolCalls?: ToolCall[]; usage?: LLMUsage; } interface LLMStreamChunk { content: string; done: boolean; model: string; toolCalls?: ToolCall[]; usage?: LLMUsage; } interface VisionAnalysisOptions { prompt?: string; maxTokens?: number; temperature?: number; detail?: 'low' | 'high' | 'auto'; model?: string; } interface VisionAnalysisResult { content: string; confidence?: number; metadata?: { model?: string; provider?: string; processingTime?: number; tokenUsage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; }; } interface EmbeddingResult { embedding: number[]; model: string; usage?: { promptTokens: number; totalTokens: number; }; } interface LLMProvider { name: string; generateResponse(options: LLMRequestOptions): Promise<LLMResponse>; generateStreamResponse(options: LLMRequestOptions): AsyncIterableIterator<LLMStreamChunk>; getSupportedModels(): string[]; getVisionModels(): string[]; getEmbeddingModels(): string[]; generateEmbedding?(text: string, model?: string): Promise<EmbeddingResult>; analyzeImage?(imagePath: string, options?: VisionAnalysisOptions): Promise<VisionAnalysisResult>; analyzeImageFromBase64?(base64Data: string, options?: VisionAnalysisOptions): Promise<VisionAnalysisResult>; getEmbeddingProvider?(): LLMProvider; getVisionProvider?(): LLMProvider; } /** * Primitive values that can be used in MCP */ type MCPPrimitive = string | number | boolean | null; /** * Complex MCP values that can contain primitives, arrays, or nested objects */ type MCPValue = MCPPrimitive | MCPPrimitive[] | { [key: string]: MCPValue; }; /** * JSON Schema representation for MCP tools */ type MCPJsonSchema = { type: string; properties?: Record<string, MCPJsonSchema>; items?: MCPJsonSchema; required?: string[]; enum?: Array<string | number>; description?: string; }; interface MCPServerConfig { command?: string; args?: string[]; env?: Record<string, string>; url?: string; cwd?: string; } interface MCPTool { name: string; description: string; inputSchema: MCPJsonSchema; } interface MCPToolCall { name: string; arguments: Record<string, MCPValue>; } interface MCPToolResult { content: Array<{ type: string; text?: string; }>; isError?: boolean; } interface MCPServerDefinition extends MCPServerConfig { name: string; } type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed'; interface Task$1 { id: string; agentId: string; graphId?: string; graphNodeId?: string; prompt: string; response?: string; status: TaskStatus; metadata?: MetadataObject; executionContext?: Record<string, unknown>; createdAt: Date; updatedAt: Date; completedAt?: Date; } interface TaskSearchOptions { limit?: number; offset?: number; status?: TaskStatus; graphId?: string; orderBy?: 'createdAt' | 'updatedAt' | 'completedAt'; order?: 'asc' | 'desc'; } interface TaskRequest { prompt: string; graphId?: string; graphNodeId?: string; useTools?: boolean; mcpServers?: MCPServerDefinition[]; plugins?: Array<{ plugin: Plugin$1; config?: PluginConfig; }>; attachments?: Array<{ type: 'image' | 'pdf' | 'text' | 'markdown' | 'code' | 'json' | 'file'; path: string; name?: string; language?: string; }>; schedule?: string; metadata?: MetadataObject; executionContext?: Record<string, unknown>; useSubAgents?: boolean; subAgentDelegation?: 'auto' | 'manual' | 'sequential'; subAgentCoordination?: 'parallel' | 'sequential'; taskAssignment?: Record<string, string>; } interface TaskResponse { task: Task$1; response: string; model?: string; usage?: LLMUsage; } interface Memory$1 { id: string; agentId: string; graphId?: string; taskId?: string; sessionId?: string; content: string; embedding?: number[]; metadata?: MetadataObject; createdAt: Date; updatedAt: Date; } interface MemorySearchOptions { limit?: number; offset?: number; pageSize?: number; graphId?: string; taskId?: string; sessionId?: string; orderBy?: 'createdAt' | 'updatedAt' | 'relevance'; order?: 'asc' | 'desc'; startDate?: Date; endDate?: Date; similarityThreshold?: number; useEmbedding?: boolean; } interface AnalysisOptions { prompt?: string; maxTokens?: number; detail?: 'low' | 'high' | 'auto'; } interface ContextMessage { role: 'user' | 'assistant' | 'system'; content: string; timestamp?: Date; metadata?: MetadataObject; tokens?: number; } interface CompressionResult { success: boolean; compressedMessages: ContextMessage[]; tokensReduced: number; compressionRatio: number; strategy?: string; error?: string; } interface ContextCompressorOptions { maxContextLength?: number; compressionRatio?: number; preserveLastN?: number; model?: string; provider?: LLMProvider; compressionStrategy?: 'summarize' | 'selective' | 'hybrid'; enableSemanticCompression?: boolean; preserveImportantContext?: boolean; } interface ContextAnalysis { totalTokens: number; messageCount: number; averageTokensPerMessage: number; contextUtilization: number; compressionNeeded: boolean; suggestedCompressionRatio?: number; } interface ContextWindow { messages: ContextMessage[]; totalTokens: number; maxTokens: number; utilizationPercentage: number; } interface ContextManager$1 { addMessage(message: ContextMessage): Promise<void>; getMessages(): ContextMessage[]; getContextWindow(): ContextWindow; analyzeContext(): ContextAnalysis; compressContext(): Promise<CompressionResult>; clearContext(): Promise<void>; shouldCompress(): boolean; exportContext(): string; importContext(data: string): void; updateModel(model: string): void; loadFromMemory(memoryModule: { listMemories: (options: { limit: number; orderBy: string; order: string; }) => Promise<Array<{ id: string; content: string; created_at: string; graphId?: string; taskId?: string; sessionId?: string; metadata?: MetadataObject; }>>; }, limit?: number): Promise<boolean>; saveToMemory(memoryModule: { addMemory: (content: string, metadata?: MetadataObject, context?: { graphId?: string; taskId?: string; sessionId?: string; }) => Promise<{ id: string; content: string; }>; }): Promise<boolean>; initializeForAgent(agentId: string): Promise<void>; saveToStorage(): Promise<void>; } interface ContextSummary { mainTopics: string[]; keyEntities: string[]; conversationFlow: string; importantFacts: string[]; actionItems?: string[]; } /** * Core types for the agent system */ /** * Task module methods - bound when Task module is available */ interface ITaskMethods { createTask(request: TaskRequest): Promise<Task$1>; getTask(id: string): Promise<Task$1 | null>; listTasks(options?: TaskSearchOptions): Promise<Task$1[]>; updateTask(id: string, updates: Partial<Task$1>): Promise<Task$1 | null>; deleteTask(id: string): Promise<boolean>; clearTasks(): Promise<number>; executeTask(taskId: string, // UUID options?: { model?: string; stream?: boolean; }): Promise<TaskResponse>; } /** * Memory module methods - bound when Memory module is available */ interface IMemoryMethods { addMemory(content: string, metadata?: MetadataObject): Promise<Memory$1>; getMemory(id: string): Promise<Memory$1 | null>; searchMemories(query: string, options?: MemorySearchOptions): Promise<Memory$1[]>; listMemories(options?: MemorySearchOptions): Promise<Memory$1[]>; updateMemory(id: string, // UUID updates: { content?: string; metadata?: MetadataObject; }): Promise<Memory$1 | null>; deleteMemory(id: string): Promise<boolean>; clearMemories(): Promise<number>; rememberConversation(content: string, role?: 'user' | 'assistant'): Promise<Memory$1>; searchMemoriesBySimilarity(query: string, options?: MemorySearchOptions): Promise<Memory$1[]>; generateEmbeddingForMemory(memoryId: string): Promise<{ success: boolean; message: string; embedding?: number[]; }>; } /** * Knowledge module methods - bound when Knowledge module is available */ interface IKnowledgeMethods { addKnowledge(content: string, title?: string, metadata?: MetadataObject): Promise<string>; searchKnowledge(query: string, limit?: number, threshold?: number): Promise<Array<{ content: string; metadata: MetadataObject; similarity: number; }>>; getKnowledgeContext(query: string, limit?: number): Promise<string>; getKnowledgeDocuments(): Promise<Array<{ id: string; title: string; created_at: string; }>>; deleteKnowledgeDocument(documentId: string): Promise<boolean>; deleteKnowledgeChunk(chunkId: string): Promise<boolean>; clearKnowledge(): Promise<void>; addKnowledgeFromFile(filePath: string, metadata?: MetadataObject): Promise<void>; addKnowledgeFromDirectory(dirPath: string, metadata?: MetadataObject): Promise<void>; expandKnowledgeContext(documentId: string, // UUID chunkIndex: number, expandBefore?: number, expandAfter?: number): Promise<string[]>; } /** * Plugin module methods - bound when Plugin module is available */ interface IPluginMethods { registerPlugin(plugin: Plugin$1, config?: PluginConfig): Promise<void>; unregisterPlugin(name: string): Promise<void>; listPlugins(): Plugin$1[]; getTools(): ToolDefinition[]; executeTool(toolCall: ToolCall$1): Promise<ToolCallResult>; } /** * MCP module methods - bound when MCP module is available */ interface IMCPMethods { addMCPServer(serverDef: MCPServerDefinition): Promise<void>; addMCPServers(servers: MCPServerDefinition[]): Promise<void>; removeMCPServer(name: string): void; callMCPTool(toolName: string, args: Record<string, MCPValue>): Promise<{ content: Array<{ type: string; text?: string; }>; isError?: boolean; }>; getMCPTools(): MCPTool[]; } /** * Vision module methods - bound when Vision module is available */ interface IVisionMethods { analyzeImage(imagePath: string, options?: AnalysisOptions): Promise<string>; describeImage(imagePath: string): Promise<string>; extractTextFromImage(imagePath: string): Promise<string>; } /** * Context module methods - bound when context management is enabled */ interface IContextMethods { getContextMessages(): ContextMessage[]; getContextWindow(): ContextWindow; analyzeContext(): ContextAnalysis; compressContext(): Promise<CompressionResult>; clearContext?(options?: { syncWithMemory?: boolean; }): Promise<void>; exportContext?(): string; importContext?(data: string): void; generateContextSummary(): Promise<ContextSummary>; updateContextModel(model: string): void; searchContext(options: { query?: string; graphId?: string; taskId?: string; sessionId?: string; role?: 'user' | 'assistant' | 'system'; limit?: number; }): ContextMessage[]; } /** * SubAgent module methods - bound when SubAgent module is available */ interface ISubAgentMethods { executeWithSubAgents(prompt: string, subAgents: IAgent[], options?: Record<string, string | number | boolean | object | null>, mainModel?: string): Promise<string>; delegateTask(taskPrompt: string, targetAgent: IAgent, options?: Record<string, string | number | boolean | object | null>): Promise<string>; coordinateAgents(tasks: Array<{ agent: IAgent; prompt: string; }>, coordination?: 'parallel' | 'sequential'): Promise<Array<{ task: { agent: IAgent; prompt: string; }; result: string; }>>; } /** * Base interface that all agents must implement */ interface IAgent { id: string; name: string; config: AgentConfig; logger: Logger$1; run(prompt: string, options?: RunOptions): Promise<string>; ask(prompt: string, options?: AskOptions): Promise<string>; canUseTools(): boolean; hasMemory(): boolean; hasKnowledge(): boolean; hasVision(): boolean; getContext(): ContextMessage[]; clearContext?(options?: { syncWithMemory?: boolean; }): Promise<void>; exportContext?(): string; importContext?(data: string): void; addMemory?(content: string, metadata?: MetadataObject): Promise<Memory$1>; loadGraphContext?(graphId: string, limit?: number, isolated?: boolean): Promise<void>; } /** * Base interface for all agent modules */ interface IAgentModule { readonly name: string; initialize(): Promise<void>; destroy?(): Promise<void>; } /** * Agent configuration input (for creating new agents) */ interface AgentConfigInput { name: string; description?: string; model?: string; embeddingModel?: string; visionModel?: string; temperature?: number; maxTokens?: number; systemPrompt?: string; memory?: boolean; knowledge?: boolean; vision?: boolean; useTools?: boolean; autoContextCompression?: boolean; maxContextLength?: number; preserveLastN?: number; compressionRatio?: number; compressionStrategy?: 'summarize' | 'selective' | 'hybrid'; debug?: boolean; subAgents?: IAgent[]; } /** * Agent configuration (complete, from database) */ interface AgentConfig extends AgentConfigInput { id: string; memory: boolean; knowledge: boolean; vision: boolean; useTools: boolean; autoContextCompression: boolean; debug: boolean; createdAt: Date; updatedAt: Date; } /** * Options for agent.run() method */ interface RunOptions { model?: string; temperature?: number; maxTokens?: number; stream?: boolean; useTools?: boolean; onChunk?: (chunk: string) => void; } /** * Options for agent.ask() method */ interface AskOptions { model?: string; temperature?: number; maxTokens?: number; stream?: boolean; useTools?: boolean; onChunk?: (chunk: string) => void; timeout?: number; useSubAgents?: boolean; delegation?: 'auto' | 'manual' | 'sequential'; taskAssignment?: Record<string, string>; coordination?: 'parallel' | 'sequential'; contextIsolation?: 'isolated' | 'shared' | 'merge'; attachments?: Array<{ type: 'image' | 'pdf' | 'text' | 'markdown' | 'code' | 'json' | 'file'; path: string; name?: string; language?: string; }>; mcpServers?: Array<{ name: string; command?: string; args?: string[]; url?: string; cwd?: string; }>; plugins?: Array<{ plugin: { name: string; version: string; description?: string; tools?: Array<{ name: string; description: string; parameters: Record<string, { name: string; type: 'string' | 'number' | 'boolean' | 'object' | 'array'; description: string; required?: boolean; }>; handler: (params: Record<string, string | number | boolean | null>) => Promise<{ success: boolean; data?: string | number | boolean | object; error?: string; }>; }>; }; config?: Record<string, string | number | boolean | null>; }>; } /** * Complete Agent interface with all possible bound methods * This reflects what the Agent class actually provides after module binding */ interface IAgentWithModules extends IAgent, ITaskMethods, IContextMethods, // Context is now always available, not Partial Partial<IMemoryMethods>, Partial<IKnowledgeMethods>, Partial<IPluginMethods>, Partial<IMCPMethods>, Partial<IVisionMethods>, Partial<ISubAgentMethods> { updateModel(model: string): void; getContext(): ContextMessage[]; /** * Clear all data: both memory and context * This ensures Memory and Context are always synchronized */ clearAll(): Promise<{ memoriesCleared: number; contextCleared: boolean; }>; } declare class Logger implements Logger$1 { private pino; config: LoggerConfig; private transportWorker; constructor(config?: Partial<LoggerConfig>); private formatLogObject; debug(message: string, data?: LogData, agentName?: string): void; info(message: string, data?: LogData, agentName?: string): void; warn(message: string, data?: LogData, agentName?: string): void; error(message: string, error?: Error, data?: LogData, agentName?: string): void; success(message: string, data?: LogData, agentName?: string): void; log(level: LogLevel, message: string, module?: string, data?: LogData, error?: Error, agentName?: string): void; setLevel(level: LogLevel): void; setDebug(debug: boolean): void; /** * Cleanup the transport worker to prevent memory leaks */ private cleanupTransportWorker; /** * Flush any pending log entries and cleanup resources. * Call this before application shutdown. */ flush(): Promise<void>; /** * Dispose of the logger instance and cleanup resources. */ dispose(): void; } declare function getLogger(config?: Partial<LoggerConfig>): Logger; declare function initializeLogger(config: Partial<LoggerConfig>): Promise<Logger>; /** * Cleanup the global logger instance. * Call this during application shutdown to ensure proper resource cleanup. */ declare function shutdownLogger(): Promise<void>; /** * Reset the global logger instance (useful for testing). */ declare function resetLogger(): void; /** * Abstract base class for all agents * Provides core functionality and database operations */ declare abstract class BaseAgent implements IAgent { data: AgentConfig; logger: Logger; protected sessionMessages: ContextMessage[]; constructor(data: AgentConfig); /** * Abstract method that must be implemented by concrete agent classes */ abstract run(prompt: string, options?: RunOptions): Promise<string>; /** * Abstract method that must be implemented by concrete agent classes */ abstract ask(prompt: string, options?: AskOptions): Promise<string>; /** * Abstract context methods that must be implemented by concrete agent classes */ abstract getContext(): ContextMessage[]; abstract clearContext(options?: { syncWithMemory?: boolean; }): Promise<void>; abstract exportContext(): string; abstract importContext(data: string): void; get id(): string; get name(): string; get config(): AgentConfig; canUseTools(): boolean; hasMemory(): boolean; hasKnowledge(): boolean; hasVision(): boolean; update(updates: Partial<AgentConfig>): Promise<void>; delete(): Promise<boolean>; getId(): string; getName(): string; getDescription(): string | null; getModel(): string; getTemperature(): number; getMaxTokens(): number; getSystemPrompt(): string | null; /** * Protected helper for concrete implementations */ protected callLLM(prompt: string, options?: RunOptions): Promise<string>; } /** * Main Agent class with module system */ declare class Agent extends BaseAgent implements IAgentWithModules { private static creationLock; private operationLock; private operationQueue; private modules; constructor(data: AgentConfig); createTask(request: TaskRequest): Promise<Task$1>; getTask(id: string): Promise<Task$1 | null>; listTasks(options?: TaskSearchOptions): Promise<Task$1[]>; updateTask(id: string, updates: Partial<Task$1>): Promise<Task$1 | null>; deleteTask(id: string): Promise<boolean>; clearTasks(): Promise<number>; executeTask(taskId: string, options?: { model?: string; stream?: boolean; }): Promise<TaskResponse>; addMemory(content: string, metadata?: MetadataObject): Promise<Memory$1>; getMemory(id: string): Promise<Memory$1 | null>; searchMemories(query: string, options?: MemorySearchOptions): Promise<Memory$1[]>; listMemories(options?: MemorySearchOptions): Promise<Memory$1[]>; updateMemory(id: string, updates: { content?: string; metadata?: MetadataObject; }): Promise<Memory$1 | null>; deleteMemory(id: string): Promise<boolean>; clearMemories(): Promise<number>; /** * Clear all data: both memory and context * This ensures Memory and Context are always synchronized */ clearAll(): Promise<{ memoriesCleared: number; contextCleared: boolean; }>; /** * Clear session messages to free memory. * Call this when conversation context is no longer needed. */ clearSessionMessages(): void; /** * Destroy agent resources and free memory. * Call this when the agent is no longer needed. * All cleanup operations are performed even if some fail. */ destroy(): Promise<void>; rememberConversation(content: string, role?: 'user' | 'assistant'): Promise<Memory$1>; searchMemoriesBySimilarity(query: string, options?: MemorySearchOptions): Promise<Memory$1[]>; generateEmbeddingForMemory(memoryId: string): Promise<{ success: boolean; message: string; embedding?: number[]; }>; addKnowledge(content: string, title?: string, metadata?: MetadataObject): Promise<string>; searchKnowledge(query: string, limit?: number, threshold?: number): Promise<Array<{ content: string; metadata: MetadataObject; similarity: number; }>>; getKnowledgeContext(query: string, limit?: number): Promise<string>; getKnowledgeDocuments(): Promise<Array<{ id: string; title: string; created_at: string; }>>; deleteKnowledgeDocument(documentId: string): Promise<boolean>; deleteKnowledgeChunk(chunkId: string): Promise<boolean>; clearKnowledge(): Promise<void>; addKnowledgeFromFile(filePath: string, metadata?: MetadataObject): Promise<void>; addKnowledgeFromDirectory(dirPath: string, metadata?: MetadataObject): Promise<void>; expandKnowledgeContext(documentId: string, chunkIndex: number, expandBefore?: number, expandAfter?: number): Promise<string[]>; registerPlugin(plugin: Plugin$1, config?: PluginConfig): Promise<void>; unregisterPlugin(name: string): Promise<void>; listPlugins(): Plugin$1[]; getTools(): ToolDefinition[]; executeTool(toolCall: ToolCall$1): Promise<ToolCallResult>; addMCPServer(serverDef: MCPServerDefinition): Promise<void>; addMCPServers(servers: MCPServerDefinition[]): Promise<void>; removeMCPServer(name: string): void; callMCPTool(toolName: string, args: Record<string, MCPValue>): Promise<{ content: Array<{ type: string; text?: string; }>; isError?: boolean; }>; getMCPTools(): MCPTool[]; analyzeImage(imagePath: string, options?: AnalysisOptions): Promise<string>; describeImage(imagePath: string): Promise<string>; extractTextFromImage(imagePath: string): Promise<string>; executeWithSubAgents(prompt: string, subAgents: IAgent[], options?: Record<string, string | number | boolean | object | null>, mainModel?: string): Promise<string>; delegateTask(taskPrompt: string, targetAgent: IAgent, options?: Record<string, string | number | boolean | object | null>): Promise<string>; coordinateAgents(tasks: Array<{ agent: IAgent; prompt: string; }>, coordination?: 'parallel' | 'sequential'): Promise<Array<{ task: { agent: IAgent; prompt: string; }; result: string; }>>; private getContextModule; getContextMessages(): ContextMessage[]; getContextWindow(): ContextWindow; analyzeContext(): ContextAnalysis; compressContext(): Promise<CompressionResult>; clearContext(options?: { syncWithMemory?: boolean; }): Promise<void>; exportContext(): string; importContext(data: string): void; generateContextSummary(): Promise<ContextSummary>; updateContextModel(model: string): void; /** * Search context messages with filtering support * Supports graphId, taskId, sessionId, role, and text query filters */ searchContext(options: { query?: string; graphId?: string; taskId?: string; sessionId?: string; role?: 'user' | 'assistant' | 'system'; limit?: number; }): ContextMessage[]; /** * Get conversation context messages based on memory configuration * This is the central method that all modules use to get conversation history */ getContext(): ContextMessage[]; /** * Save current context to memory */ private saveContextToMemory; /** * Update agent's model and propagate to context manager */ updateModel(model: string): void; /** * Load conversation history from memory for a specific graph * @param graphId - The graph ID to load context for * @param limit - Maximum number of messages to load * @param isolated - If true, only load graph-specific memories (default: false) * If false, load both general agent memories + graph-specific memories */ loadGraphContext(graphId: string, limit?: number, isolated?: boolean): Promise<void>; /** * Initialize all modules */ initializeModules(): Promise<void>; /** * Factory method to create a new agent or find existing one by name. * Uses a lock mechanism to prevent race conditions when creating agents * with the same name concurrently. * * Note: If the first creation attempt fails, subsequent callers will NOT * receive the rejected promise - instead they will start a fresh creation attempt. */ static create(config: AgentConfigInput): Promise<Agent>; /** * Internal method that performs the actual agent creation. * Should not be called directly - use create() instead. */ private static _doCreate; /** * Find agent by ID */ static findById(id: string): Promise<Agent | null>; /** * Find agent by name */ static findByName(name: string): Promise<Agent | null>; /** * List all agents (returns only agent data without initializing modules). * Use this for listing/browsing agents without full initialization. * @param options - Optional settings * @param options.initialize - If true, fully initialize all agents (default: false for performance) * @param options.limit - Maximum number of agents to return (default: 100, max: 1000) * @param options.offset - Number of agents to skip for pagination (default: 0) */ static list(options?: { initialize?: boolean; limit?: number; offset?: number; }): Promise<Agent[]>; /** * Acquire operation lock to prevent concurrent chat/run operations * Operations are queued and executed sequentially to prevent state corruption * Uses a proper async queue instead of busy-wait loop for efficiency * @param timeout - Maximum time to wait for lock acquisition (default: 60000ms) * @returns A release function to be called when operation completes */ private acquireOperationLock; /** * Main run method - protected by operation lock to prevent concurrent state corruption */ run(prompt: string, options?: RunOptions): Promise<string>; /** * Ask method - direct conversation with the agent (task-independent) * Protected by operation lock to prevent concurrent state corruption */ ask(prompt: string, options?: AskOptions): Promise<string>; /** * Internal ask implementation - do not call directly, use ask() instead */ private _askInternal; /** * Update agent configuration * Ensures module state consistency even if initialization or cleanup fails */ update(updates: Partial<AgentConfig>): Promise<void>; } /** * Types for the SubAgent system */ /** * Context isolation strategy for sub-agents * - 'isolated': SubAgent executes in its own context, changes don't affect parent Agent * - 'shared': SubAgent shares context with parent Agent (changes propagate to parent) * - 'merge': SubAgent context changes are merged back to parent after execution */ type ContextIsolationStrategy = 'isolated' | 'shared' | 'merge'; /** * Options for running main agent with sub-agents */ interface SubAgentRunOptions extends RunOptions { useSubAgents?: boolean; delegation?: 'auto' | 'manual' | 'sequential'; taskAssignment?: Record<string, string>; coordination?: 'parallel' | 'sequential'; contextIsolation?: ContextIsolationStrategy; } /** * Sub-agent task assignment */ interface SubAgentTask { taskId?: string; agentId: string; task: string; priority?: number; dependencies?: string[]; } /** * Sub-agent execution result */ interface SubAgentResult { agentId: string; agentName: string; task: string; result: string; success: boolean; error?: string; executionTime: number; } /** * Delegation strategy interface */ interface DelegationStrategy { name: 'auto' | 'manual' | 'sequential'; delegate(prompt: string, subAgents: IAgent[], options?: SubAgentRunOptions, model?: string): Promise<SubAgentTask[]>; } /** * Sub-agent coordination result */ interface SubAgentCoordinationResult { success: boolean; results: SubAgentResult[]; finalResult: string; totalExecutionTime: number; errors: string[]; } /** * SubAgent module - Manages sub-agent coordination and delegation */ declare class SubAgent implements IAgentModule { readonly name = "subAgent"; private coordinator; private logger; constructor(logger?: Logger$1); initialize(): Promise<void>; /** * Execute task using sub-agents * @param prompt - The prompt/task to execute * @param subAgents - Array of sub-agents to use * @param options - Execution options including contextIsolation strategy * @param mainAgentModel - Optional model override for main agent * @param parentAgent - Optional parent agent for context merging */ executeWithSubAgents(prompt: string, subAgents: IAgent[], options?: AskOptions, mainAgentModel?: string, parentAgent?: IAgent): Promise<string>; /** * Get detailed results from sub-agent execution */ executeWithSubAgentsDetailed(prompt: string, subAgents: IAgent[], options?: AskOptions, mainAgentModel?: string): Promise<SubAgentCoordinationResult>; /** * Check if an agent has sub-agents */ hasSubAgents(agent: IAgent): boolean; /** * Get sub-agents for an agent */ getSubAgents(agent: IAgent): IAgent[]; /** * Destroy SubAgent module and free resources. * Call this when the module is no longer needed. */ destroy(): Promise<void>; } /** * Callback type for memory change events */ type MemoryChangeCallback = (event: 'update' | 'delete' | 'clear', data: { memoryId?: string; content?: string; metadata?: MetadataObject; }) => void | Promise<void>; /** * Memory module for agent conversation memory * * Features: * - Read-write locking for concurrent access * - Deadlock prevention via lock timeouts * - Starvation prevention for write operations */ declare class Memory implements IAgentModule { private agent; readonly name = "memory"; private knex; private logger; private _encryption?; private static readonly MAX_MEMORIES_FETCH; private static initMutex; private static initPromise; private rwLock; private onChangeCallback; private get encryption(); constructor(agent: IAgent); /** * Register a callback for memory change events * This allows the Agent to synchronize Context when memories are updated/deleted */ onMemoryChange(callback: MemoryChangeCallback): void; /** * Notify registered callback about memory changes */ private notifyChange; initialize(): Promise<void>; private ensureDatabase; private doInitialize; /** * Generate embedding for memory content */ private generateEmbedding; /** * Add a memory */ addMemory(content: string, metadata?: MetadataObject, context?: { graphId?: string; taskId?: string; sessionId?: string; }): Promise<Memory$1>; /** * Remember a conversation (alias for add with conversation metadata) */ rememberConversation(content: string, role?: 'user' | 'assistant'): Promise<Memory$1>; /** * Get a memory by ID */ getMemory(id: string): Promise<Memory$1 | null>; /** * Search memories */ searchMemories(query: string, options?: MemorySearchOptions): Promise<Memory$1[]>; /** * List memories */ listMemories(options?: MemorySearchOptions): Promise<Memory$1[]>; /** * Update a memory */ updateMemory(id: string, updates: { content?: string; metadata?: MetadataObject; }): Promise<Memory$1 | null>; /** * Delete a memory */ deleteMemory(id: string): Promise<boolean>; /** * Search memories using vector similarity with pagination to prevent memory leaks */ searchMemoriesBySimilarity(query: string, options?: MemorySearchOptions): Promise<Memory$1[]>; /** * Calculate cosine similarity between two vectors * @throws Error if embedding dimensions do not match */ private cosineSimilarity; /** * Generate embedding for a specific memory */ generateEmbeddingForMemory(memoryId: string): Promise<{ success: boolean; message: string; embedding?: number[]; }>; /** * Clear all memories * @param options - Optional settings for clearing memories * @param options.syncWithContext - If true (default), notifies Context to also clear. Set to false to clear only Memory. */ clearMemories(options?: { syncWithContext?: boolean; }): Promise<number>; /** * Format memory from database */ private formatMemory; /** * Destroy Memory module and free resources. * Call this when the module is no longer needed. */ destroy(): Promise<void>; } declare class Task implements IAgentModule { private agent; readonly name = "task"; private knex; private logger; private static initializingDatabase; private static readonly MAX_TOOL_CALLS; private static initMutex; constructor(agent: IAgent); initialize(): Promise<void>; private ensureDatabase; private getKnex; createTask(request: TaskRequest): Promise<Task$1>; executeTask(taskId: string, options?: { model?: string; stream?: boolean; onChunk?: (chunk: string) => void; onToolCall?: (toolName: string, args: Record<string, unknown>, status: 'start' | 'end', result?: string) => void; }): Promise<TaskResponse>; getTask(id: string): Promise<Task$1 | null>; listTasks(options?: TaskSearchOptions): Promise<Task$1[]>; updateTask(id: string, updates: Partial<Task$1>): Promise<Task$1 | null>; private updateTaskStatus; deleteTask(id: string): Promise<boolean>; clearTasks(): Promise<number>; private formatTask; } type DatabaseType = 'sqlite' | 'postgres'; interface DatabaseConnection { filename?: string; host?: string; port?: number; user?: string; password?: string; database?: string; ssl?: boolean; } interface DatabasePool { min?: number; max?: number; } interface DatabaseConfig { type?: DatabaseType; driver?: 'sqlite' | 'postgres' | 'pg'; connectionString?: string; filename?: string; host?: string; port?: number; user?: string; password?: string; database?: string; client?: string; connection?: DatabaseConnection; pool?: DatabasePool; /** Maximum number of connections in the pool (default: 10) */ maxPoolSize?: number; /** Minimum number of connections in the pool (default: 2) */ minPoolSize?: number; } declare class Database { protected knex: Knex; protected config: DatabaseConfig; private logger; private _encryption?; private get encryption(); /** * Check if using SQLite database */ isSQLite(): boolean; /** * Check if an index exists on a table */ private checkIndexExists; /** * Check if using PostgreSQL database */ isPostgres(): boolean; /** * Generate a new UUID */ generateUUID(): string; /** * Get the knex instance for direct database operations */ getKnex(): Knex; constructor(config: DatabaseConfig, logger?: Logger$1); connect(): Promise<void>; disconnect(): Promise<void>; initialize(): Promise<void>; createAgent(data: AgentConfigInput): Promise<AgentConfig>; getAgent(id: string): Promise<AgentConfig | null>; getAgentByName(name: string): Promise<AgentConfig | null>; listAgents(): Promise<AgentConfig[]>; updateAgent(id: string, data: Partial<AgentConfig>): Promise<AgentConfig | null>; deleteAgent(id: string): Promise<boolean>; private formatAgent; } declare function getDatabase(): Promise<Database>; /** * Request priority levels for fair scheduling */ declare enum RequestPriority { /** High priority - Agent.ask() direct user interactions */ HIGH = 0, /** Normal priority - Task execution, SubAgent operations */ NORMAL = 1, /** Low priority - Background tasks like context compression */ LOW = 2 } declare class LLM { private providers; private logger; constructor(logger?: Logger$1); private initializeProvider; generateResponse(options: LLMRequestOptions, priority?: RequestPriority, caller?: string): Promise<LLMResponse>; generateStreamResponse(options: LLMRequestOptions, priority?: RequestPriority, caller?: string): AsyncIterableIterator<LLMStreamChunk>; getSupportedModels(): string[]; getAvailableProviders(): string[]; generateEmbedding(text: string, model?: string): Promise<{ embedding: number[]; }>; private getProviderForModel; } declare function getLLM(logger?: Logger$1): LLM; declare function clearLLMInstances(): void; /** * Primitive values that can be returned as node results */ type GraphResultPrimitive = string | number | boolean | null | Date; /** * Complex result data that can contain primitives, arrays, or nested objects */ type GraphResultValue = GraphResultPrimitive | GraphResultPrimitive[] | { [key: string]: GraphResultValue; }; type GraphNodeType = 'agent' | 'task'; type GraphExecutionStatus = 'idle' | 'running' | 'completed' | 'failed' | 'paused'; /** * Token usage statistics for a node */ interface NodeUsage { promptTokens: number; completionTokens: number; totalTokens: number; contextTokens?: number; model?: string; cost?: number; } interface GraphNode { id: string; type: GraphNodeType; name: string; description?: string; agentId?: string; agent?: Agent; prompt?: string; model?: string; stream?: boolean; taskId?: string; useSubAgents?: boolean; subAgentDelegation?: 'auto' | 'manual' | 'sequential'; subAgentCoordination?: 'parallel' | 'sequential'; status: 'pending' | 'running' | 'completed' | 'failed' | 'skipped' | 'scheduled'; priority: number; dependencies: string[]; schedule?: string; result?: GraphResultValue; error?: string; usage?: NodeUsage; metadata?: MetadataObject; createdAt: Date; updatedAt: Date; } interface GraphEdge { id: string; fromNodeId: string; toNodeId: string; condition?: string; metadata?: MetadataObject; createdAt: Date; updatedAt: Date; } /** * Graph-level usage statistics */ interface GraphUsage { totalPromptTokens: number; totalCompletionTokens: number; totalTokens: number; totalContextTokens: number; totalCost: number; nodeUsages: Record<string, NodeUsage>; modelsUsed: string[]; } interface GraphConfig { id?: string; name: string; description?: string; maxConcurrency?: number; timeout?: number; retryAttempts?: number; subAgentAware?: boolean; optimizeSubAgentUsage?: boolean; subAgentCoordination?: 'parallel' | 'sequential' | 'adaptive'; autoLink?: boolean; maxContextTokens?: number; contextWarningThreshold?: number; subAgentNodeTimeout?: number; metadata?: MetadataObject; } interface Graph$1 { id?: string; defaultAgentId?: string; config: GraphConfig; nodes: GraphNode[]; edges: GraphEdge[]; status: GraphExecutionStatus; startedAt?: Date; completedAt?: Date; executionLog: GraphExecutionLogEntry[]; usage?: GraphUsage; createdAt: Date; updatedAt: Date; } interface GraphExecutionLogEntry { timestamp: Date; level: 'info' | 'warn' | 'error' | 'debug'; message: string; nodeId?: string; metadata?: MetadataObject; } interface GraphExecutionResult { graph: Graph$1; success: boolean; completedNodes: number; failedNodes: number; duration: number; results: Record<string, GraphResultValue>; errors: Record<string, string>; usage: GraphUsage; } interface AddNodeOptions { dependencies?: string[]; priority?: number; metadata?: MetadataObject; } interface AddAgentNodeOptions extends AddNodeOptions { agentId: string; } interface AddTaskNodeOptions extends AddNodeOptions { name?: string; prompt: string; model?: string; agentId?: string; stream?: boolean; schedule?: string; dependsOn?: string[]; useSubAgents?: boolean; subAgentDelegation?: 'auto' | 'manual' | 'sequential'; subAgentCoordination?: 'parallel' | 'sequential'; } interface GraphSchedulingOptions { respectSchedules?: boolean; waitForScheduled?: boolean; schedulingCheckInterval?: number; onChunk?: (chunk: string) => void; } /** * State change event for graph execution tracking * Allows Agent to track state changes during graph execution */ interface GraphStateChangeEvent { type: 'node_started' | 'node_completed' | 'node_failed' | 'graph_started' | 'graph_completed' | 'graph_failed'; nodeId?: string; nodeName?: string; graphId?: string; status: GraphExecutionStatus; result?: GraphResultValue; error?: string; usage?: NodeUsage; timestamp: Date; } /** * Callback type for graph state change events * This allows Agent to track state changes during graph execution */ type GraphStateChangeCallback = (event: GraphStateChangeEvent) => void | Promise<voi