/** * Context Compaction Policy for PraisonAI TypeScript SDK. * * Python parity with: * - praisonaiagents/context/protocols.py (CompactionRoute, CompactionStrategy, * ContextBudgetResult, ContextCompactionPolicyProtocol, get_default_policy) * - praisonaiagents/context/adapters.py (ContextCompactionPolicyAdapter and the * CONSERVATIVE_POLICY / BALANCED_POLICY / AGGRESSIVE_POLICY presets) * - praisonaiagents/context/policy.py (which aliases the adapter as * `ContextCompactionPolicy` -- the name exported for the class here) * * The policy replaces reactive "context too long" error handling with a * proactive token-budget analysis performed *before* the LLM call. * * Token estimation and model-limit lookups are ports of the offline * heuristics in praisonaiagents/context/tokens.py and context/budgeter.py. * Python additionally consults litellm's `model_cost` registry when litellm is * installed; the TypeScript SDK has no such registry and always uses the * static tables below. */ import type { CompactionRouteType, CompactionStrategyType } from './compaction-types'; export { CompactionRoute, CompactionStrategy } from './compaction-types'; export type { CompactionRouteType, CompactionStrategyType } from './compaction-types'; /** * Coerce a strategy given as a string (any case) or enum value into the enum * value. Mirrors Python's `CompactionStrategy(value.lower())`, which raises * `ValueError` for unknown values. */ export declare function toCompactionStrategy(value: string | CompactionStrategyType): CompactionStrategyType; /** A chat message as passed to the LLM (Python: `Dict[str, Any]`). */ export type ContextMessage = Record; /** A tool schema as passed to the LLM (Python: `Dict[str, Any]`). */ export type ToolSchema = Record; /** Per-model overrides (Python: `Dict[str, Dict[str, Any]]`). */ export type ModelOverrides = Record>; /** * Model context-window sizes. Python parity with `MODEL_LIMITS` in * context/budgeter.py. Insertion order matters for the partial-match * fallback in {@link getModelLimit}, exactly as it does in Python. */ export declare const MODEL_LIMITS: Readonly>; /** * Default output reserves by model family. Python parity with * `OUTPUT_RESERVES` in context/budgeter.py (insertion order matters for the * substring match in {@link getOutputReserve}). */ export declare const OUTPUT_RESERVES: Readonly>; /** * Get the context-window limit for a model. * Python parity with `get_model_limit(model)` in context/budgeter.py (static * table only; the litellm lookup has no TypeScript equivalent). * * @param model - Model name or identifier * @returns Context window size in tokens */ export declare function getModelLimit(model: string): number; /** * Get the recommended output token reserve for a model. * Python parity with `get_output_reserve(model)` in context/budgeter.py. * * @param model - Model name * @returns Output reserve in tokens */ export declare function getOutputReserve(model: string): number; /** * Estimate token count using the character-based heuristic. * Python parity with `estimate_tokens_heuristic(text)` in context/tokens.py. * * @param text - Text to estimate tokens for * @returns Estimated token count (0 for empty text, otherwise at least 1) */ export declare function estimateTokensHeuristic(text: string | null | undefined): number; /** * Estimate tokens for a single chat message. * Python parity with `estimate_message_tokens(message, use_accurate=False)` * in context/tokens.py (heuristic mode only). * * @param message - Message dict with role, content, optional tool_calls, etc. * @returns Estimated token count */ export declare function estimateMessageTokens(message: ContextMessage): number; /** * Estimate total tokens for a list of messages. * Python parity with `estimate_messages_tokens(messages, use_accurate=False)` * in context/tokens.py. * * @param messages - List of message dicts * @returns Total estimated token count */ export declare function estimateMessagesTokens(messages: ContextMessage[] | null | undefined): number; /** * Estimate tokens for tool/function schemas. * Python parity with `estimate_tool_schema_tokens(tools, use_accurate=False)` * in context/tokens.py. * * @param tools - List of tool definitions * @returns Estimated token count */ export declare function estimateToolSchemaTokens(tools: ToolSchema[] | null | undefined): number; /** * Constructor fields for {@link ContextBudgetResult}. Python parity with the * keyword arguments of `ContextBudgetResult.__init__` in context/protocols.py. */ export interface ContextBudgetResultInit { /** Python: `route` */ route: CompactionRouteType; /** Python: `current_tokens` */ currentTokens: number; /** Python: `available_tokens` */ availableTokens: number; /** Python: `utilization` */ utilization: number; /** Python: `needs_action` */ needsAction: boolean; /** Python: `recommended_strategy` */ recommendedStrategy: CompactionStrategyType; /** Python: `details` */ details: Record; } /** * Result of context budget analysis. * Python parity with `ContextBudgetResult` in context/protocols.py. */ export declare class ContextBudgetResult { route: CompactionRouteType; currentTokens: number; availableTokens: number; utilization: number; needsAction: boolean; recommendedStrategy: CompactionStrategyType; details: Record; constructor(init: ContextBudgetResultInit); } /** * Protocol for context compaction policy implementations. * Python parity with `ContextCompactionPolicyProtocol` (a * `@runtime_checkable Protocol`) in context/protocols.py. * * Python's protocol also declares a `from_dict` classmethod; TypeScript * interfaces cannot express statics, so see * {@link ContextCompactionPolicy.fromDict}. */ export interface ContextCompactionPolicyProtocol { /** Python: `trigger_at` -- fraction (0.0-1.0) of the usable window at which to compact. */ triggerAt: number; /** Python: `strategy` */ strategy: CompactionStrategyType | string; /** Python: `preserve_last_n_turns` */ preserveLastNTurns: number; /** Python: `max_compaction_attempts` */ maxCompactionAttempts: number; /** Python: `target_utilization` -- utilization to aim for after compaction. */ targetUtilization: number; /** Python: `aggressive_tool_truncation` */ aggressiveToolTruncation: boolean; /** Python: `model_overrides` */ modelOverrides: ModelOverrides | null; /** * Compute context budget and determine route before LLM call. * Python parity with `compute_context_budget(messages, model="gpt-4o-mini", tools=None, system_prompt=None)`. */ computeContextBudget(messages: ContextMessage[], model?: string, tools?: ToolSchema[] | null, systemPrompt?: string | null): ContextBudgetResult; /** Convert policy to a plain object for serialization. Python: `to_dict()`. */ toDict(): Record; } /** * Runtime check mirroring Python's `isinstance(obj, ContextCompactionPolicyProtocol)` * on the `@runtime_checkable` protocol (structural: attributes + methods present). */ export declare function isContextCompactionPolicy(value: unknown): value is ContextCompactionPolicyProtocol; /** * Constructor options for {@link ContextCompactionPolicy}. Each field mirrors * a dataclass field of `ContextCompactionPolicyAdapter` in * context/adapters.py with the same default. */ export interface ContextCompactionPolicyConfig { /** Python: `trigger_at: float = 0.90` -- when to trigger compaction (0.0-1.0 fraction of context window). */ triggerAt?: number; /** Python: `strategy: Union[str, CompactionStrategy] = CompactionStrategy.DROP_OLDEST_TOOLS`. */ strategy?: CompactionStrategyType | string; /** Python: `preserve_last_n_turns: int = 5` -- always preserve the most recent N conversation turns. */ preserveLastNTurns?: number; /** Python: `max_compaction_attempts: int = 2` -- maximum compaction attempts before giving up. */ maxCompactionAttempts?: number; /** Python: `target_utilization: float = 0.70` -- target utilization after compaction (0.0-1.0). */ targetUtilization?: number; /** Python: `aggressive_tool_truncation: bool = True` -- whether to be aggressive about tool output truncation. */ aggressiveToolTruncation?: boolean; /** Python: `model_overrides: Optional[Dict[str, Dict[str, Any]]] = None` -- model-specific overrides. */ modelOverrides?: ModelOverrides | null; } /** * Concrete context compaction policy. * * Python parity with `ContextCompactionPolicyAdapter` in context/adapters.py, * re-exported by context/policy.py as `ContextCompactionPolicy`. * * Provides intelligent policy decisions for proactive context management, * replacing reactive string-matching with proactive token budget analysis. * * @example * ```ts * const policy = new ContextCompactionPolicy({ triggerAt: 0.85 }); * const result = policy.computeContextBudget(messages, 'gpt-4o-mini'); * if (result.needsAction) { ... } * ``` */ export declare class ContextCompactionPolicy implements ContextCompactionPolicyProtocol { triggerAt: number; strategy: CompactionStrategyType; preserveLastNTurns: number; maxCompactionAttempts: number; targetUtilization: number; aggressiveToolTruncation: boolean; modelOverrides: ModelOverrides | null; constructor(config?: ContextCompactionPolicyConfig); /** * Compute context budget and determine route before LLM call. * * Python parity with `ContextCompactionPolicyAdapter.compute_context_budget` * in context/adapters.py. Replaces reactive error handling with proactive * analysis. * * @param messages - Current conversation history * @param model - Model name for context window lookup (Python default: "gpt-4o-mini") * @param tools - Tool schemas (if any) (Python default: None) * @param systemPrompt - System prompt content (Python default: None) * @returns ContextBudgetResult with routing decision */ computeContextBudget(messages: ContextMessage[], model?: string, tools?: ToolSchema[] | null, systemPrompt?: string | null): ContextBudgetResult; /** * Check if messages contain large tool outputs that could be truncated. * Python parity with `_has_large_tool_outputs`. */ protected hasLargeToolOutputs(messages: ContextMessage[]): boolean; /** Model context window (Python: `get_model_limit(model)`). */ protected resolveModelLimit(model: string): number; /** Usable tokens after output reserve (Python: `ContextBudgeter(model, model_limit).usable`). */ protected resolveUsableTokens(model: string, modelLimit: number): number; /** Python: `estimate_messages_tokens(messages, use_accurate=False)`. */ protected estimateMessages(messages: ContextMessage[]): number; /** Python: `estimate_tokens_heuristic(system_prompt)`. */ protected estimateSystemPrompt(systemPrompt: string): number; /** Python: `estimate_tool_schema_tokens(tools, use_accurate=False)`. */ protected estimateTools(tools: ToolSchema[]): number; /** * Convert policy to a plain object for serialization. * Python parity with `to_dict()`; keys are camelCase here (the TypeScript * convention). {@link ContextCompactionPolicy.fromDict} accepts either * camelCase or Python's snake_case keys. */ toDict(): Record; /** * Create a policy from a plain object. * Python parity with `from_dict(data)` (classmethod). Accepts camelCase keys * (as produced by {@link toDict}) or Python's snake_case keys. */ static fromDict(data: Record): ContextCompactionPolicy; /** Independent copy of this policy (Python: `copy.deepcopy(policy)`). */ clone(): ContextCompactionPolicy; } /** * Conservative preset: compact early, keep more history. * Python parity with `CONSERVATIVE_POLICY` in context/adapters.py. */ export declare const CONSERVATIVE_POLICY: ContextCompactionPolicy; /** * Balanced preset (the default policy). * Python parity with `BALANCED_POLICY` in context/adapters.py. */ export declare const BALANCED_POLICY: ContextCompactionPolicy; /** * Aggressive preset: use as much of the window as possible, summarise when full. * Python parity with `AGGRESSIVE_POLICY` in context/adapters.py. */ export declare const AGGRESSIVE_POLICY: ContextCompactionPolicy; /** * Get the default context compaction policy: a fresh copy of * {@link BALANCED_POLICY}, so mutating the result never affects the preset. * Python parity with `get_default_policy()` in context/protocols.py / * context/policy.py (which return `deepcopy(BALANCED_POLICY)`). */ export declare function getDefaultPolicy(): ContextCompactionPolicy; export default ContextCompactionPolicy;