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

# 多轮对话

`query()` 有两种输入模式：

* **单消息查询模式**：一次提交一条用户消息，SDK 完成本轮回复后关闭会话。见 [快速开始](/zh/cli/sdk/quick-start)。
* **多消息会话模式**：保持会话开启，和模型进行多轮对话。

***

<div id="多消息会话" />

## 多消息会话

定义一个按顺序产出用户消息的序列：

```typescript theme={null}
import { qodercliAuth, query, type SDKUserMessage } from '@qoder-ai/qoder-agent-sdk';

async function* messages(): AsyncGenerator<SDKUserMessage> {
  yield {
    type: 'user',
    message: { role: 'user', content: [{ type: 'text', text: 'Analyze this codebase for security issues' }] },
    parent_tool_use_id: null,
  };

  // 中间可以等待任意外部条件再产出下一条
  await new Promise((resolve) => setTimeout(resolve, 2000));

  yield {
    type: 'user',
    message: { role: 'user', content: [{ type: 'text', text: 'Now write a short report' }] },
    parent_tool_use_id: null,
  };
}

for await (const msg of query({
  prompt: messages(),
  options: {
    auth: qodercliAuth(),
    allowedTools: ['Read', 'Grep'],
  },
})) {
  if (msg.type === 'result' && msg.subtype === 'success') {
    console.log(msg.result);
  }
}
```

模型每收到一条用户消息回一轮，消息序列结束后会话自动关闭。消息字段定义见 [`SDKUserMessage`](/zh/cli/sdk/references#sdkusermessage)。

***

<div id="管理会话生命周期" />

## 管理会话生命周期

多消息会话下，**`query()` 返回对象的生命周期由调用方掌握**。SDK 只会在消息序列自然结束时顺带关闭会话；其余情况都需要调用方主动决定何时收尾，否则会话会一直挂着。

常见的需要调用方主动管理的场景：

* 消息序列本身不会结束，例如循环等外部输入的 generator：

  ```typescript theme={null}
  async function* fromUserUI(): AsyncGenerator<SDKUserMessage> {
    while (true) {
      const text = await waitForUserInput();   // 你的 UI 输入源
      yield {
        type: 'user',
        message: { role: 'user', content: [{ type: 'text', text }] },
        parent_tool_use_id: null,
      };
    }
  }
  ```

* 想在消息序列正常结束之前提前终止：超时、用户取消、其他业务条件。

两种关闭方式：

<div id="自动管理推荐node-22-或支持显式资源管理的运行时" />

### 自动管理（推荐，Node 22+ 或支持显式资源管理的运行时）

适合会话生命周期和某个函数 / 代码块一致的场景，离开作用域时自动释放。

```typescript theme={null}
{
  await using q = query({ prompt: fromUserUI(), options: { auth: qodercliAuth() } });
  for await (const msg of q) { /* ... */ }
}  // 离开作用域自动关闭
```

<div id="手动关闭" />

### 手动关闭

适合外部触发关闭的场景：超时、用户取消、其他业务条件。

```typescript theme={null}
const q = query({ prompt: fromUserUI(), options: { auth: qodercliAuth() } });
setTimeout(() => q.close(), 30_000);   // 30 秒后强制结束

for await (const msg of q) { /* ... */ }
```
