export function cloneMessages(messages) {
    return structuredClone(messages);
}
function extractAssistantText(content) {
    if (typeof content === 'string')
        return content;
    if (!Array.isArray(content))
        return String(content);
    return content
        .filter((part) => part.type === 'text')
        .map((part) => part.text)
        .join('');
}
function toInternalMessage(message) {
    if (message.role === 'user') {
        return {
            role: 'user',
            content: typeof message.content === 'string' ? message.content : message.content,
        };
    }
    if (message.role === 'assistant') {
        return { role: 'assistant', content: extractAssistantText(message.content) };
    }
    const toolMsg = message;
    return {
        role: 'tool',
        callId: toolMsg.callId ?? '',
        content: typeof toolMsg.content === 'string' ? toolMsg.content : String(toolMsg.content),
        ...(typeof toolMsg.name === 'string' && toolMsg.name.length > 0 ? { toolName: toolMsg.name } : {}),
    };
}
export function messagesToInternal(messages) {
    return messages.map(toInternalMessage);
}
export function cloneBranchMap(branches) {
    const result = {};
    for (const [name, msgs] of branches) {
        result[name] = cloneMessages(msgs);
    }
    return result;
}
export function restoreBranchMap(branches) {
    const restored = new Map();
    if (!branches)
        return restored;
    for (const [name, msgs] of Object.entries(branches)) {
        restored.set(name, msgs);
    }
    return restored;
}
export function deriveConversationTitle(content) {
    const text = content.trim();
    if (text.length <= 50)
        return text;
    let cut = text.lastIndexOf(' ', 50);
    if (cut <= 0)
        cut = 50;
    return text.slice(0, cut);
}
export function extractUserDisplayText(content) {
    if (typeof content === 'string')
        return content;
    const textParts = content.filter((part) => part.type === 'text');
    const imageCount = content.filter((part) => part.type === 'image').length;
    return textParts.map((part) => part.text).join('') + (imageCount > 0 ? ` [+${imageCount} image(s)]` : '');
}
