/**
 * Owns history cleanup before a low-level agent run enters the model loop.
 *
 * It removes orphaned tool messages and trims interrupted assistant tool calls
 * so reused histories remain valid model input.
 */
export class AgentHistorySanitizer {
    static sanitize(args) {
        const { introduced, resolved } = AgentHistorySanitizer.indexToolCallIds(args.history);
        return args.history.flatMap((message) => AgentHistorySanitizer.sanitizeMessage(message, introduced, resolved));
    }
    static indexToolCallIds(history) {
        const introduced = new Set(history
            .filter((m) => m.role === 'assistant' && !!m.toolCalls)
            .flatMap((m) => m.toolCalls.map((c) => c.id)));
        const resolved = new Set(history
            .filter((m) => m.role === 'tool')
            .map((m) => m.toolCallId));
        return { introduced, resolved };
    }
    static sanitizeMessage(message, introduced, resolved) {
        if (message.role === 'assistant' && message.toolCalls) {
            return AgentHistorySanitizer.sanitizeAssistantWithToolCalls(message, resolved);
        }
        if (message.role === 'tool' && !introduced.has(message.toolCallId)) {
            return [];
        }
        return [message];
    }
    static sanitizeAssistantWithToolCalls(message, resolved) {
        const resolvedCalls = message.toolCalls.filter((call) => resolved.has(call.id));
        if (resolvedCalls.length > 0) {
            return [{ ...message, toolCalls: resolvedCalls }];
        }
        return message.content.trim()
            ? [{ role: 'assistant', content: message.content }]
            : [];
    }
}
//# sourceMappingURL=history-sanitizer.js.map