/** * Message Sanitizer - Cleans messages before saving to history * * Handles edge cases where LLM API calls fail and produce invalid messages * that would cause subsequent API calls to fail (creating a vicious cycle). * * Key issues addressed: * - Empty content from API errors * - Messages with stopReason: "error" * - Messages with errorMessage field * - Invalid tool_call_id references */ import type { AgentMessage } from '@earendil-works/pi-agent-core'; /** * Options for message sanitization */ export interface SanitizeOptions { /** Remove error messages (default: true) */ removeErrors?: boolean; /** Remove empty messages (default: true) */ removeEmpty?: boolean; /** Keep at least N recent messages (default: 0) */ keepRecent?: number; /** Log removed messages (default: true in development) */ logRemovals?: boolean; } /** * Result of sanitization */ export interface SanitizeResult { /** Sanitized messages */ messages: AgentMessage[]; /** Number of messages removed */ removed: number; /** Reasons for removal */ reasons: Array<{ index: number; reason: string; }>; } /** * Sanitize messages before saving to history. * * Removes: * - Assistant messages with stopReason: "error" * - Assistant messages with stopReason: "aborted" only when empty (partial interrupted text is kept) * - Assistant messages with errorMessage field * - Assistant messages with empty/invalid content * * @param messages - Messages to sanitize * @param options - Sanitization options * @returns Sanitized messages and removal details */ export declare function sanitizeMessages(messages: AgentMessage[], options?: SanitizeOptions): SanitizeResult; /** * Clean trailing error messages from message history. * * This is useful for cleaning up after a failed turn, ensuring * the conversation can continue from the last valid state. * * @param messages - Messages to clean * @returns Cleaned messages */ export declare function cleanTrailingErrors(messages: AgentMessage[]): AgentMessage[]; /** * Validate a single message for potential issues. * Returns null if valid, or an error description if problematic. */ export declare function validateMessage(message: AgentMessage): string | null; /** * Quick check if messages contain any problematic entries. * Useful for debugging and monitoring. */ export declare function hasProblematicMessages(messages: AgentMessage[]): boolean;