> ## 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.

# Run 生命周期

> 识别 runId、取消执行并处理断连与终态。

# 管理 Run 生命周期

每次 `POST /v1/agents/:agentId/runs` 执行都会被分配一个唯一的 `runId`（UUID），用于传输层标识。该 ID 通过以下方式暴露：

* 响应头 `X-Run-ID`（SSE 和 JSON 响应都有）
* SSE 初始 `system` 事件的 `runId` 字段
* JSON 响应体的 `runId` 字段

## 取消 run

要显式取消仍在运行的请求：

```http theme={null}
POST /v1/runs/:runId/cancel
```

响应码与响应体：

| 场景            | 状态码   | 响应体                                                     |
| ------------- | ----- | ------------------------------------------------------- |
| 已触发取消         | `202` | `{ runId, state: "cancelling" }`                        |
| 重复取消（幂等）      | `202` | `{ runId, state: "cancelling" \| "cancelled", reason }` |
| run 已处于非取消的终态 | `409` | `{ runId, state: "completed" \| "failed" }`             |
| 未知或已过期的 runId | `404` | `{ error: "Run not found" }`                            |

终态缓存 TTL 为 **5 分钟**，过期后重复取消返回 `404`。

## SSE 取消语义

当 run 被取消时（显式 API 调用或客户端断连），SSE 流依次发送 `cancelled` 与 `done` 事件：

```text theme={null}
event: cancelled
data: {"runId":"...","reason":"client_request|disconnect"}

event: done
data: {}
```

* `reason=client_request`：显式调用 `POST /v1/runs/:runId/cancel`。
* `reason=disconnect`：SSE 客户端断开连接。

<Warning>客户端断连等同于静默取消：关闭 SSE 连接会中止底层 Agent 执行。Runtime 不区分“主动取消”和“网络中断”，两者都会停止 run，以避免浪费 token。</Warning>

## 范围边界

该 API 属于传输层能力。Runtime **不提供**：

* 持久化的 Run 历史记录（请使用外部编排器）
* 重试或故障转移策略
* 可持久化的事件回放（不支持中途重连）
* GET 状态端点（终态通过响应本身传达）

## 关停语义

进程关停时的排空由包装 Runtime 进程的外部编排器（例如 agent-deployer）调用 `RunRegistry.closeAll()`，在收到 SIGTERM 时排空进行中的 run。Runtime 自身不安装信号处理器——容器级 SIGTERM/KILL 由编排器负责。
