"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUserTextMessage = createUserTextMessage;
exports.createErrorTextMessage = createErrorTextMessage;
exports.createUserFileMessage = createUserFileMessage;
exports.createToolOutputMessagePart = createToolOutputMessagePart;
exports.createToolOutputMessage = createToolOutputMessage;
exports.createToolOutputFromResult = createToolOutputFromResult;
exports.extractToolCallsFromMessages = extractToolCallsFromMessages;
exports.filterClientSideToolCalls = filterClientSideToolCalls;
exports.filterToolCallsWithoutOutputs = filterToolCallsWithoutOutputs;
exports.getAskForHelpToolCallPart = getAskForHelpToolCallPart;
exports.isAskingForHelp = isAskingForHelp;
exports.getAskForHelpText = getAskForHelpText;
const uuid_1 = require("uuid");
const contextBuilder_1 = require("./contextBuilder");
function createUserTextMessage(text, metadata) {
    return {
        role: 'user',
        id: (0, uuid_1.v4)(),
        timestamp: Date.now(),
        metadata,
        parts: [
            {
                type: 'text',
                text,
            },
        ],
    };
}
function createErrorTextMessage(text) {
    return createUserTextMessage(text, { type: 'error' });
}
function createUserFileMessage(text, fileData, mediaType) {
    return {
        role: 'user',
        id: (0, uuid_1.v4)(),
        timestamp: Date.now(),
        parts: [
            {
                type: 'text',
                text,
            },
            {
                type: 'file',
                source: {
                    type: 'base64',
                    media_type: mediaType,
                    data: fileData,
                },
            },
        ],
    };
}
function createToolOutputMessagePart({ toolCallId, toolName, result, isError = false, screenshot, additionalImages, }) {
    const contentItems = [];
    const jsonContentItem = {
        type: 'json',
        json: result,
    };
    contentItems.push(jsonContentItem);
    if (screenshot) {
        const imageDataContentItem = {
            type: 'image-data',
            image_data: screenshot,
            media_type: 'image/png',
        };
        contentItems.push(imageDataContentItem);
    }
    if (additionalImages) {
        for (const img of additionalImages) {
            contentItems.push({
                type: 'image-data',
                image_data: img.image_data,
                media_type: img.media_type,
            });
        }
    }
    const output = isError
        ? {
            type: 'error-content',
            error_content: contentItems,
        }
        : {
            type: 'content',
            content: contentItems,
        };
    const part = {
        type: 'tool_output',
        tool_name: toolName,
        tool_call_id: toolCallId,
        output,
    };
    return part;
}
function createToolOutputMessage(toolOutputMessageParts) {
    return {
        role: 'tool_output',
        id: (0, uuid_1.v4)(),
        timestamp: Date.now(),
        parts: toolOutputMessageParts,
    };
}
function createToolOutputFromResult(params) {
    const { toolCallId, toolName, wrappedResult } = params;
    const { result, isError } = wrappedResult;
    const contentItems = [];
    contentItems.push({
        type: 'json',
        json: result.toolResponse,
    });
    if (result.imageContentItems) {
        for (const img of result.imageContentItems) {
            if (img.type === 'image-data' && img.image_data && img.media_type) {
                const imageDataContentItem = {
                    type: 'image-data',
                    image_data: img.image_data,
                    media_type: img.media_type,
                };
                contentItems.push(imageDataContentItem);
            }
        }
    }
    const output = isError
        ? { type: 'error-content', error_content: contentItems }
        : { type: 'content', content: contentItems };
    return {
        type: 'tool_output',
        tool_name: toolName,
        tool_call_id: toolCallId,
        output,
    };
}
function extractToolCallsFromMessages(messages, logger) {
    const modelMessages = messages.filter((m) => m.role === 'model');
    return modelMessages.flatMap((m) => (m.parts ?? [])
        .filter((p) => p.type === 'tool_call')
        .map((p) => {
        const toolCallPart = p;
        logger.info('[extractToolCallsFromMessages] Tool call part', JSON.stringify(toolCallPart, undefined, 2));
        const input = toolCallPart.input;
        const args = input?.type === 'json' ? input.json ?? {} : input ?? {};
        return {
            id: toolCallPart.id ?? '',
            name: toolCallPart.name ?? '',
            arguments: args,
        };
    }));
}
function filterClientSideToolCalls(toolCalls) {
    const supportedTools = new Set((0, contextBuilder_1.getSupportedTools)());
    return toolCalls.filter((tc) => tc.name.startsWith('execute_') || supportedTools.has(tc.name));
}
function filterToolCallsWithoutOutputs(toolCalls, messages) {
    const toolCallIdsWithOutputs = new Set(messages
        .filter((m) => m.role === 'tool_output')
        .flatMap((m) => (m.parts ?? [])
        .filter((p) => p.type === 'tool_output')
        .map((p) => p.tool_call_id)));
    return toolCalls.filter((tc) => !toolCallIdsWithOutputs.has(tc.id));
}
function getAskForHelpToolCallPart(messages) {
    return messages
        .flatMap((m) => m.parts ?? [])
        .filter((p) => p.type === 'tool_call')
        .find((toolCallPart) => toolCallPart.name === 'execute_ask_for_help');
}
function isAskingForHelp(messages) {
    return getAskForHelpToolCallPart(messages) !== undefined;
}
function getAskForHelpText(messages) {
    return (getAskForHelpToolCallPart(messages)?.input?.json?.question ??
        'Can you give me a hint for how to proceed?');
}
