# 流式处理会话事件

Copilot 代理执行的每个操作——思考、编写代码、运行工具——都会以 session 事件 的形式发出，供你订阅。 本指南是每个事件类型的字段级参考，因此你确切地知道在未读取 SDK 源的情况下预期的数据。

<!-- markdownlint-disable GHD046 GHD005 -->

<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->

## 概述

对会话设置 `streaming: true` 时，SDK 会实时发出**临时**事件（增量、进度更新）以及**持久**事件（完整的消息、工具结果）。 所有事件共享一个公用信封，并携带一个载荷，其形状取决于事件 `data`。

![关系图：显示描述的过程的序列图。](/assets/images/help/copilot/copilot-sdk/features-streaming-events-diagram-0.png)

| 概念               | Description                              |
| ---------------- | ---------------------------------------- |
| **临时事件**         | 瞬时; 实时流传，但不持久保存到会话日志。 会话恢复时未重播。          |
| **持久化事件**        | 保存到磁盘上的会话事件日志。 恢复会话时重播。                  |
| **Delta 事件**     | 临时流式处理块（文本或推理）。 累积增量以生成完整内容。             |
| **`parentId` 链** | 每个事件的 `parentId` 都指向上一个事件，形成一个可以遍历的链接列表。 |

## 事件封装

无论类型如何，每个会话事件都包含以下字段：

| 领域                  | 类型               | Description                           |
| ------------------- | ---------------- | ------------------------------------- |
| `id`                |                  |                                       |
| `string` （UUID v4）  | 唯一事件标识符          |                                       |
| `timestamp`         |                  |                                       |
| `string` （ISO 8601） | 创建事件时            |                                       |
| `parentId`          | `string \| null` | 链中上一个事件的 ID；对于第一个事件使用 `null`          |
| `ephemeral`         | `boolean?`       | `true`（适用于临时事件）；缺失或 `false`（适用于持久化事件） |
| `type`              | `string`         | 事件类型鉴别器（请参阅下表）                        |
| `data`              | `object`         | 特定于事件的有效负载                            |

## 订阅事件

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
// All events
session.on((event) => {
    console.log(event.type, event.data);
});

// Specific event type — data is narrowed automatically
session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
from copilot import CopilotClient
from copilot.generated.session_events import SessionEventType

client = CopilotClient()

session = None  # assume session is created elsewhere

def handle(event):
    if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
        print(event.data.delta_content, end="", flush=True)

# session.on(handle)
```

```python
from copilot.generated.session_events import SessionEventType

def handle(event):
    if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
        print(event.data.delta_content, end="", flush=True)

session.on(handle)
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
package main

import (
    "context"
    "fmt"
    copilot "github.com/github/copilot-sdk/go"
    "github.com/github/copilot-sdk/go/rpc"
)

func main() {
    ctx := context.Background()
    client := copilot.NewClient(nil)

    session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
        Model:     "gpt-4.1",
        Streaming: copilot.Bool(true),
        OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) {
            return &rpc.PermissionDecisionApproveOnce{}, nil
        },
    })

    session.On(func(event copilot.SessionEvent) {
        if d, ok := event.Data.(*copilot.AssistantMessageDeltaData); ok {
            fmt.Print(d.DeltaContent)
        }
    })
    _ = session
}
```

```golang
session.On(func(event copilot.SessionEvent) {
    if d, ok := event.Data.(*copilot.AssistantMessageDeltaData); ok {
        fmt.Print(d.DeltaContent)
    }
})
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
using GitHub.Copilot;

public static class StreamingEventsExample
{
    public static async Task Example(CopilotSession session)
    {
        session.On<SessionEvent>(evt =>
        {
            if (evt is AssistantMessageDeltaEvent delta)
            {
                Console.Write(delta.Data.DeltaContent);
            }
        });
    }
}
```

```csharp
session.On<SessionEvent>(evt =>
{
    if (evt is AssistantMessageDeltaEvent delta)
    {
        Console.Write(delta.Data.DeltaContent);
    }
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
// All events
session.on(event -> System.out.println(event.getType()));

// Specific event type — data is narrowed to the matching class
session.on(AssistantMessageDeltaEvent.class, event ->
    System.out.print(event.getData().deltaContent())
);
```

</div>

</div>

> \[!TIP]
> **（Python/Go）** 这些 SDK 将所有可能的字段用作可选/可为 null 的单个 `Data` 类/结构。 只有下表中列出的字段会针对每个事件类型进行填充，其余字段会保持为`None` / `nil`。
>
> \[!TIP]
> **（.NET）** .NET SDK 为每个事件使用单独的强类型数据类（例如，`AssistantMessageDeltaData`），因此每个类型上仅存在相关字段。
>
> \[!TIP]
> **(TypeScript)** TypeScript SDK 使用可区分的联合 - 当你根据 `event.type` 匹配时，`data` 有效负载会自动缩小到正确的形状。

## 助理活动

这些事件会跟踪代理的响应生命周期 - 从轮次开始，经过流式处理块，直到最终消息。

### `assistant.turn_start`

代理开始处理轮次时已发出。

| 数据字段               | 类型       | 必需 | Description         |
| ------------------ | -------- | -- | ------------------- |
| `turnId`           | `string` | ✅  | 轮次标识符（通常是字符串化的轮次编号） |
| `interactionId`    | `string` |    |                     |
| 用于遥测关联的 CAPI 交互 ID |          |    |                     |

### `assistant.intent`

短暂。 代理当前正在执行的操作的简短描述，随着其工作的进行而更新。

| 数据字段     | 类型       | 必需 | Description        |
| -------- | -------- | -- | ------------------ |
| `intent` | `string` | ✅  | 人类可读的意图（例如“浏览代码库”） |

### `assistant.reasoning`

从模型中得出完整的扩展思维定式。 推理完成后发出。

| 数据字段          | 类型       | 必需 | Description |
| ------------- | -------- | -- | ----------- |
| `reasoningId` | `string` | ✅  | 此推理块的唯一标识符  |
| `content`     | `string` | ✅  | 完整的扩展思维文本   |

### `assistant.reasoning_delta`

短暂。 实时流式处理的模型扩展思维增量区块。

| 数据字段           | 类型       | 必需 | Description                    |
| -------------- | -------- | -- | ------------------------------ |
| `reasoningId`  | `string` | ✅  | 匹配相应的 `assistant.reasoning` 事件 |
| `deltaContent` | `string` | ✅  | 要附加到推理内容的文本区块                  |

### `assistant.message`

此 LLM 调用的助手完整响应。 可能包括工具调用请求。

| 数据字段                                   | 类型              | 必需 | Description |
| -------------------------------------- | --------------- | -- | ----------- |
| `messageId`                            | `string`        | ✅  | 此消息的唯一标识符   |
| `content`                              | `string`        | ✅  | 助手的文本响应     |
| `toolRequests`                         | `ToolRequest[]` |    |             |
| 助理拟进行的工具调用（请参阅下文）                      |                 |    |             |
| `reasoningOpaque`                      | `string`        |    |             |
| 加密扩展思维（人类模型）：会话绑定                      |                 |    |             |
| `reasoningText`                        | `string`        |    |             |
| 扩展思维中的可读推理文本                           |                 |    |             |
| `encryptedContent`                     | `string`        |    |             |
| 加密推理内容（OpenAI 模型）：会话绑定                 |                 |    |             |
| `phase`                                | `string`        |    |             |
| 生成阶段（例如， `"thinking"` vs `"response"`） |                 |    |             |
| `outputTokens`                         | `number`        |    |             |
| 来自 API 响应的实际输出令牌计数                     |                 |    |             |
| `interactionId`                        | `string`        |    |             |
| 用于遥测的 CAPI 交互 ID                       |                 |    |             |
| `parentToolCallId`                     | `string`        |    |             |
| 当此消息源自子代理时进行设置                         |                 |    |             |

\*\*
`ToolRequest` 领域：\*\*

| 领域                        | 类型                       | 必需 | Description                            |
| ------------------------- | ------------------------ | -- | -------------------------------------- |
| `toolCallId`              | `string`                 | ✅  | 此工具调用的唯一 ID                            |
| `name`                    | `string`                 | ✅  | 工具名称（例如， `"bash"`、 `"edit"`、 `"grep"`） |
| `arguments`               | `object`                 |    |                                        |
| 用于工具的解析参数                 |                          |    |                                        |
| `type`                    | `"function" \| "custom"` |    |                                        |
| 调用类型；如果缺失，默认为`"function"` |                          |    |                                        |

### `assistant.message_delta`

短暂。 实时流式处理的助理文本响应的增量区块。

| 数据字段               | 类型       | 必需 | Description                  |
| ------------------ | -------- | -- | ---------------------------- |
| `messageId`        | `string` | ✅  | 匹配相应的 `assistant.message` 事件 |
| `deltaContent`     | `string` | ✅  | 要追加到消息的文本片段                  |
| `parentToolCallId` | `string` |    |                              |
| 当由子代理发起时设定         |          |    |                              |

### `assistant.turn_end`

代理完成轮次时发出（所有工具执行完成，最终响应已传递）。

| 数据字段     | 类型       | 必需 | Description                     |
| -------- | -------- | -- | ------------------------------- |
| `turnId` | `string` | ✅  | 匹配相应的 `assistant.turn_start` 事件 |

### `assistant.usage`

短暂。 单个 API 调用的令牌使用情况和成本信息。

| 数据字段                                     | 类型                                                                         | 必需 | Description           |
| ---------------------------------------- | -------------------------------------------------------------------------- | -- | --------------------- |
| `model`                                  | `string`                                                                   | ✅  | 模型标识符（例如 `"gpt-4.1"`） |
| `inputTokens`                            | `number`                                                                   |    |                       |
| 消耗的输入令牌                                  |                                                                            |    |                       |
| `outputTokens`                           | `number`                                                                   |    |                       |
| 生成的输出令牌                                  |                                                                            |    |                       |
| `cacheReadTokens`                        | `number`                                                                   |    |                       |
| 从提示缓存中读取的令牌                              |                                                                            |    |                       |
| `cacheWriteTokens`                       | `number`                                                                   |    |                       |
| 写入提示缓存的令牌                                |                                                                            |    |                       |
| `cost`                                   | `number`                                                                   |    |                       |
| 计费的模型乘数成本                                |                                                                            |    |                       |
| `duration`                               | `number`                                                                   |    |                       |
| API 调用持续时间（以毫秒为单位）                       |                                                                            |    |                       |
| `initiator`                              | `string`                                                                   |    |                       |
| 触发此次调用的原因（例如 `"sub-agent"`）；如果是用户发起的，则为空 |                                                                            |    |                       |
| `apiCallId`                              | `string`                                                                   |    |                       |
| 提供程序的完成 ID（例如 `chatcmpl-abc123`）         |                                                                            |    |                       |
| `apiEndpoint`                            | `"/chat/completions" \| "/v1/messages" \| "/responses" \| "ws:/responses"` |    |                       |
| 用于模型调用的 API 终结点;对于可观测性和成本归因非常有用。         |                                                                            |    |                       |
| `ws:/responses` 是响应 API 的 Websocket 变体   |                                                                            |    |                       |
| `providerCallId`                         | `string`                                                                   |    |                       |
| GitHub请求跟踪 ID （`x-github-request-id`）    |                                                                            |    |                       |
| `parentToolCallId`                       | `string`                                                                   |    |                       |
| 当使用情况源自子代理时进行设置                          |                                                                            |    |                       |
| `quotaSnapshots`                         | `Record<string, QuotaSnapshot>`                                            |    |                       |
| 按配额标识符记录的每个配额的资源使用情况                     |                                                                            |    |                       |
| `copilotUsage`                           | `CopilotUsage`                                                             |    |                       |
| API 中的分项令牌成本明细                           |                                                                            |    |                       |

### `assistant.streaming_delta`

短暂。 低级别网络进度指示器 - 从流式处理 API 响应接收的总字节数。

| 数据字段                     | 类型       | 必需 | Description   |
| ------------------------ | -------- | -- | ------------- |
| `totalResponseSizeBytes` | `number` | ✅  | 到目前为止收到的累积字节数 |

## 工具执行事件

这些事件跟踪每个工具调用的完整生命周期，从模型请求工具调用到执行和结束。

### `tool.execution_start`

当工具开始执行时发出。

| 数据字段                      | 类型       | 必需 | Description                          |
| ------------------------- | -------- | -- | ------------------------------------ |
| `toolCallId`              | `string` | ✅  | 此工具调用的唯一标识符                          |
| `toolName`                | `string` | ✅  | 工具的名称（例如，`"bash"`， `"edit"``"grep"`） |
| `arguments`               | `object` |    |                                      |
| 传递给工具的已分析参数               |          |    |                                      |
| `mcpServerName`           | `string` |    |                                      |
| MCP 服务器名称，当 MCP 服务器提供该工具时 |          |    |                                      |
| `mcpToolName`             | `string` |    |                                      |
| MCP 服务器上的原始工具名称           |          |    |                                      |
| `parentToolCallId`        | `string` |    |                                      |
| 在子代理调用时设置                 |          |    |                                      |

### `tool.execution_partial_result`

短暂。 运行中工具的增量输出（例如 bash 的流式输出）。

| 数据字段            | 类型       | 必需 | Description                  |
| --------------- | -------- | -- | ---------------------------- |
| `toolCallId`    | `string` | ✅  | 匹配相应的 `tool.execution_start` |
| `partialOutput` | `string` | ✅  | 增量输出区块                       |

### `tool.execution_progress`

短暂。 由运行中的工具提供的人类可读的进度状态（例如 MCP 服务器进度通知）。

| 数据字段              | 类型       | 必需 | Description                  |
| ----------------- | -------- | -- | ---------------------------- |
| `toolCallId`      | `string` | ✅  | 匹配相应的 `tool.execution_start` |
| `progressMessage` | `string` | ✅  | 进度状态消息                       |

### `tool.execution_complete`

当工具完成执行时发出 — 成功或出错。

| 数据字段                      | 类型                   | 必需 | Description                  |
| ------------------------- | -------------------- | -- | ---------------------------- |
| `toolCallId`              | `string`             | ✅  | 匹配相应的 `tool.execution_start` |
| `success`                 | `boolean`            | ✅  | 执行是否成功                       |
| `model`                   | `string`             |    |                              |
| 生成此工具调用的模型                |                      |    |                              |
| `interactionId`           | `string`             |    |                              |
| CAPI 交互标识                 |                      |    |                              |
| `isUserRequested`         | `boolean`            |    |                              |
|                           |                      |    |                              |
| `true` 当用户显式请求此工具调用时      |                      |    |                              |
| `result`                  | `Result`             |    |                              |
| 成功时显示（请参阅下文）              |                      |    |                              |
| `error`                   | `{ message, code? }` |    |                              |
| 失败时显示                     |                      |    |                              |
| `toolTelemetry`           | `object`             |    |                              |
| 工具特定的遥测数据（例如，CodeQL 检查次数） |                      |    |                              |
| `parentToolCallId`        | `string`             |    |                              |
| 在子代理调用时设置                 |                      |    |                              |

\*\*
`Result` 领域：\*\*

| 领域                     | 类型               | 必需 | Description              |
| ---------------------- | ---------------- | -- | ------------------------ |
| `content`              | `string`         | ✅  | 发送给 LLM 的简明结果（可能为令牌效率截断） |
| `detailedContent`      | `string`         |    |                          |
| 显示的完整结果，保留差异等完整内容      |                  |    |                          |
| `contents`             | `ContentBlock[]` |    |                          |
| 结构化内容块（文本、终端、图像、音频、资源） |                  |    |                          |

### `tool.user_requested`

当用户显式请求工具调用（而不是由模型选择调用时）发出。

| 数据字段         | 类型       | 必需 | Description |
| ------------ | -------- | -- | ----------- |
| `toolCallId` | `string` | ✅  | 此工具调用的唯一标识符 |
| `toolName`   | `string` | ✅  | 用户要调用的工具的名称 |
| `arguments`  | `object` |    |             |
| 函数调用的参数      |          |    |             |

## 会话生命周期事件

### `session.idle`

短暂。 代理已完成所有处理，并已准备好下一条消息。 这是转弯已完全完成的信号。

| 数据字段                    | 类型                | 必需 | Description |
| ----------------------- | ----------------- | -- | ----------- |
| `backgroundTasks`       | `BackgroundTasks` |    |             |
| 后台代理/shell 在代理变得空闲时仍在运行 |                   |    |             |

### `session.error`

会话处理期间出错。

| 数据字段                       | 类型       | 必需 | Description                                           |
| -------------------------- | -------- | -- | ----------------------------------------------------- |
| `errorType`                | `string` | ✅  | 错误类别（例如，`"authentication"`、、 `"quota"``"rate_limit"`） |
| `message`                  | `string` | ✅  | 用户可读的错误消息                                             |
| `stack`                    | `string` |    |                                                       |
| 错误堆栈跟踪                     |          |    |                                                       |
| `statusCode`               | `number` |    |                                                       |
| 来自上游请求的 HTTP 状态代码          |          |    |                                                       |
| `providerCallId`           | `string` |    |                                                       |
| 用于服务器端日志关联的 GitHub 请求跟踪 ID |          |    |                                                       |

### `session.compaction_start`

上下文窗口压缩已经开始。
**数据有效负载为空 （`{}`）** 。

### `session.compaction_complete`

上下文窗口压缩已完成。

| 数据字段                          | 类型                               | 必需 | Description |
| ----------------------------- | -------------------------------- | -- | ----------- |
| `success`                     | `boolean`                        | ✅  | 压缩是否成功      |
| `error`                       | `string`                         |    |             |
| 压缩失败时出现错误消息                   |                                  |    |             |
| `preCompactionTokens`         | `number`                         |    |             |
| 压缩前的令牌                        |                                  |    |             |
| `postCompactionTokens`        | `number`                         |    |             |
| 压缩后的令牌                        |                                  |    |             |
| `preCompactionMessagesLength` | `number`                         |    |             |
| 压缩前的消息计数                      |                                  |    |             |
| `messagesRemoved`             | `number`                         |    |             |
| 已删除邮件                         |                                  |    |             |
| `tokensRemoved`               | `number`                         |    |             |
| 已删除令牌                         |                                  |    |             |
| `summaryContent`              | `string`                         |    |             |
| LLM 生成的压缩历史记录摘要               |                                  |    |             |
| `checkpointNumber`            | `number`                         |    |             |
| 为恢复创建的检查点快照编号                 |                                  |    |             |
| `checkpointPath`              | `string`                         |    |             |
| 存储检查点的文件路径                    |                                  |    |             |
| `compactionTokensUsed`        | `{ input, output, cachedInput }` |    |             |
| 压缩LLM调用中的令牌使用情况               |                                  |    |             |
| `requestId`                   | `string`                         |    |             |
| GitHub 请求跟踪 ID（用于压缩调用）        |                                  |    |             |

### `session.title_changed`

短暂。 会话自动生成的标题已更新。

| 数据字段    | 类型       | 必需 | Description |
| ------- | -------- | -- | ----------- |
| `title` | `string` | ✅  | 新会话标题       |

### `session.context_changed`

会话的工作目录或存储库上下文已更改。

| 数据字段                  | 类型       | 必需 | Description |
| --------------------- | -------- | -- | ----------- |
| `cwd`                 | `string` | ✅  | 当前工作目录      |
| `gitRoot`             | `string` |    |             |
| Git 存储库根目录            |          |    |             |
| `repository`          | `string` |    |             |
|                       |          |    |             |
| `"owner/name"` 格式的存储库 |          |    |             |
| `branch`              | `string` |    |             |
| 当前 Git 分支             |          |    |             |

### `session.usage_info`

短暂。 上下文窗口利用率快照。

| 数据字段             | 类型       | 必需 | Description   |
| ---------------- | -------- | -- | ------------- |
| `tokenLimit`     | `number` | ✅  | 模型上下文窗口的最大标记数 |
| `currentTokens`  | `number` | ✅  | 上下文窗口中的当前标记   |
| `messagesLength` | `number` | ✅  | 对话中的当前消息计数    |

### `session.task_complete`

代理已完成其分配的任务。

| 数据字段      | 类型       | 必需 | Description |
| --------- | -------- | -- | ----------- |
| `summary` | `string` |    |             |
| 已完成任务的摘要  |          |    |             |

### `session.shutdown`

会话已结束。

| 数据字段                              | 类型                                            | 必需 | Description          |
| --------------------------------- | --------------------------------------------- | -- | -------------------- |
| `shutdownType`                    | `"routine" \| "error"`                        | ✅  | 正常关闭或崩溃              |
| `errorReason`                     | `string`                                      |    |                      |
|                                   |                                               |    |                      |
| `shutdownType` 为 `"error"` 时的错误描述 |                                               |    |                      |
| `totalPremiumRequests`            | `number`                                      | ✅  | 使用的高级 API 请求总数       |
| `totalApiDurationMs`              | `number`                                      | ✅  | 累积 API 调用时间（以毫秒为单位）  |
| `sessionStartTime`                | `number`                                      | ✅  | 会话启动时的 Unix 时间戳 （ms） |
| `codeChanges`                     | `{ linesAdded, linesRemoved, filesModified }` | ✅  | 代码更改的聚合指标            |
| `modelMetrics`                    | `Record<string, ModelMetric>`                 | ✅  | 按模型使用情况细分            |
| `currentModel`                    | `string`                                      |    |                      |
| 关闭时选择的模型                          |                                               |    |                      |

## 权限和用户输入事件

在继续操作之前，当代理需要用户批准或输入时，将发出这些事件。

### `permission.requested`

短暂。 代理需要权限才能执行操作（运行命令、写入文件等）。

| 数据字段                | 类型                  | 必需 | Description                                  |
| ------------------- | ------------------- | -- | -------------------------------------------- |
| `requestId`         | `string`            | ✅  | 使用该功能通过 `session.respondToPermission()` 进行响应 |
| `permissionRequest` | `PermissionRequest` | ✅  | 正在请求的权限的详细信息                                 |

`permissionRequest` 是 `kind` 上的可区分联合：

| `kind`                                                       | 关键字段        | Description |
| ------------------------------------------------------------ | ----------- | ----------- |
| `"shell"`                                                    |             |             |
| `fullCommandText`、`intention`、`commands[]`、`possiblePaths[]` | 执行 shell 命令 |             |
| `"write"`                                                    |             |             |
| `fileName`、`diff`、`intention`、`newFileContents?`             | 写入/修改文件     |             |
| `"read"`                                                     |             |             |
| `path`、`intention`                                           | 读取文件或目录     |             |
| `"mcp"`                                                      |             |             |
| `serverName`、`toolName`、`toolTitle`、`args?`、`readOnly`       | 调用 MCP 工具   |             |
| `"url"`                                                      |             |             |
| `url`、`intention`                                            | 获取 URL      |             |
| `"memory"`                                                   |             |             |
| `subject`、`fact`、`citations`                                 | 存储记忆        |             |
| `"custom-tool"`                                              |             |             |
| `toolName`、`toolDescription`、`args?`                         | 调用自定义工具     |             |

所有 `kind` 变体均包含一个可选的 `toolCallId` 链接，其指向触发请求的工具调用。

### `permission.completed`

短暂。 权限请求已解决。

| 数据字段          | 类型       | 必需 | Description                                                                                                                                                               |
| ------------- | -------- | -- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `requestId`   | `string` | ✅  | 匹配相应的 `permission.requested`                                                                                                                                              |
| `result.kind` | `string` | ✅  | 其中之一：`"approved"`、、`"denied-by-rules"``"denied-interactively-by-user"`、`"denied-no-approval-rule-and-could-not-request-from-user"`、`"denied-by-content-exclusion-policy"` |

### `user_input.requested`

短暂。 代理正在向用户提问。

| 数据字段            | 类型         | 必需 | Description                                 |
| --------------- | ---------- | -- | ------------------------------------------- |
| `requestId`     | `string`   | ✅  | 使用该功能通过 `session.respondToUserInput()` 进行响应 |
| `question`      | `string`   | ✅  | 向用户呈现的问题                                    |
| `choices`       | `string[]` |    |                                             |
| 用户的预定义选项        |            |    |                                             |
| `allowFreeform` | `boolean`  |    |                                             |
| 是否允许自由格式文本输入    |            |    |                                             |

### `user_input.completed`

短暂。 解决了用户输入请求。

| 数据字段        | 类型       | 必需 | Description                  |
| ----------- | -------- | -- | ---------------------------- |
| `requestId` | `string` | ✅  | 匹配相应的 `user_input.requested` |

### `elicitation.requested`

短暂。 代理需要用户（MCP 引证协议）的结构化表单输入。

| 数据字段               | 类型                                          | 必需 | Description                                   |
| ------------------ | ------------------------------------------- | -- | --------------------------------------------- |
| `requestId`        | `string`                                    | ✅  | 使用该功能通过 `session.respondToElicitation()` 进行响应 |
| `message`          | `string`                                    | ✅  | 所需信息的说明                                       |
| `mode`             | `"form"`                                    |    |                                               |
| 启发模式（当前仅 `"form"`） |                                             |    |                                               |
| `requestedSchema`  | `{ type: "object", properties, required? }` | ✅  | 描述窗体字段的 JSON 架构                               |

### `elicitation.completed`

短暂。 启发请求已解决。

| 数据字段        | 类型       | 必需 | Description                   |
| ----------- | -------- | -- | ----------------------------- |
| `requestId` | `string` | ✅  | 匹配相应的 `elicitation.requested` |

## 子代理和技能事件

### `subagent.started`

自定义代理被调用为子代理。

| 数据字段               | 类型       | 必需 | Description  |
| ------------------ | -------- | -- | ------------ |
| `toolCallId`       | `string` | ✅  | 生成此子代理的父工具调用 |
| `agentName`        | `string` | ✅  | 子代理的内部名称     |
| `agentDisplayName` | `string` | ✅  | 人工可读的显示名称    |
| `agentDescription` | `string` | ✅  | 子代理的作用说明     |

### `subagent.completed`

子代理成功完成。

| 数据字段               | 类型       | 必需 | Description              |
| ------------------ | -------- | -- | ------------------------ |
| `toolCallId`       | `string` | ✅  | 匹配相应的 `subagent.started` |
| `agentName`        | `string` | ✅  | 内部名称                     |
| `agentDisplayName` | `string` | ✅  | 显示名称                     |

### `subagent.failed`

子代理遇到错误。

| 数据字段               | 类型       | 必需 | Description              |
| ------------------ | -------- | -- | ------------------------ |
| `toolCallId`       | `string` | ✅  | 匹配相应的 `subagent.started` |
| `agentName`        | `string` | ✅  | 内部名称                     |
| `agentDisplayName` | `string` | ✅  | 显示名称                     |
| `error`            | `string` | ✅  | 错误消息                     |

### `subagent.selected`

已选择自定义代理（推断）来处理当前请求。

| 数据字段               | 类型                 | 必需 | Description                |
| ------------------ | ------------------ | -- | -------------------------- |
| `agentName`        | `string`           | ✅  | 所选代理的内部名称                  |
| `agentDisplayName` | `string`           | ✅  | 显示名称                       |
| `tools`            | `string[] \| null` | ✅  | 此代理可用的工具名称; `null` 适用于所有工具 |

### `subagent.deselected`

取消了自定义代理的选择，返回到默认代理。
**数据有效负载为空 （`{}`）** 。

### `skill.invoked`

为当前对话激活了技能。

| 数据字段              | 类型         | 必需 | Description      |
| ----------------- | ---------- | -- | ---------------- |
| `name`            | `string`   | ✅  | 技能名称             |
| `path`            | `string`   | ✅  | SKILL.md 定义的文件路径 |
| `content`         | `string`   | ✅  | 将完整的技能内容注入到对话中   |
| `allowedTools`    | `string[]` |    |                  |
| 此技能处于活动状态时自动批准的工具 |            |    |                  |
| `pluginName`      | `string`   |    |                  |
| 技能的来源插件           |            |    |                  |
| `pluginVersion`   | `string`   |    |                  |
| 插件版本              |            |    |                  |

## 其他事件

### `abort`

当前轮次已中止。

| 数据字段     | 类型       | 必需 | Description                       |
| -------- | -------- | -- | --------------------------------- |
| `reason` | `string` | ✅  | 为什么轮次被中止 （例如， `"user initiated"`） |

### `user.message`

用户发送了一条消息。 已针对会话时间线进行记录。

| 数据字段                                                  | 类型             | 必需 | Description |
| ----------------------------------------------------- | -------------- | -- | ----------- |
| `content`                                             | `string`       | ✅  | 用户的消息内容     |
| `transformedContent`                                  | `string`       |    |             |
| 预处理后的转换版本                                             |                |    |             |
| `attachments`                                         | `Attachment[]` |    |             |
| 文件、目录、选定内容、Blob 或 GitHub 引用附件                         |                |    |             |
| `source`                                              | `string`       |    |             |
| 消息源标识符                                                |                |    |             |
| `agentMode`                                           | `string`       |    |             |
| 代理模式：`"interactive"`、、`"plan"``"autopilot"`或`"shell"` |                |    |             |
| `interactionId`                                       | `string`       |    |             |
| CAPI 交互标识                                             |                |    |             |

### `system.message`

系统或开发人员提示已注入对话。

| 数据字段       | 类型                               | 必需 | Description |
| ---------- | -------------------------------- | -- | ----------- |
| `content`  | `string`                         | ✅  | 提示文本        |
| `role`     | `"system" \| "developer"`        | ✅  | 消息角色        |
| `name`     | `string`                         |    |             |
| 源标识符       |                                  |    |             |
| `metadata` | `{ promptVersion?, variables? }` |    |             |
| 提示模板元数据    |                                  |    |             |

### `external_tool.requested`

短暂。 代理想要调用外部工具（由 SDK 使用者提供）。

| 数据字段         | 类型       | 必需 | Description                                    |
| ------------ | -------- | -- | ---------------------------------------------- |
| `requestId`  | `string` | ✅  | 使用该功能通过 `session.respondToExternalTool()` 进行响应 |
| `sessionId`  | `string` | ✅  | 此请求所属的会话                                       |
| `toolCallId` | `string` | ✅  | 此调用的工具 ID                                      |
| `toolName`   | `string` | ✅  | 外部工具的名称                                        |
| `arguments`  | `object` |    |                                                |
| 工具参数         |          |    |                                                |

### `external_tool.completed`

短暂。 解决了外部工具请求。

| 数据字段        | 类型       | 必需 | Description                     |
| ----------- | -------- | -- | ------------------------------- |
| `requestId` | `string` | ✅  | 匹配相应的 `external_tool.requested` |

### `exit_plan_mode.requested`

短暂。 代理已创建计划并想要退出计划模式。

| 数据字段                | 类型         | 必需 | Description                                    |
| ------------------- | ---------- | -- | ---------------------------------------------- |
| `requestId`         | `string`   | ✅  | 使用该功能通过 `session.respondToExitPlanMode()` 进行响应 |
| `summary`           | `string`   | ✅  | 计划摘要                                           |
| `planContent`       | `string`   | ✅  | 完整计划文件内容                                       |
| `actions`           | `string[]` | ✅  | 可用的用户操作（例如批准、编辑、拒绝）                            |
| `recommendedAction` | `string`   | ✅  | 建议的操作                                          |

### `exit_plan_mode.completed`

短暂。 已解决退出计划模式请求。

| 数据字段        | 类型       | 必需 | Description                      |
| ----------- | -------- | -- | -------------------------------- |
| `requestId` | `string` | ✅  | 匹配相应的 `exit_plan_mode.requested` |

### `command.queued`

短暂。 斜杠命令已排队执行。

| 数据字段        | 类型       | 必需 | Description                                     |
| ----------- | -------- | -- | ----------------------------------------------- |
| `requestId` | `string` | ✅  | 使用该功能通过 `session.respondToQueuedCommand()` 进行响应 |
| `command`   | `string` | ✅  | 斜杠命令文本（例如， `/help``/clear`）                     |

### `command.completed`

短暂。 排队的命令已解决。

| 数据字段        | 类型       | 必需 | Description            |
| ----------- | -------- | -- | ---------------------- |
| `requestId` | `string` | ✅  | 匹配相应的 `command.queued` |

## 快速参考：智能回合流程

典型的代理行为轮次按以下顺序触发事件：

```text
assistant.turn_start          → Turn begins
├── assistant.intent          → What the agent plans to do (ephemeral)
├── assistant.reasoning_delta → Streaming thinking chunks (ephemeral, repeated)
├── assistant.reasoning       → Complete thinking block
├── assistant.message_delta   → Streaming response chunks (ephemeral, repeated)
├── assistant.message         → Complete response (may include toolRequests)
├── assistant.usage           → Token usage for this API call (ephemeral)
│
├── [If tools were requested:]
│   ├── permission.requested  → Needs user approval (ephemeral)
│   ├── permission.completed  → Approval result (ephemeral)
│   ├── tool.execution_start  → Tool begins
│   ├── tool.execution_partial_result  → Streaming tool output (ephemeral, repeated)
│   ├── tool.execution_progress        → Progress updates (ephemeral, repeated)
│   ├── tool.execution_complete        → Tool finished
│   │
│   └── [Agent loops: more reasoning → message → tool calls...]
│
assistant.turn_end            → Turn complete
session.idle                  → Ready for next message (ephemeral)
```

## 所有事件类型一目了然

| 事件类型                                                                      | 临时         | 类别      | 关键数据字段                   |
| ------------------------------------------------------------------------- | ---------- | ------- | ------------------------ |
| `assistant.turn_start`                                                    |            |         |                          |
| 助手                                                                        |            |         |                          |
| `turnId`、`interactionId?`                                                 |            |         |                          |
| `assistant.intent`                                                        | ✅          | 助手      | `intent`                 |
| `assistant.reasoning`                                                     |            |         |                          |
| 助手                                                                        |            |         |                          |
| `reasoningId`、`content`                                                   |            |         |                          |
| `assistant.reasoning_delta`                                               | ✅          | 助手      |                          |
| `reasoningId`、`deltaContent`                                              |            |         |                          |
| `assistant.streaming_delta`                                               | ✅          | 助手      | `totalResponseSizeBytes` |
| `assistant.message`                                                       |            |         |                          |
| 助手                                                                        |            |         |                          |
| `messageId`、`content`、`toolRequests?`、`outputTokens?`、`phase?`            |            |         |                          |
| `assistant.message_delta`                                                 | ✅          | 助手      |                          |
| `messageId`、`deltaContent`、`parentToolCallId?`                            |            |         |                          |
| `assistant.turn_end`                                                      |            |         |                          |
| 助手                                                                        | `turnId`   |         |                          |
| `assistant.usage`                                                         | ✅          | 助手      |                          |
| `model`、`apiEndpoint?`、`inputTokens?`、`outputTokens?`、`cost?`、`duration?` |            |         |                          |
| `tool.user_requested`                                                     |            |         |                          |
| 工具                                                                        |            |         |                          |
| `toolCallId`、`toolName`、`arguments?`                                      |            |         |                          |
| `tool.execution_start`                                                    |            |         |                          |
| 工具                                                                        |            |         |                          |
| `toolCallId`、`toolName`、`arguments?`、`mcpServerName?`                     |            |         |                          |
| `tool.execution_partial_result`                                           | ✅          | 工具      |                          |
| `toolCallId`、`partialOutput`                                              |            |         |                          |
| `tool.execution_progress`                                                 | ✅          | 工具      |                          |
| `toolCallId`、`progressMessage`                                            |            |         |                          |
| `tool.execution_complete`                                                 |            |         |                          |
| 工具                                                                        |            |         |                          |
| `toolCallId`、`success`、`result?`、`error?`                                 |            |         |                          |
| `session.idle`                                                            | ✅          | Session | `backgroundTasks?`       |
| `session.error`                                                           |            |         |                          |
| Session                                                                   |            |         |                          |
| `errorType`、`message`、`statusCode?`                                       |            |         |                          |
| `session.compaction_start`                                                |            |         |                          |
| Session                                                                   |            |         |                          |
| *（空）*                                                                     |            |         |                          |
| `session.compaction_complete`                                             |            |         |                          |
| Session                                                                   |            |         |                          |
| `success`、`preCompactionTokens?`、`summaryContent?`                        |            |         |                          |
| `session.title_changed`                                                   | ✅          | Session | `title`                  |
| `session.context_changed`                                                 |            |         |                          |
| Session                                                                   |            |         |                          |
| `cwd`、`gitRoot?`、`repository?`、`branch?`                                  |            |         |                          |
| `session.usage_info`                                                      | ✅          | Session |                          |
| `tokenLimit`、`currentTokens`、`messagesLength`                             |            |         |                          |
| `session.task_complete`                                                   |            |         |                          |
| Session                                                                   | `summary?` |         |                          |
| `session.shutdown`                                                        |            |         |                          |
| Session                                                                   |            |         |                          |
| `shutdownType`、`codeChanges`、`modelMetrics`                               |            |         |                          |
| `permission.requested`                                                    | ✅          | 许可      |                          |
| `requestId`、`permissionRequest`                                           |            |         |                          |
| `permission.completed`                                                    | ✅          | 许可      |                          |
| `requestId`、`result.kind`                                                 |            |         |                          |
| `user_input.requested`                                                    | ✅          | 用户输入    |                          |
| `requestId`、`question`、`choices?`                                         |            |         |                          |
| `user_input.completed`                                                    | ✅          | 用户输入    | `requestId`              |
| `elicitation.requested`                                                   | ✅          | 用户输入    |                          |
| `requestId`、`message`、`requestedSchema`                                   |            |         |                          |
| `elicitation.completed`                                                   | ✅          | 用户输入    | `requestId`              |
| `subagent.started`                                                        |            |         |                          |
| 子代理                                                                       |            |         |                          |
| `toolCallId`、`agentName`、`agentDisplayName`                               |            |         |                          |
| `subagent.completed`                                                      |            |         |                          |
| 子代理                                                                       |            |         |                          |
| `toolCallId`、`agentName`、`agentDisplayName`                               |            |         |                          |
| `subagent.failed`                                                         |            |         |                          |
| 子代理                                                                       |            |         |                          |
| `toolCallId`、`agentName`、`error`                                          |            |         |                          |
| `subagent.selected`                                                       |            |         |                          |
| 子代理                                                                       |            |         |                          |
| `agentName`、`agentDisplayName`、`tools`                                    |            |         |                          |
| `subagent.deselected`                                                     |            |         |                          |
| 子代理                                                                       |            |         |                          |
| *（空）*                                                                     |            |         |                          |
| `skill.invoked`                                                           |            |         |                          |
| 技能                                                                        |            |         |                          |
| `name`、`path`、`content`、`allowedTools?`                                   |            |         |                          |
| `abort`                                                                   |            |         |                          |
| 控件                                                                        | `reason`   |         |                          |
| `user.message`                                                            |            |         |                          |
| User                                                                      |            |         |                          |
| `content`、`attachments?`、`agentMode?`                                     |            |         |                          |
| `system.message`                                                          |            |         |                          |
| 系统                                                                        |            |         |                          |
| `content`、`role`                                                          |            |         |                          |
| `external_tool.requested`                                                 | ✅          | 外部工具    |                          |
| `requestId`、`toolName`、`arguments?`                                       |            |         |                          |
| `external_tool.completed`                                                 | ✅          | 外部工具    | `requestId`              |
| `command.queued`                                                          | ✅          | 命令      |                          |
| `requestId`、`command`                                                     |            |         |                          |
| `command.completed`                                                       | ✅          | 命令      | `requestId`              |
| `exit_plan_mode.requested`                                                | ✅          | 计划模式    |                          |
| `requestId`、`summary`、`planContent`、`actions`                             |            |         |                          |
| `exit_plan_mode.completed`                                                | ✅          | 计划模式    | `requestId`              |