export function createCompactionEventHandler(options) {
    const { sessionId, compactionService, onCompaction } = options;
    return async function handleCompactionEvent(event) {
        if (!isCompactionEvent(event)) {
            return;
        }
        const compactionEvent = extractCompactionEvent(event);
        if (!compactionEvent) {
            return;
        }
        await compactionService.notifyCompaction(sessionId, compactionEvent);
        await onCompaction?.(compactionEvent);
    };
}
function isCompactionEvent(event) {
    if (event.event === 'on_llm_new_token') {
        const name = 'name' in event ? event.name : '';
        return name === 'CompactionReducer' || name === 'context_compaction';
    }
    if (typeof event.event === 'string') {
        return event.event.includes('compaction') || event.event.includes('context');
    }
    return false;
}
function extractCompactionEvent(event) {
    try {
        const data = event.data;
        if (!data)
            return null;
        const chunk = data.chunk;
        if (!chunk)
            return null;
        if (chunk.type === 'compaction' || chunk.__type === 'compaction') {
            return {
                summary: String(chunk.summary ?? 'Context compacted'),
                source: chunk.source ?? 'llm',
                estimatedTokens: Number(chunk.estimatedTokens ?? 0),
                thresholdTokens: Number(chunk.thresholdTokens ?? 0),
                messagesCompacted: Number(chunk.messagesCompacted ?? 0),
                preservedRecentMessages: Number(chunk.preservedRecentMessages ?? 4),
                fallbackReason: chunk.fallbackReason,
            };
        }
        return {
            summary: String(chunk.summary ?? 'Context compacted'),
            source: 'llm',
            estimatedTokens: Number(chunk.estimatedTokens ?? 0),
            thresholdTokens: Number(chunk.thresholdTokens ?? 0),
            messagesCompacted: Number(chunk.messagesCompacted ?? 0),
            preservedRecentMessages: Number(chunk.preservedRecentMessages ?? 4),
        };
    }
    catch {
        return null;
    }
}
export async function processCompactionFromStream(event, sessionId, compactionService, onCompaction) {
    const handler = createCompactionEventHandler({ sessionId, compactionService, onCompaction });
    await handler(event);
}
//# sourceMappingURL=compaction-middleware.js.map