import { normalizeWhitespace, truncateText } from "@best-agent/foundation";
export function summarizeToolActivity(resultItems, tools, mode = "default", callSourceItems = resultItems) {
    const toolCalls = callSourceItems.filter((item) => item.kind === "tool-call");
    const toolResults = resultItems.filter((item) => item.kind === "tool-result");
    const toolCallsByCallId = new Map(toolCalls.map((item) => [item.callId, item]));
    const lines = toolResults.flatMap((result) => {
        if (result.toolName === "delegate_tasks") {
            return [
                `- Tool delegate_tasks completed with output "${truncateToolLedgerText(result.output)}".`,
            ];
        }
        if (result.toolName === "invalid") {
            return [`- Tool invalid failed with output "${truncateToolLedgerText(result.output)}".`];
        }
        const toolCall = toolCallsByCallId.get(result.callId) ??
            [...toolCalls]
                .reverse()
                .find((item) => item.turnId === result.turnId && item.toolName === result.toolName);
        if (!toolCall) {
            return [];
        }
        const summary = sanitizeToolLedgerText(summarizeStoredToolResult(result, toolCall, tools));
        return summary ? [`- ${summary}`] : [];
    });
    if (lines.length === 0) {
        return undefined;
    }
    const seen = new Set();
    const deduped = [];
    for (let i = lines.length - 1; i >= 0; i -= 1) {
        const line = lines[i];
        if (!seen.has(line)) {
            seen.add(line);
            deduped.unshift(line);
        }
    }
    const summaryLimit = mode === "compact" ? 6 : 12;
    return deduped.slice(-summaryLimit).join("\n");
}
export function buildMicrocompressedToolLedgerConversation(items, recentItemLimit, tools) {
    const recentItems = items.slice(-recentItemLimit);
    const condensedToolActivity = summarizeToolActivity(recentItems, tools, "compact", items);
    if (!condensedToolActivity) {
        return [];
    }
    return [
        {
            role: "assistant",
            content: `Recent tool ledger:\n${condensedToolActivity}`,
        },
    ];
}
function sanitizeToolLedgerText(value) {
    return value.trim();
}
function summarizeStoredToolResult(result, toolCall, tools) {
    if (toolCall.historyInput !== undefined) {
        return tools.summarize(result.toolName, toolCall.historyInput, result.output);
    }
    return [
        `Tool ${result.toolName} ${result.outcome}.`,
        `Input: ${truncateToolLedgerText(toolCall.input)}`,
        `Output: ${truncateToolLedgerText(result.output)}`,
    ].join("\n");
}
function truncateToolLedgerText(value) {
    return truncateText(normalizeWhitespace(sanitizeToolLedgerText(value)), 160);
}
//# sourceMappingURL=tool-ledger.js.map