function isToolMessage(msg) {
    return msg.role === "tool" && Array.isArray(msg.content);
}
function isUnsummarizedToolMessage(msg) {
    return isToolMessage(msg) && !msg._superblocks?.summarized;
}
function isAssistantWithTokens(msg) {
    return (msg.role === "assistant" &&
        msg._superblocks?.cumulativeInputTokens !== undefined);
}
/**
 * Groups messages into turns. Each turn ends with an assistant message
 * that has cumulativeInputTokens. The token count for a turn is calculated
 * as the delta between consecutive assistant messages' cumulativeInputTokens.
 */
export function identifyTurns(messages) {
    const turns = [];
    let turnStart = 0;
    let prevTokens = 0;
    for (let i = 0; i < messages.length; i++) {
        const msg = messages[i];
        if (isAssistantWithTokens(msg)) {
            const currentTokens = msg._superblocks.cumulativeInputTokens;
            const toolIndices = [];
            for (let j = turnStart; j <= i; j++) {
                if (isUnsummarizedToolMessage(messages[j])) {
                    toolIndices.push(j);
                }
            }
            turns.push({
                startIndex: turnStart,
                endIndex: i,
                tokenCount: currentTokens - prevTokens,
                toolMessageIndices: toolIndices,
            });
            prevTokens = currentTokens;
            turnStart = i + 1;
        }
    }
    return turns;
}
/**
 * Selects the most recent turns that fit within the token budget.
 * Walks backward through turns, accumulating token counts.
 */
export function selectRecentTurns(turns, tokenBudget) {
    const selected = [];
    let accumulated = 0;
    for (let i = turns.length - 1; i >= 0; i--) {
        const turn = turns[i];
        if (accumulated + turn.tokenCount <= tokenBudget) {
            accumulated += turn.tokenCount;
            selected.unshift(turn);
        }
        else {
            break;
        }
    }
    return selected;
}
//# sourceMappingURL=turns.js.map