/**
 * Advanced Context Manager for LLM conversations (Primary)
 *
 * This is the main context manager used by all agents (CodeBuddyAgent, BaseAgent).
 * For the server API routes, see context-manager-v3.ts.
 *
 * Implements multiple strategies based on research:
 * - Recurrent Context Compression (arxiv:2406.06110)
 * - Recursive Summarization (arxiv:2308.15022)
 * - Sliding Window Attention with Overlap
 * - Event-centric Memory (LoCoMo)
 * - Content-type-aware Compression
 * - Key Information Preservation
 */
import { CodeBuddyMessage } from '../codebuddy/client.js';
import { EnhancedCompressionConfig } from './enhanced-compression.js';
import type { KeyInformation, ContextArchive, CompressionMetrics, EnhancedCompressionResult } from './types.js';
export interface ContextManagerConfig {
    /** Maximum tokens for the context window */
    maxContextTokens: number;
    /** Reserve tokens for model response */
    responseReserveTokens: number;
    /** Number of recent messages to always keep */
    recentMessagesCount: number;
    /** Enable automatic summarization */
    enableSummarization: boolean;
    /** Compression ratio target (e.g., 4 = compress to 1/4) */
    compressionRatio: number;
    /** Model name for token counting */
    model: string;
    /** Auto-compact threshold in tokens (like mistral-vibe's 200K) */
    autoCompactThreshold: number;
    /** Warning thresholds as percentages (e.g., [50, 75, 90]) */
    warningThresholds: number[];
    /** Enable context warnings */
    enableWarnings: boolean;
    /** Enable enhanced compression with key info preservation */
    enableEnhancedCompression: boolean;
    /** Configuration for enhanced compression */
    enhancedCompressionConfig?: Partial<EnhancedCompressionConfig>;
}
export interface ContextStats {
    totalTokens: number;
    maxTokens: number;
    usagePercent: number;
    messageCount: number;
    summarizedSessions: number;
    isNearLimit: boolean;
    isCritical: boolean;
}
/**
 * Memory metrics for monitoring context manager health
 */
export interface ContextMemoryMetrics {
    /** Current number of stored summaries */
    summaryCount: number;
    /** Total tokens in summaries */
    summaryTokens: number;
    /** Peak message count seen this session */
    peakMessageCount: number;
    /** Number of compression operations performed */
    compressionCount: number;
    /** Total tokens saved by compression */
    totalTokensSaved: number;
    /** Last compression timestamp */
    lastCompressionTime: Date | null;
    /** Number of warning thresholds triggered */
    warningsTriggered: number;
}
/**
 * Advanced Context Manager with multiple compression strategies
 */
export declare class ContextManagerV2 {
    private config;
    private tokenCounter;
    private summaries;
    private systemMessage;
    /** Track which warning thresholds have been triggered (to avoid duplicate warnings) */
    private triggeredWarnings;
    /** Last token count for auto-compact tracking */
    private lastTokenCount;
    /** Enhanced compressor for advanced compression strategies */
    private enhancedCompressor;
    /** Last enhanced compression result */
    private lastEnhancedResult;
    /** Session ID for archiving */
    private sessionId;
    /** Maximum number of summaries to keep (prevents unbounded growth) */
    private static readonly MAX_SUMMARIES;
    /** Peak message count seen this session */
    private peakMessageCount;
    /** Number of compression operations performed */
    private compressionCount;
    /** Total tokens saved by compression */
    private totalTokensSaved;
    /** Last compression timestamp */
    private lastCompressionTime;
    static readonly DEFAULT_CONFIG: ContextManagerConfig;
    constructor(config?: Partial<ContextManagerConfig>);
    /**
     * Get the effective token limit (accounting for response reserve + estimation safety margin)
     * The 5% safety margin compensates for token counting estimation drift.
     */
    get effectiveLimit(): number;
    /**
     * Count tokens in messages
     */
    countTokens(messages: CodeBuddyMessage[]): number;
    /**
     * Get context statistics
     */
    getStats(messages: CodeBuddyMessage[]): ContextStats;
    /**
     * Prepare messages for API call, managing context as needed
     * Returns optimized message array that fits within token limits
     *
     * Implements auto-compact like mistral-vibe's AutoCompactMiddleware
     * Now supports enhanced compression with key info preservation
     */
    prepareMessages(messages: CodeBuddyMessage[]): CodeBuddyMessage[];
    /**
     * Prepare messages using enhanced compression with key info preservation
     */
    private prepareMessagesEnhanced;
    /**
     * Legacy compression (original implementation)
     */
    private prepareMessagesLegacy;
    /**
     * Apply compression strategies in order of priority
     */
    private applyStrategies;
    /**
     * Strategy 1: Sliding Window - Keep N most recent messages
     */
    private applySlidingWindow;
    /**
     * Strategy 2: Truncate verbose tool results
     */
    private truncateToolResults;
    /**
     * Strategy 3: Summarize older messages
     * Based on Recursive Summarization (arxiv:2308.15022)
     */
    private applySummarization;
    /**
     * Create a condensed summary of messages
     * This is a simple extractive summary - for production, use LLM-based summarization
     */
    private createSummary;
    /**
     * Strategy 4: Hard truncation as last resort
     */
    private hardTruncate;
    /**
     * Check if context is approaching limits and emit warning
     * Implements multi-threshold warnings with deduplication (like mistral-vibe's ContextWarningMiddleware)
     */
    shouldWarn(messages: CodeBuddyMessage[]): {
        warn: boolean;
        message: string;
        threshold?: number;
    };
    /**
     * Check if auto-compact should be triggered
     * Returns true if token count exceeds autoCompactThreshold
     */
    shouldAutoCompact(messages: CodeBuddyMessage[]): boolean;
    /**
     * Reset warning triggers (call when starting new conversation)
     */
    resetWarnings(): void;
    /**
     * Update configuration
     */
    updateConfig(config: Partial<ContextManagerConfig>): void;
    /**
     * Get current configuration
     */
    getConfig(): ContextManagerConfig;
    /**
     * Clean up resources
     */
    dispose(): void;
    /**
     * Get last token count (useful for tracking auto-compact effectiveness)
     */
    getLastTokenCount(): number;
    /**
     * Get memory metrics for monitoring context manager health
     * Useful for detecting potential memory leaks and understanding compression behavior
     */
    getMemoryMetrics(): ContextMemoryMetrics;
    /**
     * Format memory metrics as a human-readable string
     */
    formatMemoryMetrics(): string;
    /**
     * Force cleanup of old summaries and reset metrics
     * Call this to reclaim memory during long sessions
     */
    forceCleanup(): {
        summariesRemoved: number;
        tokensFreed: number;
    };
    /**
     * Check memory pressure and cleanup if needed
     * Returns true if cleanup was performed
     */
    checkMemoryPressure(): Promise<boolean>;
    /**
     * Get combined health metrics including memory
     */
    getHealthMetrics(): Promise<{
        context: ContextMemoryMetrics;
        memory?: {
            heapUsed: number;
            heapTotal: number;
            pressure: 'low' | 'medium' | 'high' | 'critical';
        };
    }>;
    /**
     * Get the last enhanced compression result (if available)
     * Contains detailed metrics and preserved key information
     */
    getLastCompressionResult(): EnhancedCompressionResult | null;
    /**
     * Get the last compression metrics
     */
    getLastCompressionMetrics(): CompressionMetrics | null;
    /**
     * Get key information preserved from the last compression
     */
    getPreservedKeyInfo(): KeyInformation | null;
    /**
     * Recover full context from an archive
     *
     * @param archiveId - Optional archive ID, or undefined for most recent
     * @returns The full context messages, or undefined if not available
     */
    recoverFullContext(archiveId?: string): CodeBuddyMessage[] | undefined;
    /**
     * List available context archives
     */
    listContextArchives(): Array<{
        id: string;
        timestamp: Date;
        messageCount: number;
        tokenCount: number;
    }>;
    /**
     * Get enhanced compression configuration
     */
    getEnhancedCompressionConfig(): Partial<EnhancedCompressionConfig> | null;
    /**
     * Update enhanced compression configuration
     */
    updateEnhancedCompressionConfig(config: Partial<EnhancedCompressionConfig>): void;
    /**
     * Enable or disable enhanced compression
     */
    setEnhancedCompressionEnabled(enabled: boolean): void;
    /**
     * Get detailed compression statistics
     */
    getCompressionStats(): {
        totalCompressions: number;
        totalTokensSaved: number;
        averageCompressionRatio: number;
        lastCompression: Date | null;
        archivesAvailable: number;
        lastStrategiesUsed: string[];
    };
    /**
     * Format compression statistics as human-readable string
     */
    formatCompressionStats(): string;
}
export type { KeyInformation, ContextArchive, CompressionMetrics, EnhancedCompressionResult, };
/**
 * Create a context manager with auto-detection of model limits
 */
export declare function createContextManager(model: string, maxTokens?: number): ContextManagerV2;
export declare function getContextManager(): ContextManagerV2;
