/**
 * Shared SSE reader for Shortcut's local `/api/llm/stream` proxy endpoint.
 *
 * This is part of the desktop Shortcut provider path only. Cloud mode does not
 * use this reader and must not depend on the Python-backed proxy stream.
 *
 * This sits below provider/tool adapters: it only reads the wire format and
 * invokes a callback for each parsed event payload.
 */
import { parseSSE } from './sse-protocol.js';
/**
 * Read an SSE response body, parse each event block, and invoke the callback.
 * Handles chunked decoding and double-newline event splitting.
 */
export async function readShortcutSSE(response, onEvent) {
    if (!response.body) {
        throw new Error('LLM stream returned no response body');
    }
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    const processEventBlock = async (eventBlock) => {
        if (!eventBlock.trim()) {
            return;
        }
        const parsed = parseSSE(eventBlock.split('\n'));
        if (!parsed) {
            return;
        }
        let payload;
        try {
            payload = JSON.parse(parsed.data);
        }
        catch {
            return;
        }
        await onEvent(parsed.event, payload);
    };
    while (true) {
        const { done, value } = await reader.read();
        if (done) {
            break;
        }
        buffer += decoder.decode(value, { stream: true });
        const events = buffer.split('\n\n');
        buffer = events.pop() || '';
        for (const eventBlock of events) {
            await processEventBlock(eventBlock);
        }
    }
    buffer += decoder.decode();
    if (buffer.trim()) {
        await processEventBlock(buffer);
    }
}
//# sourceMappingURL=shortcut-sse.js.map