import { safeSliceHead } from "../utils/safe-slice.js";
export const LIVE_TOOL_RESULT_MAX_CHARS = 16_000;
export const LIVE_TOOL_RESULT_AGGREGATE_MAX_CHARS = 64_000;
function normalizePositiveInteger(value, fallback) {
    if (value === undefined || !Number.isFinite(value) || value <= 0) {
        return fallback;
    }
    return Math.max(1, Math.floor(value));
}
export function truncateLiveToolResultText(text, maxChars) {
    if (text.length <= maxChars)
        return text;
    const marker = `\n[... live tool result truncated from ${text.length} chars; ` +
        "request a narrower snapshot/selector if missing detail ...]";
    const headBudget = Math.max(0, maxChars - marker.length);
    if (headBudget <= 0)
        return safeSliceHead(marker, maxChars);
    return `${safeSliceHead(text, headBudget)}${marker}`;
}
export function guardLiveToolResults(messages, opts = {}) {
    const liveToolIndexes = [];
    for (let i = messages.length - 1; i >= 0; i--) {
        const msg = messages[i];
        if (msg.role === "assistant")
            break;
        if (msg.role === "tool" && typeof msg.content === "string") {
            liveToolIndexes.push(i);
        }
    }
    liveToolIndexes.reverse();
    const stats = {
        cappedCount: 0,
        inputChars: 0,
        outputChars: 0,
    };
    if (liveToolIndexes.length === 0)
        return { messages, stats };
    const perToolMax = normalizePositiveInteger(opts.liveToolResultMaxChars, LIVE_TOOL_RESULT_MAX_CHARS);
    const aggregateMax = normalizePositiveInteger(opts.liveToolResultAggregateMaxChars, LIVE_TOOL_RESULT_AGGREGATE_MAX_CHARS);
    const effectiveMax = Math.max(1, Math.min(perToolMax, Math.floor(aggregateMax / liveToolIndexes.length)));
    let guarded = messages;
    for (const index of liveToolIndexes) {
        const msg = messages[index];
        const content = msg.content;
        const output = truncateLiveToolResultText(content, effectiveMax);
        stats.inputChars += content.length;
        stats.outputChars += output.length;
        if (output !== content) {
            stats.cappedCount++;
            if (guarded === messages)
                guarded = [...messages];
            guarded[index] = { ...msg, content: output };
        }
    }
    return { messages: guarded, stats };
}
//# sourceMappingURL=live-tool-result-guard.js.map