export const stringifyToolField = (value) => {
    if (value === undefined || value === null)
        return undefined;
    if (typeof value === "string") {
        return value.trim().length > 0 ? value : undefined;
    }
    try {
        return JSON.stringify(value);
    }
    catch {
        return String(value);
    }
};
export const parseToolResultValue = (value) => {
    if (value === undefined || value === null) {
        return undefined;
    }
    if (typeof value === "object") {
        return value;
    }
    if (typeof value !== "string") {
        return String(value);
    }
    const trimmed = value.trim();
    if (!trimmed) {
        return undefined;
    }
    try {
        let parsed = JSON.parse(trimmed);
        if (typeof parsed === "string" &&
            (parsed.startsWith("{") || parsed.startsWith("["))) {
            parsed = JSON.parse(parsed);
        }
        if (parsed && typeof parsed === "object") {
            return parsed;
        }
    }
    catch {
        // Fall back to the original string when the payload is plain text.
    }
    return value;
};
export const getFirstToolCallEnvelope = (data) => {
    if (!data || typeof data !== "object")
        return undefined;
    const direct = data.toolCall || data.tool_call;
    if (direct)
        return direct;
    const arrayCandidates = [data.tool_calls, data.toolCalls];
    for (const candidate of arrayCandidates) {
        if (Array.isArray(candidate) && candidate.length > 0) {
            return candidate[0];
        }
    }
    return undefined;
};
export const extractToolCallFields = (data) => {
    const envelope = getFirstToolCallEnvelope(data);
    const functionPayload = data?.function || envelope?.function;
    const functionName = data?.functionName ||
        data?.name ||
        functionPayload?.name ||
        envelope?.functionName ||
        envelope?.name ||
        "unknown";
    const toolCallId = data?.toolCallId || data?.id || envelope?.id;
    const functionArguments = stringifyToolField(data?.functionArguments) ||
        stringifyToolField(data?.arguments) ||
        stringifyToolField(functionPayload?.arguments) ||
        stringifyToolField(envelope?.functionArguments) ||
        stringifyToolField(envelope?.arguments) ||
        "{}";
    return {
        toolCallId,
        functionName,
        functionArguments,
    };
};
export const convertAgentMessagesToAiFormat = (agentMessages) => {
    return agentMessages.map((agentMessage) => {
        const message = {
            id: agentMessage.id,
            content: agentMessage.content,
            reasoning: agentMessage.reasoning,
            formattedContent: agentMessage.content
                ?.replace(/^######\s+(.+)$/gm, "<h6>$1</h6>")
                ?.replace(/^#####\s+(.+)$/gm, "<h5>$1</h5>")
                ?.replace(/^####\s+(.+)$/gm, "<h4>$1</h4>")
                ?.replace(/^###\s+(.+)$/gm, "<h3>$1</h3>")
                ?.replace(/^##\s+(.+)$/gm, "<h2>$1</h2>")
                ?.replace(/^#\s+(.+)$/gm, "<h1>$1</h1>")
                ?.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
                ?.replace(/\n/g, "<br/>"),
            name: agentMessage.name,
            role: agentMessage.role,
            createdDate: agentMessage.createdDate,
            tool_calls: agentMessage.toolCalls
                ? agentMessage.toolCalls.map((toolCall) => {
                    const isPruned = !!toolCall.isPruned ||
                        /^PRUNED$/i.test(toolCall.functionError || "");
                    const displayResult = parseToolResultValue(toolCall.functionResultRichContent) ?? toolCall.functionResult;
                    return {
                        id: toolCall.toolCallId,
                        displayName: toolCall.functionName,
                        function: {
                            name: toolCall.functionName,
                            arguments: toolCall.functionArguments,
                            result: displayResult,
                            error: toolCall.functionError,
                        },
                        requiresApproval: toolCall.requiresApproval,
                        isPruned,
                        prunedAt: toolCall.prunedAt,
                        isCompleted: toolCall.isCompleted,
                        isStreaming: !agentMessage.isCompleted &&
                            !toolCall.isCompleted &&
                            !displayResult &&
                            !toolCall.functionError &&
                            !isPruned,
                        messageId: toolCall.messageId,
                        dbMessageId: toolCall.dbMessageId,
                        responseTimeMs: toolCall.responseTimeMs,
                        createdDate: toolCall.createdDate,
                    };
                })
                : [],
        };
        if (agentMessage.toolCallId) {
            message.tool_call_id = agentMessage.toolCallId;
        }
        return message;
    });
};
//# sourceMappingURL=agentMessageConversion.js.map