import { CodeBuddyToolCall } from '../codebuddy/client.js';
import { StreamEvent, ChunkProcessorOptions } from './types.js';
interface ChatDelta {
    choices?: Array<{
        delta?: {
            content?: string | null;
            tool_calls?: Array<{
                index: number;
                id?: string;
                function?: {
                    name?: string;
                    arguments?: string;
                };
            }>;
        };
    }>;
}
/**
 * Chunk timeout error for per-chunk timeout handling
 */
export declare class ChunkTimeoutError extends Error {
    readonly chunkIndex: number;
    readonly timeoutMs: number;
    constructor(chunkIndex: number, timeoutMs: number);
}
/**
 * Latency metrics for streaming performance analysis
 */
export interface StreamingMetrics {
    /** Total chunks processed */
    chunkCount: number;
    /** Total bytes processed */
    totalBytes: number;
    /** Average chunk processing time in ms */
    avgProcessingTimeMs: number;
    /** Max chunk processing time in ms */
    maxProcessingTimeMs: number;
    /** Min chunk processing time in ms */
    minProcessingTimeMs: number;
    /** Time to first chunk in ms */
    timeToFirstChunkMs: number;
    /** Total processing time in ms */
    totalProcessingTimeMs: number;
    /** Chunks per second throughput */
    chunksPerSecond: number;
    /** Bytes per second throughput */
    bytesPerSecond: number;
    /** Number of batched flushes */
    batchFlushCount: number;
    /** Backpressure events count */
    backpressureEvents: number;
    /** P50 latency (median) in ms */
    p50LatencyMs: number;
    /** P95 latency in ms */
    p95LatencyMs: number;
    /** P99 latency in ms */
    p99LatencyMs: number;
    /** Number of chunk timeouts */
    chunkTimeouts: number;
    /** Jitter (latency variance) in ms */
    jitterMs: number;
    /** Inter-chunk arrival time average in ms */
    avgInterChunkTimeMs: number;
}
/**
 * Extended options for optimized chunk processor
 */
export interface OptimizedChunkProcessorOptions extends ChunkProcessorOptions {
    /** Enable batch processing for small chunks (default: true) */
    enableBatching?: boolean;
    /** Batch size threshold in bytes before auto-flush (default: 64) */
    batchSizeThreshold?: number;
    /** Batch time threshold in ms before auto-flush (default: 16 ~60fps) */
    batchTimeThresholdMs?: number;
    /** Enable backpressure handling (default: true) */
    enableBackpressure?: boolean;
    /** Max pending events before applying backpressure (default: 100) */
    maxPendingEvents?: number;
    /** Throttle render updates in ms (default: 16 ~60fps) */
    renderThrottleMs?: number;
    /** Per-chunk timeout in ms (default: 5000). 0 = no timeout */
    chunkTimeoutMs?: number;
    /** Adaptive throttle based on rendering performance (default: true) */
    adaptiveThrottle?: boolean;
    /** Min render throttle for adaptive mode in ms (default: 8 ~120fps) */
    minRenderThrottleMs?: number;
    /** Max render throttle for adaptive mode in ms (default: 50 ~20fps) */
    maxRenderThrottleMs?: number;
    /** Flow hint callback for consumer feedback */
    onFlowHint?: (hint: FlowHint) => void;
}
/**
 * Flow control hints for consumers
 */
export interface FlowHint {
    /** Current flow state */
    state: 'flowing' | 'slow' | 'backpressured';
    /** Recommended action for consumer */
    action: 'continue' | 'slow_down' | 'pause';
    /** Buffer fill percentage 0-100 */
    bufferFillPercent: number;
    /** Estimated time to drain buffer in ms */
    estimatedDrainTimeMs: number;
}
/**
 * High-performance processor for streaming chunks
 * Optimizations:
 * - Reusable buffers to minimize memory allocations
 * - Batch processing for small chunks
 * - Backpressure handling for flow control
 * - Per-chunk timeout support
 * - Latency metrics with percentiles for performance monitoring
 * - Adaptive render throttling based on consumer performance
 * - Flow hints for consumer feedback
 */
export declare class ChunkProcessor {
    private contentBuffer;
    private rawContentBuffer;
    private accumulatedContent;
    private rawContent;
    private contentDirty;
    private toolCallsMap;
    private pendingBatch;
    private pendingBatchSize;
    private lastBatchFlushTime;
    private batchFlushCount;
    private pendingEvents;
    private isBackpressured;
    private backpressureEvents;
    private lastRenderTime;
    private pendingRenderContent;
    private currentRenderThrottle;
    private renderDurations;
    private startTime;
    private firstChunkTime;
    private processingTimes;
    private interChunkTimes;
    private lastChunkArrivalTime;
    private totalBytes;
    private chunkCount;
    private chunkTimeouts;
    private chunkTimeoutTimer;
    private lastChunkProcessedTime;
    private options;
    constructor(options?: OptimizedChunkProcessorOptions);
    /**
     * Start per-chunk timeout monitoring
     * Call this when waiting for the next chunk
     */
    startChunkTimeout(): void;
    /**
     * Clear the current chunk timeout
     * Call this when a chunk is received
     */
    clearChunkTimeout(): void;
    /**
     * Check if a chunk timeout has occurred
     */
    hasTimedOut(): boolean;
    /**
     * Process a delta chunk and return derived events
     * Optimized for minimal allocations and batch processing
     */
    processDelta(chunk: ChatDelta): StreamEvent[];
    /**
     * Emit a flow hint to the consumer based on current state
     */
    private emitFlowHint;
    /**
     * Get average processing time from recent samples
     */
    private getAverageProcessingTime;
    /**
     * Determine if content should be batched
     * Batching is used for rapid successive small chunks.
     * A chunk is batched if:
     * - It's small enough (< batchSizeThreshold)
     * - AND it arrived quickly after the last chunk (< batchTimeThresholdMs)
     * This ensures isolated chunks emit immediately for responsiveness
     * while rapid streams of small chunks are batched for efficiency
     */
    private shouldBatch;
    /**
     * Add content to pending batch
     */
    private addToBatch;
    /**
     * Check if batch should be flushed
     */
    private shouldFlushBatch;
    /**
     * Flush batched content and return combined string
     */
    private flushBatch;
    /**
     * Force flush any pending batched content
     * Call this at stream end to ensure all content is emitted
     */
    flushPendingBatch(): StreamEvent | null;
    /**
     * Process sanitization with caching for performance
     */
    private processSanitize;
    /**
     * Create a content event (reuses pattern for consistency)
     */
    private createContentEvent;
    /**
     * Process tool call deltas efficiently
     */
    private processToolCalls;
    /**
     * Handle backpressure by queueing events when overwhelmed
     */
    private handleBackpressure;
    /**
     * Drain pending events (call when ready to process more)
     */
    drainPendingEvents(maxCount?: number): StreamEvent[];
    /**
     * Check if backpressure is currently applied
     */
    isUnderBackpressure(): boolean;
    /**
     * Get count of pending events
     */
    getPendingEventCount(): number;
    /**
     * Check if content should be rendered (throttled)
     * Uses adaptive throttling if enabled
     */
    shouldRender(): boolean;
    /**
     * Get throttled content for rendering
     * Accumulates content between renders and returns it when shouldRender() is true
     */
    getThrottledContent(content: string): string | null;
    /**
     * Report render duration for adaptive throttling
     * Call this after rendering to help the processor adjust throttle
     */
    reportRenderDuration(durationMs: number): void;
    /**
     * Adjust adaptive throttle based on recent render durations
     */
    private adjustAdaptiveThrottle;
    /**
     * Get current adaptive render throttle value
     */
    getCurrentRenderThrottle(): number;
    /**
     * Force get any pending render content
     */
    flushRenderContent(): string;
    /**
     * Get all accumulated tool calls (finalized)
     */
    getToolCalls(): CodeBuddyToolCall[];
    /**
     * Get full accumulated content (sanitized)
     * Uses lazy joining for better memory efficiency
     */
    getAccumulatedContent(): string;
    /**
     * Get raw accumulated content
     * Uses lazy joining for better memory efficiency
     */
    getRawContent(): string;
    /**
     * Calculate percentile from sorted array
     */
    private calculatePercentile;
    /**
     * Calculate variance (jitter) from array of times
     */
    private calculateVariance;
    /**
     * Get detailed streaming metrics for performance analysis
     */
    getMetrics(): StreamingMetrics;
    /**
     * Get a summary string of metrics for logging
     */
    getMetricsSummary(): string;
    /**
     * Get a progress indicator object suitable for UI display
     */
    getProgressIndicator(): {
        phase: 'connecting' | 'streaming' | 'completing';
        progress: number;
        bytesReceived: number;
        chunksReceived: number;
        elapsedMs: number;
        estimatedRemainingMs: number;
        latencyTrend: 'improving' | 'stable' | 'degrading';
    };
    /**
     * Reset the processor for a new round
     * Optimized to reuse allocated arrays where possible
     */
    reset(): void;
    /**
     * Partial reset - keeps metrics but clears content
     * Useful for multi-turn conversations
     */
    softReset(): void;
    /**
     * Get the number of chunk timeouts that occurred
     */
    getChunkTimeoutCount(): number;
    /**
     * Update chunk timeout configuration dynamically
     */
    setChunkTimeout(timeoutMs: number): void;
}
export {};
