> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zerone.run/llms.txt
> Use this file to discover all available pages before exploring further.

# 流式响应

> 消费 agent.query() 的异步事件流并处理中断。

# 消费流式事件

`agent.query()` 返回 `AsyncGenerator<SDKMessage>`，事件按产生顺序到达。应用可以逐步显示 assistant 内容、Tool 调用、结果与最终状态。

```typescript theme={null}
import { createAgent } from "@zerone-agent/agent-sdk";

const agent = createAgent();

for await (const event of agent.query("写一首关于 TypeScript 的俳句")) {
  if (event.type === "assistant") {
    for (const block of event.message.content) {
      if ("text" in block) process.stdout.write(block.text);
    }
  }
}

await agent.close();
```

## 一次性流式查询

顶层 `query()` 适合一次性任务，无需管理 Agent 生命周期：

```typescript theme={null}
import { query } from "@zerone-agent/agent-sdk";

for await (const message of query({
  prompt: "读取 package.json 并告诉我项目名称。",
  options: {
    allowedTools: ["Read", "Glob"],
    permissionMode: "bypassPermissions",
  },
})) {
  if (message.type === "assistant") {
    for (const block of message.message.content) {
      if ("text" in block) console.log(block.text);
    }
  }
}
```

## 结果事件

任务完成时发出 `result` 事件，携带费用等汇总信息：

```typescript theme={null}
import { query } from "@zerone-agent/agent-sdk";

for await (const msg of query({ prompt: "列出当前目录的文件。" })) {
  if (msg.type === "result") {
    console.log(`完成: $${msg.total_cost_usd?.toFixed(4)}`);
  }
}
```

## 中断

需要取消当前查询时调用 `agent.interrupt()`，或在创建时传入 `AbortController`。消费端应处理非文本 block，不要假设每个 assistant 事件都包含字符串。
