import { c as ChatMessage } from '../types-ajANVzf7.js';
import '../agent-CW9XbmG_.js';
import 'zod';
import '../errors-C-so0M4t.js';
import '../types-BxggH0Yh.js';
import '../errors-CmVvczxZ.js';

/**
 * @witqq/agent-sdk/chat/context
 *
 * Context window manager for selecting which messages fit within a token budget.
 * Stateless: takes messages in, returns trimmed messages out.
 * Three overflow strategies: truncate-oldest, sliding-window, summarize-placeholder.
 */

/**
 * Options for token estimation.
 */
interface TokenEstimationOptions {
    /**
     * Characters per token ratio.
     * Lower = more conservative (fewer messages fit).
     * @default 4
     */
    charsPerToken?: number;
}
/**
 * Estimate token count for a single chat message.
 * Uses character-based heuristic: `Math.ceil(charCount / charsPerToken)`.
 *
 * Counts:
 * - Text content (string or text parts)
 * - Serialized tool calls and tool results
 * - Thinking blocks
 * - Role overhead (~4 tokens)
 *
 * @param message - Chat message to estimate
 * @param options - Estimation options
 * @returns Estimated token count
 *
 * @example
 * ```typescript
 * const tokens = estimateTokens(message);
 * const conservative = estimateTokens(message, { charsPerToken: 3 });
 * ```
 */
declare function estimateTokens(message: ChatMessage, options?: TokenEstimationOptions): number;
/** Overflow strategy type */
type OverflowStrategy = "truncate-oldest" | "sliding-window" | "summarize-placeholder";
/**
 * Async summarizer function for the summarize-placeholder strategy.
 * Receives removed messages and returns a summary string.
 * When configured, replaces the static placeholder text with actual summary.
 */
type ContextSummarizer = (removedMessages: readonly ChatMessage[]) => Promise<string>;
/**
 * Configuration for the context window manager.
 */
interface ContextWindowConfig {
    /** Maximum token budget for the context window */
    maxTokens: number;
    /**
     * Tokens reserved for system prompt and response generation.
     * Subtracted from maxTokens to get available budget.
     * @default 0
     */
    reservedTokens?: number;
    /**
     * Strategy for handling overflow when messages exceed budget.
     * @default "truncate-oldest"
     */
    strategy?: OverflowStrategy;
    /**
     * Token estimation options.
     */
    estimation?: TokenEstimationOptions;
    /**
     * Optional async summarizer for the summarize-placeholder strategy.
     * When provided, replaces the static placeholder with a generated summary.
     * Falls back to static placeholder if summarizer throws.
     */
    summarizer?: ContextSummarizer;
}
/**
 * Result of context window trimming.
 */
interface ContextWindowResult {
    /** Messages that fit within the budget */
    messages: ChatMessage[];
    /** Total estimated tokens for included messages */
    totalTokens: number;
    /** Number of messages removed */
    removedCount: number;
    /** Whether any messages were truncated */
    wasTruncated: boolean;
}
/**
 * Context usage statistics for a session.
 * Returned by `IChatRuntime.getContextStats()`.
 *
 * When real usage data is available (after the first API response),
 * `realPromptTokens` and `realCompletionTokens` contain actual token counts.
 * `modelContextWindow` is the model's context window from `listModels()`.
 */
interface ContextStats {
    /** Estimated total tokens in the trimmed context (heuristic, kept for backward compat) */
    totalTokens: number;
    /** Number of messages removed by trimming */
    removedCount: number;
    /** Whether context was truncated */
    wasTruncated: boolean;
    /** Available token budget (maxTokens − reservedTokens) */
    availableBudget: number;
    /** Real prompt tokens from the last API response (undefined before first response) */
    realPromptTokens?: number;
    /** Real completion tokens from the last API response (undefined before first response) */
    realCompletionTokens?: number;
    /** Model's context window in tokens from listModels() (undefined if not available) */
    modelContextWindow?: number;
}
/**
 * Stateless context window manager.
 * Takes messages and returns the subset that fits within a token budget.
 *
 * @example
 * ```typescript
 * const manager = new ContextWindowManager({
 *   maxTokens: 4096,
 *   reservedTokens: 500,
 *   strategy: "sliding-window",
 * });
 *
 * const result = manager.fitMessages(messages);
 * // result.messages — trimmed to fit budget
 * // result.totalTokens — estimated token usage
 * // result.wasTruncated — whether messages were removed
 * ```
 */
declare class ContextWindowManager {
    private readonly config;
    constructor(config: ContextWindowConfig);
    /** Available token budget after reserving tokens */
    get availableBudget(): number;
    /**
     * Estimate tokens for a single message.
     * @param message - Message to estimate
     * @returns Estimated token count
     */
    estimateMessageTokens(message: ChatMessage): number;
    /**
     * Fit messages within the token budget using the configured strategy.
     * @param messages - All messages to consider
     * @returns Result with fitted messages and metadata
     */
    fitMessages(messages: readonly ChatMessage[]): ContextWindowResult;
    /**
     * Async variant of fitMessages that supports async summarization.
     * When strategy is "summarize-placeholder" and a summarizer is configured,
     * calls the summarizer with removed messages and replaces the placeholder text.
     * Falls back to static placeholder if summarizer throws.
     * For other strategies, behaves identically to fitMessages().
     */
    fitMessagesAsync(messages: readonly ChatMessage[]): Promise<ContextWindowResult>;
    /**
     * Trim messages using real token usage data from the previous API call.
     * Uses average-based algorithm: `avgTokensPerMessage = lastPromptTokens / messageCount`.
     * Removes oldest non-system messages until freed budget brings usage under modelContextWindow.
     *
     * @param messages - All messages in the session
     * @param lastPromptTokens - Real prompt tokens from the last API response
     * @param modelContextWindow - Model's total context window size in tokens
     * @returns Result with fitted messages and metadata
     */
    fitMessagesWithUsage(messages: readonly ChatMessage[], lastPromptTokens: number, modelContextWindow: number): ContextWindowResult;
    /**
     * Truncate oldest: keeps system messages, removes oldest non-system messages first.
     * Always keeps the most recent user message.
     */
    private truncateOldest;
    /**
     * Sliding window: keeps the most recent messages that fit within budget.
     */
    private slidingWindow;
    /**
     * Summarize placeholder: replaces truncated messages with a placeholder,
     * preserving system messages and recent context.
     */
    private summarizePlaceholder;
}

export { type ContextStats, type ContextSummarizer, type ContextWindowConfig, ContextWindowManager, type ContextWindowResult, type OverflowStrategy, type TokenEstimationOptions, estimateTokens };
