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<void>;

declare class Graph implements IAgentModule {
    readonly name = "graph";
    private knex;
    private graph;
    private initialized;
    private agent?;
    private logger?;
    lastNodeId: string | null;
    private static readonly MAX_NODES;
    private static readonly MAX_EDGES;
    private executionLock;
    private releaseLock;
    private stateChangeCallback;
    private executionState;
    private activeNodeTimeouts;
    private overallTimeoutId;
    constructor(config: GraphConfig, agent?: IAgent);
    initialize(): Promise<void>;
    /**
     * Register a callback for graph state change events
     * This allows Agent to track state changes during graph execution
     */
    onStateChange(callback: GraphStateChangeCallback): void;
    /**
     * Notify registered callback about state changes
     */
    private notifyStateChange;
    /**
     * Get the current execution state of all nodes
     * Useful for Agent to sync its state with graph execution
     */
    getExecutionState(): Map<string, {
        status: string;
        result?: unknown;
        error?: string;
    }>;
    /**
     * Get the current state of a specific node
     */
    getNodeExecutionState(nodeId: string): {
        status: string;
        result?: unknown;
        error?: string;
    } | undefined;
    /**
     * Clear execution state (useful after graph reset)
     */
    clearExecutionState(): void;
    addAgentNode(options: AddAgentNodeOptions): string;
    addTaskNode(options: AddTaskNodeOptions): string;
    addEdge(fromNodeId: string, toNodeId: string, condition?: string): string;
    /**
     * Acquire the execution lock, waiting if another execution is in progress
     * Returns a release function to be called when execution is complete
     * @param timeout - Maximum time to wait for lock acquisition (default: 30000ms)
     * @throws Error if lock acquisition times out
     */
    private acquireLock;
    run(options?: {
        stream?: boolean;
        onChunk?: (chunk: string) => void;
        onToolCall?: (toolName: string, args: Record<string, unknown>, status: 'start' | 'end', result?: string) => void;
        timeout?: number;
        nodeTimeout?: number;
    } & GraphSchedulingOptions): Promise<GraphExecutionResult>;
    private executeGraph;
    /**
     * Aggregate usage statistics from all completed nodes
     */
    private aggregateUsage;
    /**
     * Check context size and warn if approaching limits
     */
    private checkContextSize;
    private executeNode;
    /**
     * Save task response to memory with graph context
     */
    private saveResponseToMemory;
    private areDependenciesCompleted;
    private hasFailedDependencies;
    /**
     * Build contextual information about the graph for sub-agent coordination
     */
    private buildGraphContext;
    /**
     * Determine if a node should use sub-agents for execution
     */
    private shouldUseSubAgents;
    /**
     * Iterative topological sort to prevent stack overflow on large graphs
     * Uses Kahn's algorithm with in-degree tracking
     */
    private topologicalSort;
    private static readonly MAX_EXECUTION_LOG_SIZE;
    private log;
    private generateNodeId;
    private generateEdgeId;
    getGraph(): Graph$1;
    getNodes(): GraphNode[];
    getEdges(): GraphEdge[];
    getStatus(): GraphExecutionStatus;
    setStatus(status: GraphExecutionStatus): void;
    getExecutionLog(): GraphExecutionLogEntry[];
    getNode(id: string): GraphNode | undefined;
    getNodesByType(type: 'agent' | 'task'): GraphNode[];
    getNodesByStatus(status: GraphNode['status']): GraphNode[];
    searchMemories(query: string, limit?: number): Promise<Memory$1[]>;
    save(): Promise<string>;
    update(): Promise<void>;
    delete(): Promise<boolean>;
    static findById(graphId: string, agent?: IAgent): Promise<Graph | null>;
    static list(): Promise<{
        id: string;
        name: string;
        status: string;
        createdAt: Date;
    }[]>;
    static create(config: GraphConfig, agent?: IAgent): Promise<Graph>;
    /**
     * Enable sub-agent awareness for all task nodes in the graph
     */
    enableSubAgentAwareness(): void;
    /**
     * Configure sub-agent delegation for specific nodes
     */
    configureSubAgentDelegation(nodeIds: string[], delegation: 'auto' | 'manual' | 'sequential'): void;
    /**
     * Configure sub-agent coordination for specific nodes
     */
    configureSubAgentCoordination(nodeIds: string[], coordination: 'parallel' | 'sequential'): void;
    /**
     * Get nodes that are currently using sub-agents
     */
    getSubAgentEnabledNodes(): GraphNode[];
    /**
     * Get sub-agent usage statistics for the graph
     */
    getSubAgentStats(): {
        totalNodes: number;
        subAgentEnabledNodes: number;
        delegationStrategies: Record<string, number>;
        coordinationPatterns: Record<string, number>;
    };
    /**
     * Optimize sub-agent usage across the graph based on task complexity
     */
    optimizeSubAgentUsage(): void;
    /**
     * Monitor and analyze sub-agent performance during execution
     */
    getSubAgentPerformanceMetrics(): {
        nodePerformance: Array<{
            nodeId: string;
            nodeName: string;
            usedSubAgents: boolean;
            delegationStrategy?: string;
            coordinationPattern?: string;
            executionTime?: number;
            status: string;
        }>;
        overallMetrics: {
            totalNodes: number;
            subAgentNodes: number;
            averageExecutionTime: number;
            successRate: number;
            subAgentEfficiency: number;
        };
    };
    /**
     * Benchmark different sub-agent coordination strategies
     */
    benchmarkSubAgentStrategies(testPrompt?: string): Promise<{
        strategies: Record<string, {
            duration: number;
            success: boolean;
            nodeResults: number;
        }>;
        recommendation: string;
    }>;
    /**
     * Dynamically adjust sub-agent coordination based on current performance
     */
    autoOptimizeSubAgentCoordination(): void;
    /**
     * Generate performance report for sub-agent usage
     */
    generateSubAgentPerformanceReport(): string;
    /**
     * Get all tasks created by this graph
     */
    getTasks(options?: {
        limit?: number;
        offset?: number;
        status?: string;
    }): Promise<unknown[]>;
    /**
     * Get task for a specific node
     */
    getTaskByNode(nodeId: string): Promise<unknown | null>;
    /**
     * Get aggregated usage statistics for the graph
     */
    getUsage(): GraphUsage | undefined;
    /**
     * Get usage statistics for a specific node
     */
    getNodeUsage(nodeId: string): NodeUsage | undefined;
    /**
     * Get total token count across all nodes
     */
    getTotalTokens(): number;
    /**
     * Get total cost across all nodes
     */
    getTotalCost(): number;
    /**
     * Get context size information
     */
    getContextInfo(): {
        currentTokens: number;
        maxTokens: number;
        utilization: number;
        isWarning: boolean;
        isExceeded: boolean;
    } | null;
    /**
     * Get usage summary as formatted string
     */
    getUsageSummary(): string;
    /**
     * Get all memories created during this graph execution
     */
    getMemories(options?: {
        limit?: number;
        sessionId?: string;
    }): Promise<unknown[]>;
    /**
     * Destroy graph resources and free memory.
     * Call this when the graph is no longer needed.
     */
    destroy(): Promise<void>;
}

interface LLMToolProperty {
    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;
    }>;
}
interface LLMToolSchema {
    type: 'object';
    properties: Record<string, LLMToolProperty>;
    required?: string[];
}
declare class Plugin implements IAgentModule, PluginManager {
    private agent;
    readonly name = "plugin";
    private plugins;
    private configs;
    private tools;
    private logger;
    private registrationLock;
    constructor(agent: IAgent);
    initialize(): Promise<void>;
    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[];
    getToolsForLLM(): Array<{
        type: string;
        function: {
            name: string;
            description: string;
            parameters: LLMToolSchema;
        };
    }>;
    private validatePlugin;
    private validateToolParameterDefinitions;
    private validateToolParameters;
    private isToolParameterValue;
    private validateParameterType;
    convertParametersToJsonSchema(parameters: Record<string, ToolParameter>, depth?: number): LLMToolSchema;
}
declare function getPlugin(agent?: IAgent): Plugin;

interface MCPMessage {
    jsonrpc: string;
    id?: string | number;
    method?: string;
    params?: Record<string, MCPValue>;
    result?: {
        tools?: MCPTool[];
    } & Record<string, MCPValue>;
    error?: {
        code: number;
        message: string;
        data?: MCPValue;
    };
}
declare class MCP implements IAgentModule {
    private agent;
    readonly name = "mcp";
    processes: Map<string, ChildProcess>;
    tools: Map<string, MCPTool>;
    servers: Map<string, MCPServerConfig>;
    private logger;
    private pendingCallbacks;
    private messageHandlers;
    private toolCallTimeout;
    private forceKillTimers;
    constructor(agent: IAgent);
    initialize(): Promise<void>;
    /**
     * Set the timeout for MCP tool calls
     * @param timeoutMs Timeout in milliseconds
     */
    setToolCallTimeout(timeoutMs: number): void;
    /**
     * Cleanup resources for a specific server
     * @param name Server name
     */
    private cleanupServerResources;
    /**
     * Cleanup all resources - call this before destroying the MCP instance
     */
    cleanup(): Promise<void>;
    /**
     * Alias for cleanup() - for consistent destroy() method naming across modules
     */
    destroy(): Promise<void>;
    startMCPServer(name: string, config: MCPServerConfig): Promise<void>;
    handleMessage(serverName: string, message: MCPMessage): void;
    sendToServer(name: string, message: MCPMessage): void;
    getMCPTools(): MCPTool[];
    /**
     * Validate a server definition before adding it
     * @param serverDef The server definition to validate
     * @throws Error if the server definition is invalid
     */
    private validateServerDefinition;
    addMCPServer(serverDef: MCPServerDefinition): Promise<void>;
    addMCPServers(servers: MCPServerDefinition[]): Promise<void>;
    removeMCPServer(name: string): void;
    /**
     * Validate MCP tool parameters against inputSchema (JSON Schema)
     * @param tool The MCP tool definition
     * @param args The arguments to validate
     * @returns Error message if validation fails, null if successful
     */
    private validateMCPToolParameters;
    /**
     * Validate a single parameter value against its JSON schema
     */
    private validateMCPParameterType;
    callMCPTool(toolName: string, args: Record<string, MCPValue>): Promise<MCPToolResult>;
}
/**
 * Get or create an MCP instance for a specific agent.
 * Each agent has its own isolated MCP instance to prevent cross-contamination.
 * @param agent The agent to get the MCP instance for (required)
 * @returns The MCP instance for the agent
 */
declare function getMCP(agent?: IAgent): MCP;

interface KnowledgeDatabaseConfig {
    url?: string;
    embeddingProvider?: {
        name: string;
        generateEmbedding?: (text: string, model?: string) => Promise<{
            embedding: number[];
        }>;
    };
    embeddingModel?: string;
}

declare const knowledgeSearchTool: ToolDefinition;
declare const knowledgeTools: ToolDefinition[];

interface KnowledgeConfig {
    database?: KnowledgeDatabaseConfig;
    embeddingProvider?: 'openai' | 'gemini' | 'ollama';
    embeddingModel?: string;
    embeddingApiKey?: string;
    chunkSize?: number;
    chunkOverlap?: number;
}
declare class Knowledge implements IAgentModule {
    private agent;
    readonly name = "knowledge";
    private database;
    private embeddingProvider;
    private embeddingModel;
    private chunkSize;
    private chunkOverlap;
    private logger;
    private config;
    constructor(agent: IAgent, config?: KnowledgeConfig);
    initialize(): Promise<void>;
    private initializeEmbeddingProvider;
    /**
     * Get or create a cached OpenAI provider instance
     */
    private getCachedOpenAIProvider;
    /**
     * Get or create a cached Gemini provider instance
     */
    private getCachedGeminiProvider;
    /**
     * Get or create a cached Ollama provider instance
     */
    private getCachedOllamaProvider;
    private detectProviderFromModel;
    private autoDetectEmbeddingProvider;
    private getDatabase;
    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>;
    expandKnowledgeContext(documentId: string, chunkIndex: number, expandBefore?: number, expandAfter?: number): Promise<string[]>;
    addKnowledgeFromFile(filePath: string, metadata?: MetadataObject): Promise<void>;
    addKnowledgeFromDirectory(dirPath: string, metadata?: MetadataObject): Promise<void>;
    private readTextFile;
    private readPdfFile;
    private chunkText;
}

type ScheduleType = 'once' | 'recurring';
type RecurrencePattern = 'daily' | 'weekly' | 'monthly' | 'yearly' | 'custom';
interface RecurrenceConfig {
    pattern: RecurrencePattern;
    interval?: number;
    endDate?: Date;
    maxExecutions?: number;
    daysOfWeek?: number[];
    dayOfMonth?: number;
    monthOfYear?: number;
    customCron?: string;
}
interface Schedule {
    type: ScheduleType;
    executeAt: Date;
    recurrence?: RecurrenceConfig;
    timezone?: string;
    metadata?: MetadataObject;
    delayMs?: number;
}
interface ScheduledItem {
    id: string;
    type: 'task' | 'graph' | 'graph_node';
    schedule: Schedule;
    targetId: string | number;
    agentId: string;
    status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
    executionCount: number;
    lastExecutedAt?: Date;
    nextExecutionAt?: Date;
    createdAt: Date;
    updatedAt: Date;
    metadata?: MetadataObject;
}
interface ScheduleOptions {
    respectDependencies?: boolean;
    maxRetries?: number;
    retryDelay?: number;
    timeout?: number;
}
interface SchedulerConfig {
    checkInterval?: number;
    maxConcurrentJobs?: number;
    enableRecurring?: boolean;
    timezone?: string;
}

interface ParsedSchedule {
    schedule: Schedule;
    isValid: boolean;
    error?: string;
}
/**
 * Parses simple schedule strings into full Schedule objects
 *
 * Supported formats:
 * - 'daily@07:00' → daily at 7 AM
 * - 'weekly@monday@09:00' → weekly on Monday at 9 AM
 * - 'monthly@1@10:00' → monthly on 1st day at 10 AM
 * - 'hourly' → every hour
 * - '@15:30' → once today at 3:30 PM
 * - 'once@2024-12-25@10:00' → once on specific date
 * - 'after:5s' → run after 5 seconds delay
 * - 'after:30m' → run after 30 minutes delay
 * - 'after:2h' → run after 2 hours delay
 */
declare function parseScheduleString(scheduleStr: string, timezone?: string): ParsedSchedule;

declare class ContextCompressor {
    private logger;
    private options;
    constructor(options?: ContextCompressorOptions);
    /**
     * Token estimation ratios for different content types.
     * Based on empirical analysis of typical tokenization patterns.
     *
     * Reference values (characters per token):
     * - English prose: ~4 chars/token
     * - Code (mixed): ~3.5 chars/token (more special chars, shorter words)
     * - JSON/structured data: ~3 chars/token (lots of punctuation)
     * - Markdown: ~3.8 chars/token (formatting characters)
     * - Technical text: ~3.7 chars/token (technical terms, numbers)
     * - Non-English: ~2.5-3 chars/token (varies by language)
     */
    private static readonly TOKEN_RATIOS;
    /**
     * Estimate token count for a message using content-type aware estimation.
     * More accurate than simple character division.
     */
    estimateTokens(content: string): number;
    private static readonly CONTENT_DETECTION_LIMIT;
    /**
     * Detect the content type for more accurate token estimation
     */
    private detectContentType;
    /**
     * Detect if content is JSON or structured data
     */
    private detectJsonContent;
    /**
     * Detect if content contains markdown formatting
     */
    private detectMarkdownContent;
    /**
     * Detect if content is technical documentation
     */
    private detectTechnicalContent;
    /**
     * Detect if content contains code
     * Note: Content is already limited by detectContentType (CONTENT_DETECTION_LIMIT)
     * Regex patterns are optimized to prevent ReDoS (catastrophic backtracking)
     */
    private detectCodeContent;
    /**
     * Calculate total token count for messages
     */
    calculateTotalTokens(messages: ContextMessage[]): number;
    /**
     * Analyze context for insights
     */
    analyzeContext(messages: ContextMessage[]): ContextAnalysis;
    /**
     * Compress conversation history
     */
    compressConversation(messages: ContextMessage[]): Promise<CompressionResult>;
    /**
     * Check if compression is needed
     */
    shouldCompress(messages: ContextMessage[]): boolean;
    /**
     * Update compression options
     */
    updateOptions(options: Partial<ContextCompressorOptions>): void;
    /**
     * Get current options
     */
    getOptions(): ContextCompressorOptions;
}

/**
 * Callback type for compression events
 * This allows Memory module to be notified when context compression occurs
 */
type CompressionCallback = (info: {
    originalMessageCount: number;
    compressedMessageCount: number;
    messagesRemoved: number;
    tokensReduced: number;
    strategy: string;
}) => void | Promise<void>;
/**
 * Callback type for context clear events
 * This allows Memory module to be notified when context is cleared
 */
type ContextClearCallback = () => void | Promise<void>;
declare class ContextManager implements ContextManager$1 {
    private messages;
    private compressor;
    private storage;
    private logger;
    private maxTokens;
    private autoCompress;
    private model;
    private agentId;
    private isDirty;
    private isCompressing;
    private pendingOperations;
    private operationLock;
    private onCompressionCallback;
    private onClearCallback;
    constructor(options?: ContextCompressorOptions & {
        autoCompress?: boolean;
    });
    /**
     * Register a callback for compression events
     * This allows the Agent to notify Memory when context compression occurs
     */
    onCompression(callback: CompressionCallback): void;
    /**
     * Register a callback for context clear events
     * This allows the Agent to sync Memory when context is cleared
     */
    onContextClear(callback: ContextClearCallback): void;
    /**
     * Notify registered callback about compression events
     */
    private notifyCompression;
    /**
     * Initialize storage and load context for a specific agent
     */
    initializeForAgent(agentId: string): Promise<void>;
    /**
     * Save current context to storage
     */
    saveToStorage(): Promise<void>;
    private lockQueue;
    /**
     * Acquire operation lock with timeout (proper mutex, no spin-wait)
     * Includes deadlock prevention via timeouts
     */
    private acquireLock;
    /**
     * Release operation lock and wake up next waiter
     */
    private releaseLock;
    /**
     * Add a message to the context
     */
    addMessage(message: ContextMessage): Promise<void>;
    /**
     * Get all messages
     */
    getMessages(): ContextMessage[];
    /**
     * Get context window information
     */
    getContextWindow(): ContextWindow;
    /**
     * Analyze the current context
     */
    analyzeContext(): ContextAnalysis;
    /**
     * Compress the context
     */
    compressContext(): Promise<CompressionResult>;
    private compressionWaiters;
    /**
     * Wait for ongoing compression to complete (promise-based, no spin-wait)
     * @param timeoutMs - Maximum time to wait
     * @returns true if compression completed, false if timed out
     */
    private waitForCompressionComplete;
    /**
     * Notify all compression waiters that compression is complete
     */
    private notifyCompressionWaiters;
    /**
     * Clear all context
     * @param options - Optional settings for clearing context
     * @param options.syncWithMemory - If true (default), notifies Memory to also clear. Set to false to clear only Context.
     */
    clearContext(options?: {
        syncWithMemory?: boolean;
    }): Promise<void>;
    /**
     * Cleanup resources and reset pending operations
     * Call this when the context manager is no longer needed
     */
    dispose(): Promise<void>;
    /**
     * Check if compression is needed
     */
    shouldCompress(): boolean;
    /**
     * Export context as JSON string
     */
    exportContext(): string;
    /**
     * Import context from JSON string
     */
    importContext(data: string): void;
    /**
     * Generate a summary of the current context
     */
    generateSummary(): Promise<ContextSummary>;
    /**
     * Get recent messages
     */
    getRecentMessages(count: number): ContextMessage[];
    /**
     * Find messages by role
     */
    getMessagesByRole(role: 'user' | 'assistant' | 'system'): ContextMessage[];
    /**
     * Update a message in context by memory ID
     * Used for synchronizing with Memory module updates
     */
    updateMessageByMemoryId(memoryId: string, updates: {
        content?: string;
        metadata?: MetadataObject;
    }): boolean;
    /**
     * Remove a message from context by memory ID
     * Used for synchronizing with Memory module deletions
     */
    removeMessageByMemoryId(memoryId: string): boolean;
    /**
     * Search context messages
     * Provides filtering by graphId, taskId, sessionId and text content
     */
    searchContext(options: {
        query?: string;
        graphId?: string;
        taskId?: string;
        sessionId?: string;
        role?: 'user' | 'assistant' | 'system';
        limit?: number;
    }): ContextMessage[];
    /**
     * Update the model used for context operations
     */
    updateModel(model: string): void;
    /**
     * Load conversation history from memory module
     * @returns true if loading was successful, false otherwise
     */
    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>;
    /**
     * Save current context messages to memory
     * @returns true if saving was successful, false otherwise
     */
    saveToMemory(memoryModule: {
        addMemory: (content: string, metadata?: MetadataObject, context?: {
            graphId?: string;
            taskId?: string;
            sessionId?: string;
        }) => Promise<{
            id: string;
            content: string;
        }>;
    }): Promise<boolean>;
    /**
     * Update compressor options
     */
    updateCompressorOptions(options: Partial<ContextCompressorOptions>): void;
}

export { type AddAgentNodeOptions, type AddTaskNodeOptions, Agent, type AgentConfig, type AskOptions, type CompressionResult, ContextManager as Context, type ContextAnalysis, ContextCompressor, type ContextCompressorOptions, ContextManager, type ContextMessage, type ContextSummary, type ContextWindow, type DatabaseConfig, type DelegationStrategy, Graph, type GraphConfig, type GraphEdge, type GraphExecutionResult, type GraphNode, type Graph$1 as GraphType, Knowledge, type KnowledgeConfig, type LLMProvider, type LLMRequestOptions, type LLMResponse, type LLMUsage, type LogLevel, type Logger$1 as Logger, type LoggerConfig, type MCPServerConfig, type MCPServerDefinition, type MCPTool, type MCPToolCall, type MCPToolResult, Memory, type MemorySearchOptions, type Memory$1 as MemoryType, type MetadataObject, Plugin, type PluginConfig, type Plugin$1 as PluginDefinition, type Schedule, type ScheduleOptions, type ScheduledItem, type SchedulerConfig, SubAgent, type SubAgentCoordinationResult, type SubAgentResult, type SubAgentTask, Task, type TaskRequest, type TaskResponse, type TaskSearchOptions, type TaskStatus, type Task$1 as TaskType, type ToolCall$1 as ToolCall, type ToolCallResult, type ToolContext, type ToolDefinition, type ToolResult, clearLLMInstances, Agent as default, getDatabase, getLLM, getLogger, getMCP, getPlugin, initializeLogger, knowledgeSearchTool, knowledgeTools, parseScheduleString, resetLogger, shutdownLogger };
