Skip to content

StreamEvent

StreamEventassistant.chat() 产出的所有事件的联合类型。跨引擎提供统一接口。

类型定义

typescript
type StreamEvent =
  | { type: 'text'; content: string }
  | { type: 'tool_call'; name: string; args: string }
  | { type: 'tool_result'; content: string }
  | { type: 'warning'; message: string }
  | { type: 'error'; message: string }
  | { type: 'done'; sessionId?: string; durationMs?: number;
      costUsd?: number; numTurns?: number };

事件类型

类型说明
text来自 Agent 的流式文本内容。多个 text 事件拼接成完整回复。
tool_callAgent 正在调用工具(读文件、运行命令等)
tool_result工具调用的结果
warning来自引擎的非致命警告
error处理过程中发生错误
done一轮对话结束。可选字段:sessionIddurationMscostUsd(Claude Code/OpenCode)、numTurns(Claude Code)

消费事件

typescript
// 只打印文本
for await (const event of assistant.chat('你好')) {
  if (event.type === 'text') process.stdout.write(event.content);
}

// IM 场景:累积后发送
let reply = '';
for await (const event of assistant.chat(message)) {
  if (event.type === 'text') reply += event.content;
}
await sendToIM(reply);

基于 MIT 协议 发布。