流式输出

session.stream(prompt) 会在回合运行过程中逐步产出事件,因此你可以在文本到达时即时渲染,并实时响应工具活动。当你需要实时 UI,或希望 CLI 逐 token 打印输出(而不是等待 send 或 run 返回完整结果)时,请使用它。

每个事件都带有稳定的 version、type、payload 和可选 metadata 信封字段。常见类型包括 agent_start、text_delta / reasoning_delta、tool_start / tool_end、agent_end 和 error。验证信息位于 agent_end 的 payload 与便捷字段中。

Node.js
Python

说明:

  • Node 端使用 stream.next() 手动迭代流,检查 next.done 与 next.value。在当前构建中,Python SDK 将流式输出暴露为同步迭代器,因此你可以用普通的 for 循环来消费它(而 parallel、pipeline 等编排 API 仍为 async)。
  • 两个 SDK 都公开规范的 event.type;Python 保留 event.event_type 作为兼容别名。event.payload 是完整、无损的 payload,未来未知事件类型也会原样保留。便捷字段遵循各语言的大小写约定:Node 中为 toolName / exitCode / verificationSummaryText,Python 中为 tool_name / exit_code / verification_summary_text。
  • 当启用确认策略时,流式事件还可能包含人工介入(human-in-the-loop)确认信号(confirmation_required、confirmation_received、confirmation_timeout)。

可运行的流式示例位于 crates/code/sdk/node/examples/streaming/ 目录下。一个完整的人工介入确认循环示例位于 crates/code/sdk/node/examples/streaming/hitl_confirmation_loop.ts,对应的 Python 版本位于 crates/code/sdk/python/examples/hitl_confirmation_loop.py。