SSE、JSON 帧与有界事件流
复用传输机制,保持取消和背压;协议解析与业务校验仍各自负责。
readSse 解析标准 SSE;encodeSseEvent/writeSseFrame 只处理编码与可取消的写入背压,HTTP 响应、认证和生命周期由 App 框架拥有。浏览器接收不需要一个专用 SDK 后端。
streamEvents 使用单槽交接,生产者必须 await emit,不无限堆积输出。消费者停止时通知生产者,不将尚未消费内容当作已交付。
scanJsonObjectFrames 仅提取完整对象帧,不校验外围内容;parseJsonFrames 按 maxFrames/maxExtraClosings 校验外围字符并 JSON.parse。它们不修复、不截断、不解释业务字段,完整业务结构仍由 Schema 校验。
由简到繁的同业务示例
在本地解析一帧 SSE
入门 · Node.js
ts
import { Support } from '@jangts/agent-core';
const frame = Support.encodeSseEvent({ event: 'status', data: JSON.stringify({ phase: 'thinking' }) });
const body = new Response(frame).body!;
for await (const event of Support.readSse(body)) console.log(event.event, event.data);js
import { Support } from '@jangts/agent-core';
const frame = Support.encodeSseEvent({ event: 'status', data: JSON.stringify({ phase: 'thinking' }) });
const body = new Response(frame).body;
for await (const event of Support.readSse(body))
console.log(event.event, event.data);生产者等待每一次事件交付
配置 · Node.js
ts
import { Support } from '@jangts/agent-core';
const signal = new AbortController().signal;
const stream = Support.streamEvents<{ phase: string }>(async emit => {
await emit({ phase: 'preparing' });
await emit({ phase: 'complete' });
}, { signal });
for await (const event of stream) console.log(event.phase);js
import { Support } from '@jangts/agent-core';
const signal = new AbortController().signal;
const stream = Support.streamEvents(async (emit) => {
await emit({ phase: 'preparing' });
await emit({ phase: 'complete' });
}, { signal });
for await (const event of stream)
console.log(event.phase);显式限制 JSON 帧数量和外围内容
扩展 · Node.js
ts
import { Support } from '@jangts/agent-core';
const text = '{"kind":"reply","answer":"服务正常"}';
console.log(Support.scanJsonObjectFrames(text));
console.log(Support.parseJsonFrames(text, { maxFrames: 1, maxExtraClosings: 0 }));
const sent: string[] = [];
await Support.writeSseFrame({
writer: { write(frame) { sent.push(frame); return true; }, async waitForDrain() {} },
frame: Support.encodeSseEvent({ event: 'answer', data: text }),
}, { signal: new AbortController().signal });
console.log(sent);js
import { Support } from '@jangts/agent-core';
const text = '{"kind":"reply","answer":"服务正常"}';
console.log(Support.scanJsonObjectFrames(text));
console.log(Support.parseJsonFrames(text, { maxFrames: 1, maxExtraClosings: 0 }));
const sent = [];
await Support.writeSseFrame({
writer: { write(frame) { sent.push(frame); return true; }, async waitForDrain() { } },
frame: Support.encodeSseEvent({ event: 'answer', data: text }),
}, { signal: new AbortController().signal });
console.log(sent);