Skip to main content

路径

GET /stream/:taskId 公网入口 https://agentapi.kira.art/stream/:taskId。响应 Content-Type: text/event-stream

认证

eitherAuth()Authorization: Bearer <Supabase JWT>X-Internal-Key: <INTERNAL_KEY>。校验 task.userId === jwtPayload.sub,不匹配返 403

请求

来源字段必填说明
路径参数taskIdPOST /task 返回
HeaderLast-Event-ID续读游标。重连时带上最后收到的 id,服务端从该 Redis stream entry 之后重放
续读用 SSE 协议标准的 Last-Event-ID header,而不是 query string。浏览器 EventSource 自动带;用 fetch 手动解析时需自行携带。

帧格式

每条 chunk batch 与终止哨兵都是一条 Redis stream entry,转成 SSE 帧(writeEntrysrc/hono/agent/index.ts:402):
id: <streamEntryId>
data: [{...}, {...}]
要点(严格按 code):
  • 普通帧无 event: 字段data 是 chunk JSON 数组本身(AI SDK UI chunks),前端 JSON.parse(data) 后直接 iterate。
  • event: donedata 为空字符串。
  • event: errordata 是错误字符串(非 JSON 对象)。
  • 每帧都带 id(Redis entry ID),即续读游标。
  • 服务端每次 BLOCK 超时会写一条 SSE comment 心跳 : keepalive,客户端忽略,防 CF / fly-proxy / Bun 任意层 idle 断连。
  • 若 task HASH 已被 GC(TTL 过期)且无新帧,服务端发 event: error + data: {"message":"stream expired"} 并关闭。
客户端见 event: doneevent: error 即关闭连接。

续读语义

1

Replay

Last-Event-ID(无则从头)readChunksFrom 重放已有 entries。读到哨兵(done / error)即结束。
2

Block 等新帧

blockingReadChunksAfterXREAD BLOCK STREAMS agent:stream:{taskId} <cursor>)循环等待新 chunk,逐帧写出并推进 cursor
3

断开 ≠ 终止

浏览器断开只让 reader 退出,后台 run 不停。重连(可能落到任意 instance)带上 Last-Event-ID 即可无缝续读。

状态码

含义
200建立 SSE 流(text/event-stream
401缺少有效 JWT / jwtPayload.sub
403task 属于其他用户
404task 不存在(从未创建或 TTL 已过期)

示例

# 首次连接
curl -N https://agentapi.kira.art/stream/33333333-3333-3333-3333-333333333333 \
  -H "Authorization: Bearer $SUPABASE_JWT"

# 续读(带上最后收到的 id)
curl -N https://agentapi.kira.art/stream/33333333-3333-3333-3333-333333333333 \
  -H "Authorization: Bearer $SUPABASE_JWT" \
  -H "Last-Event-ID: 1759500000123-0"
// fetch streaming(手动解析,可控制 Last-Event-ID)
const res = await fetch(`https://agentapi.kira.art/stream/${taskId}`, {
  headers: {
    Authorization: `Bearer ${jwt}`,
    ...(lastEventId ? { "Last-Event-ID": lastEventId } : {}),
  },
});
const reader = res.body!.getReader();
// 自行按 SSE 分帧;普通帧 JSON.parse(data) 得 chunk 数组

src/hono/agent/index.ts:338(handler)、writeEntry at :402src/lib/agentTask.tsreadChunksFrom / blockingReadChunksAfter

相关