---
title: 状态与事件
description: 订阅执行事件、消费流式文本、监听工具进度与读取只读状态快照。
---

Agent 的执行过程是一个持续的状态机。为了支持平滑的 UI 渲染与进度感知，SDK 提供了确定性的同步事件订阅机制，同时维护只读的状态投影。

## 订阅机制

调用 `agent.subscribe()` 注册事件监听函数，方法返回值即为注销函数：

```ts
const unsubscribe = agent.subscribe((event: CodingAgentEvent) => {
  // 事件处理逻辑
});

// 在不需要监听时注销（例如组件卸载）
unsubscribe();
```

所有事件均以同构的 Discriminated Union 形式呈现，具有严格的类型推断支持。

## 核心事件全景

```ts
export type CodingAgentEvent =
  | { readonly type: "agent_start" }
  | { readonly type: "agent_end"; readonly messages: readonly CodingAgentMessage[] }
  | { readonly type: "turn_start" }
  | { readonly type: "turn_end"; readonly message: CodingAssistantMessage; readonly toolResults: readonly CodingToolResult[] }
  | { readonly type: "message_start"; readonly message: CodingAgentMessage }
  | { readonly type: "message_update"; readonly message: CodingAssistantMessage; readonly assistantEvent: AssistantEvent }
  | { readonly type: "message_end"; readonly message: CodingAgentMessage; readonly entryId?: string }
  | { readonly type: "message_discard" }
  | { readonly type: "tool_execution_start"; readonly toolCallId: string; readonly toolName: string; readonly activityKind: CodingToolActivityKind; readonly title: string; readonly args: JsonValue }
  | { readonly type: "tool_execution_update"; readonly toolCallId: string; readonly toolName: string; readonly activityKind: CodingToolActivityKind; readonly partial: JsonValue }
  | { readonly type: "tool_execution_end"; readonly toolCallId: string; readonly toolName: string; readonly activityKind: CodingToolActivityKind; readonly result: JsonValue; readonly isError: boolean }
  | { readonly type: "compaction_start"; readonly trigger: string; readonly tokensBefore: number }
  | { readonly type: "compaction_end"; readonly outcome: JsonValue }
  | { readonly type: "context_measured"; readonly measurement: CodingContextMeasurement }
  | { readonly type: "background_agent_end"; readonly toolCallId: string; readonly agentId: string; readonly title: string; readonly toolName?: string; readonly status: "complete" | "error" | "stopped" };
```

### 流式文本与思考过程（`message_update`）

在模型生成过程中，`message_update` 会高频触发。其内部的 `assistantEvent` 包含增量细节：

```ts
if (event.type === "message_update") {
  const sub = event.assistantEvent;
  switch (sub.type) {
    case "text_delta":
      // 常规正文 Token 增量
      renderToken(sub.contentIndex, sub.delta);
      break;
    case "thinking_delta":
      // 深度思考 / Reasoning Token 增量
      renderThinking(sub.contentIndex, sub.delta);
      break;
    case "toolcall_end":
      // 模型完成了一个工具调用参数的组装
      notifyToolCallReady(sub.toolCall);
      break;
  }
}
```

每个内容块携带唯一的 `contentIndex`，方便在复杂的多块输出（如交替出现的思考块、文本块与工具调用块）中正确定位。

### 工具执行生命周期

工具从调用到结束派发三阶段事件：

1. **`tool_execution_start`**：工具开始执行，携带 `toolName`、操作标题 `title`、分类 `activityKind`（如 `"read"`、`"execute"`、`"search"`）与参数。
2. **`tool_execution_update`**：长耗时工具（如终端持续输出、大文件读取）发送部分增量结果 `partial`。
3. **`tool_execution_end`**：工具执行完成，包含最终结果 `result` 与是否报错的标记 `isError`。

### 上下文测量（`context_measured`）

在每次向大模型发起调用前以及压缩完成后，SDK 会派发 `context_measured` 事件。它提供了当前上下文用量的估算细分（System Prompt、工具定义、历史消息、推理块各自占用的 Token 估算），可用于渲染会话窗口用量指示器。

## 状态快照（`agent.state`）

除了事件流之外，宿主可随时通过 `agent.state` 读取当前的不可变状态快照：

```ts
const { status, messages, artifacts, appState } = agent.state;
```

- `status`：`"idle"`（空闲就绪）、`"running"`（正在执行）、`"aborted"`（已中断）或 `"closed"`（已销毁）。
- `messages`：包含本会话全部有效对话条目的只读数组。
- `artifacts`：会话中生成或修改的代码文件产物索引。
- `appState`：宿主自定义挂载的应用状态数据。
