/** Shared SSE transport framing. Protocol adapters, not this reader, decide * which events are terminal. Keep a bounded tail and tolerate a final frame * without a trailing blank line (common with compatibility endpoints). */ export function createSseFramer() { const decoder = new TextDecoder('utf-8', { fatal: true }); const maxFrameChars = 4 * 1024 * 1024; let buffer = ''; const dataOf = (frame: string): string | undefined => { if (frame.length > maxFrameChars) throw new Error('模型流单帧超过安全上限'); const data = frame.split(/\r?\n/).flatMap(line => line === 'data' ? [''] : line.startsWith('data:') ? [line.slice(5).replace(/^ /, '')] : [], ).join('\n').trim(); return data || undefined; }; return { push(bytes: Uint8Array): string[] { buffer += decoder.decode(bytes, { stream: true }); const frames = buffer.split(/\r?\n\r?\n/); buffer = frames.pop()!; if (buffer.length > maxFrameChars) throw new Error('模型流单帧超过安全上限'); return frames.map(dataOf).filter((data): data is string => data !== undefined); }, finish(): string[] { const data = dataOf(buffer + decoder.decode()); buffer = ''; return data === undefined ? [] : [data]; }, }; } /** Comment heartbeats and empty data were filtered by framing. An invalid * payload is not a heartbeat: continuing could omit part of a tool call. */ export function parseSseObject(data: string): Record { try { const value: unknown = JSON.parse(data); if (value && typeof value === 'object' && !Array.isArray(value)) return value as Record; } catch { /* Do not echo untrusted payloads into errors or logs. */ } throw new Error('模型流包含损坏的数据帧,不能确认响应完整'); } /** A declared finish is immutable. Usage can still arrive before transport * close, but no new model output may be attached to the finished generation. */ export function createFinishGuard() { let declared: string | undefined; return { declare(reason: unknown) { if (typeof reason !== 'string' || !reason || (declared !== undefined && declared !== reason)) throw new Error('模型流终态无效或与已声明的终态冲突'); declared = reason; }, assertOpen() { if (declared !== undefined) throw new Error('模型流已声明终态,不能继续添加输出'); }, }; }