import { EventEmitter } from "events";
import { ChatEntry, StreamingChunk } from "./types.js";
import { Agent } from "../types/agent.js";
import { CodeBuddyMessage, CodeBuddyToolCall } from "../codebuddy/client.js";
import { ToolResult } from "../types/index.js";
import type { TokenCounter } from "../utils/token-counter.js";
import type { ContextManagerV2, ContextMemoryMetrics } from "../context/context-manager-v2.js";
import type { CheckpointManager } from "../checkpoints/checkpoint-manager.js";
import type { SessionStore } from "../persistence/session-store.js";
import { AgentModeManager, AgentMode } from "./agent-mode.js";
import type { SandboxManager } from "../security/sandbox.js";
import type { MCPClient } from "../mcp/mcp-client.js";
import type { CostTracker } from "../utils/cost-tracker.js";
import type { PromptCacheManager } from "../optimization/prompt-cache.js";
import type { HooksManager } from "../hooks/lifecycle-hooks.js";
import { ModelRouter, RoutingDecision } from "../optimization/model-routing.js";
import type { PluginMarketplace } from "../plugins/marketplace.js";
import { EnhancedMemory, type MemoryEntry, type MemoryType } from "../memory/index.js";
import type { RepairCoordinator } from "./execution/repair-coordinator.js";
import { AgentContextFacade, type ContextConfig } from "./facades/agent-context-facade.js";
import { SessionFacade, type RewindResult } from "./facades/session-facade.js";
import { ModelRoutingFacade, type ModelRoutingStats } from "./facades/model-routing-facade.js";
import { InfrastructureFacade } from "./facades/infrastructure-facade.js";
import { MessageHistoryManager, type HistoryStats } from "./facades/message-history-manager.js";
/**
 * Comprehensive memory metrics for the agent
 */
export interface AgentMemoryMetrics {
    /** Chat history size */
    chatHistorySize: number;
    /** LLM messages size */
    messagesSize: number;
    /** Maximum chat history allowed */
    maxHistory: number;
    /** Maximum LLM messages allowed */
    maxMessages: number;
    /** Context manager metrics (if available) */
    contextMetrics?: ContextMemoryMetrics;
    /** Estimated memory usage in bytes (rough estimate) */
    estimatedMemoryBytes: number;
    /** Large tool results currently cached */
    cachedToolResults: number;
    /** Whether garbage collection has been triggered this session */
    gcTriggered: boolean;
}
/**
 * Abstract base class for all agents in the CodeBuddy system.
 *
 * This class acts as a lightweight orchestrator that delegates to specialized facades:
 * - AgentContextFacade: Context and memory management
 * - SessionFacade: Session persistence and checkpoints
 * - ModelRoutingFacade: Model routing and cost tracking
 * - InfrastructureFacade: MCP, sandbox, hooks, plugins
 * - MessageHistoryManager: Chat history operations
 *
 * Concrete implementations (like `CodeBuddyAgent`) must implement:
 * - `processUserMessage`: For single-turn interactions
 * - `processUserMessageStream`: For streaming interactions
 * - `executeTool`: For handling tool calls
 */
export declare abstract class BaseAgent extends EventEmitter implements Agent {
    /**
     * Maximum number of chat history entries to keep in memory.
     * @deprecated Use MessageHistoryManager config instead
     */
    protected static readonly MAX_HISTORY_SIZE = 1000;
    /**
     * Maximum number of LLM messages to keep in memory.
     * @deprecated Use MessageHistoryManager config instead
     */
    protected static readonly MAX_MESSAGES_SIZE = 500;
    /** Threshold for considering a tool result "large" (in characters) */
    protected static readonly LARGE_RESULT_THRESHOLD = 5000;
    /** Context and memory management facade */
    protected contextFacade: AgentContextFacade;
    /** Session and checkpoint management facade */
    protected sessionFacade: SessionFacade;
    /** Model routing and cost management facade */
    protected routingFacade: ModelRoutingFacade;
    /** Infrastructure services facade */
    protected infrastructureFacade: InfrastructureFacade;
    /** Message history manager */
    protected historyManager: MessageHistoryManager;
    /**
     * @deprecated Use historyManager.getChatHistoryRef() instead
     */
    protected get chatHistory(): ChatEntry[];
    protected set chatHistory(value: ChatEntry[]);
    /**
     * @deprecated Use historyManager.getMessagesRef() instead
     */
    protected get messages(): CodeBuddyMessage[];
    protected set messages(value: CodeBuddyMessage[]);
    /** Controller for aborting ongoing operations */
    protected abortController: AbortController | null;
    /** Whether garbage collection has been explicitly triggered this session */
    protected gcTriggered: boolean;
    protected tokenCounter: TokenCounter;
    protected contextManager: ContextManagerV2;
    protected checkpointManager: CheckpointManager;
    protected sessionStore: SessionStore;
    protected modeManager: AgentModeManager;
    protected sandboxManager: SandboxManager;
    protected mcpClient: MCPClient;
    protected costTracker: CostTracker;
    protected promptCacheManager: PromptCacheManager;
    protected hooksManager: HooksManager;
    protected modelRouter: ModelRouter;
    protected marketplace: PluginMarketplace;
    protected repairCoordinator: RepairCoordinator;
    /** Maximum number of tool rounds allowed per user request */
    protected maxToolRounds: number;
    /** Whether "YOLO mode" (fully autonomous) is enabled */
    protected yoloMode: boolean;
    /** Whether to use RAG for selecting relevant tools */
    protected useRAGToolSelection: boolean;
    /** Whether to execute independent tool calls in parallel */
    protected parallelToolExecution: boolean;
    /** Cost limit for the current session in USD */
    protected sessionCostLimit: number;
    /** Current accumulated cost of the session in USD */
    protected sessionCost: number;
    /** Whether to use model routing optimization */
    protected useModelRouting: boolean;
    /** Result of the last model routing decision */
    protected lastRoutingDecision: RoutingDecision | null;
    /** Whether memory system is enabled */
    protected memoryEnabled: boolean;
    /** Memory system instance (lazy-loaded) */
    protected _memory: EnhancedMemory | null;
    /**
     * Lazy-loaded memory system for cross-session context persistence
     */
    protected get memory(): EnhancedMemory;
    constructor();
    /**
     * Initialize all facades after managers are set up.
     * Should be called by subclass constructors after setting up managers.
     */
    protected initializeFacades(): void;
    /**
     * Process a user message and return the response entries.
     */
    abstract processUserMessage(message: string): Promise<ChatEntry[]>;
    /**
     * Process a user message with streaming response.
     */
    abstract processUserMessageStream(message: string): AsyncGenerator<StreamingChunk, void, unknown>;
    /**
     * Execute a single tool call requested by the LLM.
     */
    protected abstract executeTool(toolCall: CodeBuddyToolCall): Promise<ToolResult>;
    getChatHistory(): ChatEntry[];
    clearChat(): void;
    abortCurrentOperation(): void;
    dispose(): void;
    getMode(): AgentMode;
    setMode(mode: AgentMode): void;
    getModeStatus(): string;
    isToolAllowedInCurrentMode(toolName: string): boolean;
    isYoloModeEnabled(): boolean;
    getSessionCost(): number;
    getSessionCostLimit(): number;
    setSessionCostLimit(limit: number): void;
    isSessionCostLimitReached(): boolean;
    createCheckpoint(description: string): void;
    rewindToLastCheckpoint(): RewindResult;
    getCheckpointList(): string;
    getCheckpointManager(): CheckpointManager;
    getSessionStore(): SessionStore;
    saveCurrentSession(): Promise<void>;
    getSessionList(): Promise<string>;
    exportCurrentSession(outputPath?: string): Promise<string | null>;
    getSandboxStatus(): string;
    validateCommand(command: string): {
        valid: boolean;
        reason?: string;
    };
    connectMCPServers(): Promise<void>;
    getMCPStatus(): string;
    getMCPTools(): Promise<Map<string, unknown[]>>;
    getMCPClient(): MCPClient;
    protected initializeMCP(): void;
    getContextStats(): import("./facades/agent-context-facade.js").ContextStats;
    formatContextStats(): string;
    updateContextConfig(config: ContextConfig): void;
    getPromptCacheManager(): PromptCacheManager;
    getPromptCacheStats(): import("./facades/infrastructure-facade.js").PromptCacheStats;
    formatPromptCacheStats(): string;
    getHooksManager(): HooksManager;
    getHooksStatus(): string;
    setModelRouting(enabled: boolean): void;
    isModelRoutingEnabled(): boolean;
    getModelRouter(): ModelRouter;
    getLastRoutingDecision(): RoutingDecision | null;
    getModelRoutingStats(): ModelRoutingStats;
    formatModelRoutingStats(): string;
    remember(type: MemoryType, content: string, options?: {
        summary?: string;
        importance?: number;
        tags?: string[];
        metadata?: Record<string, unknown>;
    }): Promise<MemoryEntry>;
    recall(query?: string, options?: {
        types?: MemoryType[];
        tags?: string[];
        limit?: number;
        minImportance?: number;
    }): Promise<MemoryEntry[]>;
    getMemoryContext(query?: string): Promise<string>;
    storeConversationSummary(summary: string, topics: string[], decisions?: string[]): Promise<void>;
    setMemoryEnabled(enabled: boolean): void;
    isMemoryEnabled(): boolean;
    getMemoryStats(): {
        totalMemories: number;
        byType: Record<string, number>;
        projects: number;
        summaries: number;
    } | null;
    formatMemoryStatus(): string;
    /**
     * @deprecated Trimming is now automatic via MessageHistoryManager
     */
    protected trimHistory(_maxHistorySize?: number, _maxMessagesSize?: number): void;
    /**
     * Get current history statistics for debugging
     */
    getHistoryStats(): HistoryStats;
    /**
     * Get comprehensive memory metrics for monitoring and debugging.
     * Includes history sizes, context manager metrics, and estimated memory usage.
     */
    getAgentMemoryMetrics(): AgentMemoryMetrics;
    /**
     * Format memory metrics as a human-readable string.
     * Useful for /memory or /debug commands.
     */
    formatMemoryMetrics(): string;
    /**
     * Force garbage collection and cleanup of agent memory.
     * Should be called during long sessions or when memory pressure is detected.
     *
     * @returns Object with cleanup statistics
     */
    forceMemoryCleanup(): {
        entriesTrimmed: number;
        messagesTrimmed: number;
        contextCleanup?: {
            summariesRemoved: number;
            tokensFreed: number;
        };
    };
    /**
     * Check if memory usage is high and cleanup should be triggered.
     * Returns true if memory pressure is detected.
     */
    isMemoryPressureHigh(): boolean;
}
