/**
 * Image handling for tool execution results.
 *
 * Extracts image blocks from tool results, produces text fallbacks for
 * terminals without image support, and resolves renderable image data
 * (with Kitty PNG conversion when needed).
 */
import stripAnsi from 'strip-ansi';
import { sanitizeBinaryOutput } from '../../../app/tools/bash-runtime.js';
import { getCapabilities, getImageDimensions, imageFallback } from '../../../tui/index.js';
/** Extract image content blocks from a tool execution result. */
export function getToolExecutionImageBlocks(result) {
    return result?.content?.filter((block) => block.type === 'image') ?? [];
}
/**
 * Build the text output string from a tool result.
 * Joins text blocks and appends image fallback indicators when images
 * cannot be displayed inline.
 */
export function getToolExecutionTextOutput(result, options) {
    if (!result) {
        return '';
    }
    const textBlocks = result.content?.filter((block) => block.type === 'text') ?? [];
    const imageBlocks = getToolExecutionImageBlocks(result);
    let output = textBlocks
        .map((block) => sanitizeBinaryOutput(stripAnsi(block.text || '')).replace(/\r/g, ''))
        .join('\n');
    const capabilities = options.capabilities ?? getCapabilities();
    if (imageBlocks.length > 0 && (!capabilities.images || !options.showImages)) {
        const imageIndicators = imageBlocks
            .map((block) => {
            const mimeType = block.mimeType ?? 'image/unknown';
            const dimensions = block.data && block.mimeType
                ? (getImageDimensions(block.data, block.mimeType) ?? undefined)
                : undefined;
            return imageFallback(mimeType, dimensions);
        })
            .join('\n');
        output = output ? `${output}\n${imageIndicators}` : imageIndicators;
    }
    return output;
}
/**
 * Resolve an image block to renderable data for the current terminal.
 * Returns null if the terminal doesn't support images, images are disabled,
 * or the format is incompatible (e.g. non-PNG on Kitty without conversion).
 */
export function resolveRenderableToolImage(block, convertedImage, capabilities, showImages) {
    if (!capabilities.images || !showImages || !block.data || !block.mimeType) {
        return null;
    }
    const data = convertedImage?.data ?? block.data;
    const mimeType = convertedImage?.mimeType ?? block.mimeType;
    if (capabilities.images === 'kitty' && mimeType !== 'image/png') {
        return null;
    }
    return { data, mimeType };
}
//# sourceMappingURL=tool-execution-images.js.map