# 概览

Praxis 是智能体云平台。API 按服务组织：智能体、模型、沙箱、搜索、自动化，各在自己的前缀下。请求与响应用 JSON，流式响应用 SSE，使用标准的 HTTP 动词与状态码。所有前缀共用一个地址和一个 Key。

## 基础地址 [#基础地址]

```
https://api.deepraxis.com
```

## 客户端库 [#客户端库]

使用服务 API 页列出的客户端库。兼容接口使用对应协议的官方 SDK；自动化提供 TypeScript SDK，本地安装方式见[自动化 API](/docs/api/native/automation)。

| 服务  | 前缀            | API 页                                         |
| --- | ------------- | --------------------------------------------- |
| 智能体 | `/agent`      | [Agent API](/docs/api/native/agent)           |
| 模型  | `/model`      | [Model API](/docs/api/native/model)           |
| 沙箱  | `/sandbox`    | [Sandbox API](/docs/api/native/sandbox)       |
| 搜索  | `/search`     | [Search API](/docs/api/native/search)         |
| 自动化 | `/automation` | [Automation API](/docs/api/native/automation) |

## 兼容接口 [#兼容接口]

已经在用 OpenAI、Anthropic、Google、E2B 或 Tavily 的代码，不需要改成 Praxis 的接口：平台提供与这些厂商官方 API 一致的兼容前缀，只改地址就能用。

| 厂商        | 前缀           | API 页                                          |
| --------- | ------------ | ---------------------------------------------- |
| OpenAI    | `/openai`    | [OpenAI 兼容](/docs/api/compatible/openai)       |
| Anthropic | `/anthropic` | [Anthropic 兼容](/docs/api/compatible/anthropic) |
| Google    | `/google`    | [Google 兼容](/docs/api/compatible/google)       |
| E2B       | `/e2b`       | [E2B 兼容](/docs/api/compatible/e2b)             |
| Tavily    | `/tavily`    | [Tavily 兼容](/docs/api/compatible/tavily)       |

## 一个 Key [#一个-key]

所有前缀共用在控制台创建的 API Key，随请求放在 `Authorization` 头里。详见[鉴权](/docs/api/authentication)。

## 全局约定 [#全局约定]

* 错误用标准 HTTP 状态码表达类别，错误体按前缀的格式给出原因。详见[错误](/docs/api/errors)。
* 超出额度返回 `429`，响应头告诉你何时可以重试。详见[限流](/docs/api/rate-limits)。
* 版本号写在地址里，弃用提前 90 天以标准头通知。详见[版本](/docs/api/versioning)。
* 关于 API 本身的信息（OpenAPI 描述、健康状态）在 `/meta` 前缀下。

## 第一个请求 [#第一个请求]

```bash
curl https://api.deepraxis.com/model/v1/chat/completions \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "deepseek-flash", "messages": [{"role": "user", "content": "你好"}]}'
```

# 鉴权

所有接口用同一种凭证：在控制台创建的 API Key，随请求放在 `Authorization` 头里。没有别的鉴权方式，也没有按接口不同的规则。

## 一个头 [#一个头]

```
Authorization: Bearer {key}
```

| 段        | 含义                           | 例子                |
| -------- | ---------------------------- | ----------------- |
| `Bearer` | 固定字样                         | `Bearer`          |
| `{key}`  | 你的 API Key，以 `sk-praxis-` 开头 | `sk-praxis-a1b2…` |

一个 Key 通所有前缀下的接口。Key 在[控制台 → API Key](/docs/cloud/account/api-keys) 创建、轮换和吊销；吊销立即生效。

## 各家 SDK 把 Key 放在哪 [#各家-sdk-把-key-放在哪]

你不需要自己拼这个头——官方 SDK 会放；我们同时接受各家 SDK 默认使用的头名。

| SDK               | 你传什么     | 实际发出的头                    |
| ----------------- | -------- | ------------------------- |
| OpenAI SDK        | `apiKey` | `Authorization: Bearer …` |
| Anthropic SDK     | `apiKey` | `X-API-Key: …`            |
| Google GenAI SDK  | `apiKey` | `x-goog-api-key: …`       |
| E2B SDK           | `apiKey` | `X-API-Key: …`            |
| Tavily SDK / HTTP | `apiKey` | `Authorization: Bearer …` |

## 试一条 [#试一条]

```bash
curl https://api.deepraxis.com/model/v1/models \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 鉴权失败长什么样 [#鉴权失败长什么样]

Key 缺失、无效或已吊销，返回 `401`，错误体按该前缀的格式（见[错误](/docs/api/errors)）。收到 `401` 不要重试——换对 Key 再发。

## 保管 [#保管]

* 只在服务端使用；不要放进浏览器、移动端或公开仓库。
* 用环境变量（示例里的 `PRAXIS_API_KEY`），不要写进代码。
* 怀疑泄露时在控制台吊销并新建，旧 Key 立即失效。

# 错误

出错时，HTTP 状态码告诉你错误属于哪一类；错误体按该前缀的格式给出具体原因；每个错误响应还带四个 `x-praxis-problem-*` 头和一个 `x-praxis-recovery-action`（限流错误再多带一个 `x-praxis-problem-scope`，见[限流](/docs/api/rate-limits)），不论错误体长什么样，重试逻辑只看头就够。

## 状态码 [#状态码]

| 状态码   | 含义             | 你该做什么                          |
| ----- | -------------- | ------------------------------ |
| `400` | 请求字段或格式不合法     | 修正参数，不要原样重试                    |
| `401` | 缺少或无效的凭证       | 检查 API Key                     |
| `402` | 余额或付费额度不足      | 补充余额或联系账户管理员                   |
| `403` | 无权访问该资源或操作     | 核对 Key 权限与资源归属；必要时联系支持         |
| `404` | 资源、模型或路径不存在    | 检查 ID、模型名和路径                   |
| `408` | 请求超时           | 检查网络后重试；写操作先确认是否已完成            |
| `409` | 资源状态或并发修改冲突    | 重新读取状态，再调整请求                   |
| `413` | 请求体或文件超过大小限制   | 减小内容或改用端点支持的 URL 输入            |
| `422` | 请求内容无法处理       | 根据错误详情修正参数或输入                  |
| `429` | 请求速率、并发或模型额度超限 | 按 retry-after 等待；并发超限时等待在途请求结束 |
| `500` | 平台内部错误         | 稍后重试；持续出现请附 X-Request-Id 联系支持  |
| `501` | 功能尚未支持         | 换用已支持的端点，不要重试                  |
| `502` | 上游调用失败或返回无效响应  | 退避重试，持续失败时换模型或联系支持             |
| `503` | 服务或可用线路暂不可用    | 退避重试，或选择其它模型                   |
| `504` | 上游响应超时         | 退避重试；写操作先确认结果，避免重复创建           |

## 错误码 [#错误码]

以下是常见的机器可读错误码，不是所有端点的封闭枚举。兼容接口的错误体可能使用协议自己的 code/type；跨协议判断可读取 `x-praxis-problem-code`，其值可能与错误体 code 不同。大小写按返回值区分。

| code                                          | 什么时候出现、该怎么办                                                                                                                                                                    |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `AUTHENTICATION_ERROR`                        | Key 缺失或无效；检查并更换凭证。                                                                                                                                                             |
| `VALIDATION_ERROR`                            | 参数不符合格式、类型或范围要求；按详情改参数。                                                                                                                                                        |
| `INPUT_NOT_REPRESENTABLE`                     | 所选模型或协议无法表达输入选项；删除该选项或换模型。                                                                                                                                                     |
| `NOT_FOUND`                                   | 资源不存在或对当前账户不可见；核对 ID 与账户。                                                                                                                                                      |
| `MODEL_NOT_FOUND`                             | 模型不存在或不可见；从模型列表选取可用名称。                                                                                                                                                         |
| `MODEL_PROTOCOL_NOT_OFFERED`                  | 模型不提供所请求的协议；换用其支持的端点或模型。                                                                                                                                                       |
| `MODEL_PROTOCOL_LINE_UNAVAILABLE`             | 支持该协议的合格线路暂不可用；退避重试或换模型。                                                                                                                                                       |
| `GENERATION_NOT_FOUND`                        | 生成记录不存在或不属于当前账户；核对响应头中的生成 ID 与 Key。                                                                                                                                            |
| `RATE_LIMITED`                                | 超过速率或并发限额；按 retry-after 等待并降低速率或并发。                                                                                                                                            |
| `UPSTREAM_ERROR`                              | 上游调用失败或响应不合法；按 retryable 退避重试，持续失败时换模型或联系支持。                                                                                                                                   |
| `PROVIDER_SELECTION_NOT_ALLOWED`              | 指定供应商 order/only 时没有携带 BYOK；移除供应商选择或提供自己的上游 Key。                                                                                                                               |
| `not_implemented`                             | 该端点或能力未实现；换用已支持的能力，不要原样重试。                                                                                                                                                     |
| `model_protocol_not_offered`                  | HTTP 404；模型未声明所请求的协议。查询 `GET /model/v1/models` 的 `supported_apis`，改用相应入口，例如声明 Google 协议的模型使用 `/google/v1beta/models/{model}:generateContent`；不要只换前缀而保留另一协议的请求体。                |
| `provider_unavailable`                        | HTTP 502；本次请求的可用线路全部失败。退避重试，持续失败时换模型，并附 `X-Request-Id` 联系支持。                                                                                                                   |
| `thinking_disable_unsupported`                | HTTP 400；模型不能关闭思考，例如对 `glm-5.3` 设置 `reasoning_effort="none"`。移除关闭设置或选择支持的思考等级；需要关闭思考时换模型。                                                                                      |
| `insufficient_quota` / `INSUFFICIENT_BALANCE` | HTTP 402；余额不足，错误体或响应头的代码因入口而异。充值或联系账户管理员后再重试，不要立即循环重试。                                                                                                                         |
| `validation_error`（`response_format`）         | HTTP 400；例如 `Model "deepseek-flash" does not support json_schema on this API.`。换用在该入口支持 `json_schema` 的模型；若只需要合法 JSON，可改用 `json_object`，但它不保证 schema 约束。                       |
| `validation_error`（参数被点名）                     | HTTP 400；设置 `provider.require_parameters=true` 时，所选模型仍可能无法支持请求参数，例如 `param: "logprobs"`、`does not support the requested logprobs value`。按 `param` 和消息调整参数或换模型；不要只关闭检查后假定参数已生效。 |

## 错误体 [#错误体]

错误体的格式跟着地址第一段走，和成功响应一致——你的 SDK 不需要为错误特殊处理。

**厂商前缀**（`/openai` `/anthropic` `/google` `/e2b` `/tavily`）：和该前缀对应的官方 API 错误体一模一样。

```json
// /openai
{ "error": { "code": 401, "message": "Invalid API key." } }
```

```json
// /anthropic
{ "type": "error", "error": { "type": "authentication_error", "message": "Invalid API key." } }
```

**Praxis 前缀**（`/agent` `/model` `/sandbox` `/search` `/meta`）：标准的 Problem Details（RFC 9457），`Content-Type: application/problem+json`。

```json
{
  "type": "https://deepraxis.ai/problems/authentication_error",
  "title": "authentication_error",
  "status": 401,
  "detail": "Invalid API key.",
  "instance": "problem_eqfnxu",
  "code": "AUTHENTICATION_ERROR",
  "retryable": false
}
```

| 字段                 | 含义                 |
| ------------------ | ------------------ |
| `type`             | 错误类型的 URL，稳定，可用来分支 |
| `title` / `detail` | 给人读的摘要与具体原因        |
| `status`           | 同 HTTP 状态码         |
| `instance`         | 本次错误的 ID，联系支持时附上   |
| `code`             | 机器可读的错误码           |
| `retryable`        | 原样重试是否可能成功         |

## 错误响应头（五个通用头 + 一个限流头） [#错误响应头五个通用头--一个限流头]

五个通用头与错误体格式无关；第六个 scope 头仅适用于限流错误：

| 头                            | 含义                                                                    | 例子                       |
| ---------------------------- | --------------------------------------------------------------------- | ------------------------ |
| `x-praxis-problem-code`      | 跨协议分类码；可能与错误体的 `code` 不同                                              | `AUTHENTICATION_ERROR`   |
| `x-praxis-problem-kind`      | 错误大类——出了什么事                                                           | `authentication_failure` |
| `x-praxis-problem-origin`    | 错误归谁——谁能解决它：`user`（你的请求或凭证）、`platform`（我们）、`upstream_provider`（上游厂商）等 | `unknown`                |
| `x-praxis-problem-retryable` | 原样重试是否可能成功                                                            | `false`                  |
| `x-praxis-problem-scope`     | 仅限流错误：触发的保护层——`platform` 平台层、`model` 模型层                              | `platform`               |
| `x-praxis-recovery-action`   | 建议的处理动作                                                               | `relogin`                |

## 重试 [#重试]

* `retryable` 为 `true`（或状态码 `429` `502` `503`）：指数退避重试；`429` 优先按 `retry-after`。
* 其它一律不要原样重试——先改请求或 Key。

# 限流

Praxis 的限流分两层：**平台层**按你的 Key 限每秒请求数和同时进行的请求数；**模型层**按模型限每分钟请求数（RPM）和每分钟 token 数（TPM）。每个响应——不论成功还是 `429`——都带三个 `x-ratelimit-*` 头，写明当前额度和重置时间，你不需要猜，也不需要为读额度多发请求。

## 两层限额 [#两层限额]

| 层   | 按什么计                | 限什么                               | 超出的表现                       |
| --- | ------------------- | --------------------------------- | --------------------------- |
| 平台层 | 你的 Key（没带凭证时按来源 IP） | 每秒请求数、同时进行的请求数                    | `429` + `retry-after`，等待后重试 |
| 模型层 | 模型 × 租户             | 每分钟请求数（RPM）、每分钟 token 数（TPM）、月度预算 | `429`，见下文模型层                |

两层的 `429` 都带同样的三个限流头；是哪一层触发的，看错误体的说明（[错误](/docs/api/errors)）。

## 平台层：每秒请求数与并发数 [#平台层每秒请求数与并发数]

默认每个 API Key **每秒最多 5 个请求，同时最多 4 个在途请求**。流式请求在流结束前占用并发槽位。超过任一默认限额返回 `429`，响应带 `ratelimit-limit`、`ratelimit-remaining`、`ratelimit-reset` 和 `retry-after`；并发超限须等已有请求结束。

实际限额可能因账户而异；以响应头和并发错误详情为准。

### 三个响应头 [#三个响应头]

```http
x-ratelimit-limit-requests: 5
x-ratelimit-remaining-requests: 4
x-ratelimit-reset-requests: 850ms
```

| 头                                | 含义                                    |
| -------------------------------- | ------------------------------------- |
| `x-ratelimit-limit-requests`     | 该凭证每秒的请求上限                            |
| `x-ratelimit-remaining-requests` | 本秒还剩多少个请求                             |
| `x-ratelimit-reset-requests`     | 距离额度重置的时间：不满一秒写作 `850ms`，一秒及以上写作 `1s` |

同样的三个数也以 IETF 标准名 `RateLimit-Limit` / `RateLimit-Remaining` / `RateLimit-Reset`（整数秒）同时给出。以上 5 次/秒、4 个并发为默认限额；配置覆盖后的请求速率以响应头显示为准。

### 超出每秒上限 [#超出每秒上限]

一秒内的第 N+1 个请求（N 为该 Key 的每秒上限）返回 `429`，并带 `retry-after`（整数秒，通常是 `1`）。**被拒绝的请求不消耗额度**：`x-ratelimit-remaining-requests` 保持 `0`，等窗口重置即可恢复。

### 超出并发上限 [#超出并发上限]

同时进行的请求（包括尚未结束的流式响应——流结束前一直占坑）超过该 Key 的并发上限时，多出的请求返回 `429`，`retry-after` 为 `1`。这种情况下**仅等待秒级窗口重置不会释放并发槽位**：须等一个进行中的请求结束。是并发还是每秒触发的，错误说明里写得很清楚（"Concurrent request limit …" / "Requests per second limit …"）。

### 错误体 [#错误体]

错误体跟着地址第一段走（见[错误](/docs/api/errors)）。`/model/v1/chat/completions` 等原生端点是 Problem Details：

```json
{
  "type": "https://deepraxis.ai/problems/rate_limit",
  "title": "rate_limited",
  "status": 429,
  "detail": "Requests per second limit of 5 exceeded for this credential. Retry after the listed wait.",
  "instance": "problem_eqfnxu",
  "kind": "rate_limit",
  "scope": "platform",
  "retryable": true
}
```

`scope: "platform"` 表示是平台层触发的（模型层限额的错误不带此字段或为 `model`）。`/openai/v1/chat/completions` 等厂商前缀按该家的错误格式，例如 OpenAI 兼容端点：

```json
{ "error": { "code": 429, "type": "rate_limit_error", "message": "Requests per second limit of 5 exceeded for this credential. Retry after the listed wait." } }
```

### 没带凭证的请求 [#没带凭证的请求]

公开端点（如 `GET /model/v1/models`）允许不带 Key 调用，这时按**来源 IP** 计入一个较小的匿名额度，响应头同样给出。带了 Key 就按 Key 计，与 IP 无关。

`GET /meta/v1/health` 不限流，探活监控可以任意频率调用。

## 模型层：每分钟请求数与 token 数 [#模型层每分钟请求数与-token-数]

限额维度是**模型 × 租户 × 分钟**，不是 API Key：

* 每个模型在模型元数据里配置自己的 **RPM**（每分钟请求数）与 **TPM**（每分钟 token 数）；未配置或为 `0` 表示不限制。
* 命中任一限额返回 `429`，`type` 为 `rate_limit_error`，`Retry-After: 60`，`problem.details.rateLimit` 给出当前值与限额。
* **BYOK 调用自带供应商凭证，不占平台模型限额。**
* 上游供应商限流由平台自动 failover 到其他供应商；全部供应商不可用时按返回的 `429` 处理。

模型另有**月度预算**：按模型当月累计收入计，超出返回 `429`，`type` 为 `budget_error`（`QUOTA_EXHAUSTED`），无 `Retry-After`——等待无效，需要提升该模型的预算。

错误体与状态码见[错误](/docs/api/errors)；账号额度见[配额与限流](/docs/cloud/account/quotas)。

# 版本

版本号写在地址里，紧跟第一段；每个前缀各自计版本，没有全站统一的版本号。

## 地址里的版本段 [#地址里的版本段]

```
https://api.deepraxis.com/{protocol}/{version}/…
```

| 前缀                                             | 版本段      | 由谁决定   |
| ---------------------------------------------- | -------- | ------ |
| `/openai` `/anthropic`                         | `v1`     | 跟随厂商   |
| `/google`                                      | `v1beta` | 跟随厂商   |
| `/e2b` `/tavily`                               | 无版本段     | 跟随厂商   |
| `/agent` `/model` `/sandbox` `/search` `/meta` | `v1`     | Praxis |

厂商前缀下，版本相关的头（如 Anthropic 的 `anthropic-version`）原样透传给厂商，行为与官方一致。

## 什么算破坏性变更 [#什么算破坏性变更]

删字段、改字段类型或含义、改默认值、收紧校验、改错误码含义。加字段、加端点、放宽校验不算。

## Beta 与正式 [#beta-与正式]

* **Beta**：端点页标有「Beta」。可能随时改动，不做兼容承诺；适合试用，不建议放进生产。
* **正式**：破坏性变更只会以新版本段发布（如 `/model/v2/…`），旧版本继续可用。

## 弃用怎么通知 [#弃用怎么通知]

旧版本或端点弃用时：

1. 更新日志公告，并给出替代方案；
2. 该端点的响应带两个标准头：`Deprecation`（RFC 9745，何时弃用）与 `Sunset`（RFC 8594，何时下线），`Link` 头指向迁移说明；
3. 从公告到下线至少 **90 天**；下线后返回 `404`。

```
Deprecation: @1767225600
Sunset: Sat, 04 Apr 2026 00:00:00 GMT
Link: </docs/changelog>; rel="deprecation"
```

# OpenAI 兼容接口

## 基础地址 [#基础地址]

## 接入 [#接入]

## 端点 [#端点]

| 方法     | 路径                                                                                                            | 说明         | 支持     |
| ------ | ------------------------------------------------------------------------------------------------------------- | ---------- | ------ |
| POST   | [`/v1/chat/completions`](/docs/api/compatible/openai/createChatCompletion)                                    | 对话         | ● 支持   |
| POST   | [`/v1/responses`](/docs/api/compatible/openai/createResponse)                                                 | 生成响应       | ● 支持   |
| GET    | [`/v1/responses/{response_id}`](/docs/api/compatible/openai/retrieveResponse)                                 | 读取响应       | ● 支持   |
| DELETE | [`/v1/responses/{response_id}`](/docs/api/compatible/openai/deleteResponse)                                   | 删除响应       | ● 支持   |
| POST   | [`/v1/responses/{response_id}/cancel`](/docs/api/compatible/openai/cancelResponse)                            | 取消响应       | ◐ 部分支持 |
| GET    | [`/v1/responses/{response_id}/input_items`](/docs/api/compatible/openai/listResponseInputItems)               | 列出响应输入项    | ● 支持   |
| POST   | [`/v1/responses/compact`](/docs/api/compatible/openai/compactResponse)                                        | 压缩响应       | ○ 未支持  |
| POST   | [`/v1/responses/input_tokens`](/docs/api/compatible/openai/countResponseInputTokens)                          | 统计输入 token | ○ 未支持  |
| POST   | [`/v1/conversations`](/docs/api/compatible/openai/createConversation)                                         | 创建会话       | ● 支持   |
| GET    | [`/v1/conversations/{conversation_id}`](/docs/api/compatible/openai/retrieveConversation)                     | 读取会话       | ● 支持   |
| POST   | [`/v1/conversations/{conversation_id}`](/docs/api/compatible/openai/updateConversation)                       | 更新会话       | ● 支持   |
| DELETE | [`/v1/conversations/{conversation_id}`](/docs/api/compatible/openai/deleteConversation)                       | 删除会话       | ● 支持   |
| POST   | [`/v1/conversations/{conversation_id}/items`](/docs/api/compatible/openai/createConversationItems)            | 创建会话条目     | ● 支持   |
| GET    | [`/v1/conversations/{conversation_id}/items`](/docs/api/compatible/openai/listConversationItems)              | 列出会话条目     | ● 支持   |
| GET    | [`/v1/conversations/{conversation_id}/items/{item_id}`](/docs/api/compatible/openai/retrieveConversationItem) | 读取会话条目     | ● 支持   |
| DELETE | [`/v1/conversations/{conversation_id}/items/{item_id}`](/docs/api/compatible/openai/deleteConversationItem)   | 删除会话条目     | ● 支持   |
| POST   | [`/v1/images/generations`](/docs/api/compatible/openai/createImage)                                           | 生成图像       | ● 支持   |
| GET    | [`/v1/models`](/docs/api/compatible/openai/listModels)                                                        | 列出模型       | ● 支持   |
| GET    | [`/v1/models/{model}`](/docs/api/compatible/openai/retrieveModel)                                             | 读取模型       | ● 支持   |
| POST   | [`/v1/embeddings`](/docs/api/compatible/openai/createEmbedding)                                               | 文本向量       | ● 支持   |
| POST   | [`/v1/videos`](/docs/api/compatible/openai/createVideo)                                                       | 创建视频       | ● 支持   |
| GET    | [`/v1/videos`](/docs/api/compatible/openai/listVideos)                                                        | 列出视频       | ● 支持   |
| GET    | [`/v1/videos/{video_id}`](/docs/api/compatible/openai/retrieveVideo)                                          | 读取视频       | ● 支持   |
| GET    | [`/v1/videos/{video_id}/content`](/docs/api/compatible/openai/downloadVideoContent)                           | 下载视频内容     | ● 支持   |
| DELETE | [`/v1/videos/{video_id}`](/docs/api/compatible/openai/deleteVideo)                                            | 删除视频       | ● 支持   |
| POST   | [`/v1/videos/{video_id}/remix`](/docs/api/compatible/openai/remixVideo)                                       | 混剪视频       | ○ 未支持  |
| POST   | [`/v1/audio/transcriptions`](/docs/api/compatible/openai/openaiAudioTranscriptionsCreate)                     | 转写音频       | ● 支持   |
| POST   | [`/v1/files`](/docs/api/compatible/openai/createFile)                                                         | 上传文件       | ◐ 部分支持 |
| GET    | [`/v1/files`](/docs/api/compatible/openai/listFiles)                                                          | 列出文件       | ● 支持   |
| GET    | [`/v1/files/{file_id}`](/docs/api/compatible/openai/retrieveFile)                                             | 检索文件       | ● 支持   |
| DELETE | [`/v1/files/{file_id}`](/docs/api/compatible/openai/deleteFile)                                               | 删除文件       | ● 支持   |
| GET    | [`/v1/files/{file_id}/content`](/docs/api/compatible/openai/retrieveFileContent)                              | 检索文件内容     | ● 支持   |
| POST   | `/v1/audio/speech`                                                                                            | 生成语音       | ● 支持   |
| POST   | `/v1/images/edits`                                                                                            | 编辑图片       | ● 支持   |

[知识库（16 个操作）](/docs/api/compatible/openai/vector-stores)：创建知识库、添加文件、批量入库与搜索。

## 不支持的端点 [#不支持的端点]

以下端点在 /openai/v1 下未提供，调用返回 404。替代流程不等同于原端点。

| 端点                       | 替代                                                |
| ------------------------ | ------------------------------------------------- |
| `/v1/moderations`        | 无替代端点                                             |
| `/v1/batches`            | 逐次调用所需模型端点                                        |
| `/v1/fine_tuning`        | 使用模型目录中已有的模型                                      |
| `/v1/assistants`         | 使用 Responses 与 Conversations 构建会话                 |
| `/v1/completions`        | 改用 chat/completions                               |
| `/v1/audio/translations` | 先用 audio/transcriptions 转写，再用 chat/completions 翻译 |
| `/v1/uploads`            | 改用 files 上传文件                                     |
| `/v1/images/variations`  | 使用 images/edits 提交图片与编辑提示词                        |

## 与官方的差异 [#与官方的差异]

* <a href="/docs/api/compatible/openai/createChatCompletion">对话</a>：未知顶层字段原样转发给同协议上游，由上游决定是否接受；已声明字段的类型与取值范围仍会校验，不合法时返回 400 并点名字段。
* <a href="/docs/api/compatible/openai/createResponse">生成响应</a>：未知顶层字段原样转发给同协议上游，由上游决定是否接受；已声明字段的类型与取值范围仍会校验，不合法时返回 400 并点名字段。
* <a href="/docs/api/compatible/openai/retrieveResponse">读取响应</a>：按 ID 读取一条已保存的响应。如果创建时 store 为 false，我们不会保存这次响应，读取会返回 404 response\_not\_found；超过保留期（默认 30 天）后读取也会返回同样的 404。
* <a href="/docs/api/compatible/openai/deleteResponse">删除响应</a>：按 ID 立即删除一条已保存的响应。如果创建时 store 为 false，我们不会保存这次响应，删除会返回 404 response\_not\_found。
* <a href="/docs/api/compatible/openai/cancelResponse">取消响应</a>：仅对以 background:true 创建、且路由到具备后台生成能力的模型的响应可用：取消是 幂等的，重复调用返回同一个终态响应；我方的取消只能停止我方对上游流的继续读取， 不能保证已发往上游的算力停止计算，用量按实际收到的部分结算。对一个非后台 （同步）响应调用 cancel：如果这个响应 id 不存在（未持久化、已过期或 id 有误）， 返回 404 object\_not\_found；如果响应存在但其来源 provider 没有声明支持 cancel 操作（我们目前没有接入任何为同步响应声明该能力的上游），返回 400 native\_responses\_operation\_unsupported。这两种情况都不是尚未实现的 501 gate。
* <a href="/docs/api/compatible/openai/listResponseInputItems">列出响应输入项</a>：列出一条已保存响应的输入项。支持 limit（1–100，默认 20）、order（asc/desc， 默认 desc，与官方一致）与基于条目 id 的 after 游标分页；has\_more/first\_id/ last\_id 均与实际返回页一致，可据此翻页且不重不漏。每个条目都带服务端签发的 id（message 为 msg\_ 前缀，function\_call/function\_call\_output/reasoning 各自 对应前缀），本次上线前已保存、尚无服务端 id 的旧数据在读取时按确定性规则补 id，不做破坏性迁移，同一游标反复读取保持稳定。以 previous\_response\_id 续接 创建的响应，其输入项列出解析后的完整输入：前序响应链已有的输入与输出条目 再加本轮自己提交的输入；若该祖先响应在我方平台未保存（例如创建时 store 为 false）或已过期删除，则只列出本轮自己提交的输入。如果创建时 store 为 false，我们不会保存这次响应，列出会返回 404 response\_not\_found。
* <a href="/docs/api/compatible/openai/compactResponse">压缩响应</a>：把响应的输入压缩成摘要，依赖 OpenAI Responses 官方的服务端存储（store）语义，我们目前还没有实现；调用会返回 501（message 为 “This platform has not implemented … yet.”，响应头 x-should-retry 为 false），不产生副作用，官方 SDK 不会重试。
* <a href="/docs/api/compatible/openai/countResponseInputTokens">统计输入 token</a>：只统计请求输入会消耗的 token 数、不生成内容，依赖 OpenAI Responses 官方的服务端存储（store）语义，我们目前还没有实现；调用会返回 501（message 为 “This platform has not implemented … yet.”，响应头 x-should-retry 为 false），不产生副作用，官方 SDK 不会重试。
* <a href="/docs/api/compatible/openai/createConversation">创建会话</a>：创建一个会话，可选携带初始 items（一次最多 20 条）与 metadata。会话按租户分区，创建者是唯一能引用它的租户。
* <a href="/docs/api/compatible/openai/retrieveConversation">读取会话</a>：按 ID 读取一个会话。不存在或属于其他租户都返回 404 conversation\_not\_found。
* <a href="/docs/api/compatible/openai/updateConversation">更新会话</a>：更新一个会话的 metadata——整体替换，不与已有 metadata 合并。
* <a href="/docs/api/compatible/openai/deleteConversation">删除会话</a>：删除一个会话。删除后该会话与其 items 都不能再被引用（包括作为 Responses create 的 conversation 参数）。
* <a href="/docs/api/compatible/openai/createConversationItems">创建会话条目</a>：向一个会话追加 items（一次最多 20 条），返回刚追加的这些 items。
* <a href="/docs/api/compatible/openai/listConversationItems">列出会话条目</a>：按创建顺序列出会话的 items，支持 limit/after/order 分页参数。
* <a href="/docs/api/compatible/openai/retrieveConversationItem">读取会话条目</a>：按 ID 读取会话里的单条 item。
* <a href="/docs/api/compatible/openai/deleteConversationItem">删除会话条目</a>：删除会话里的单条 item，返回该会话对象（不是被删除的 item）。
* <a href="/docs/api/compatible/openai/retrieveModel">读取模型</a>：返回与列表中同一条目相同的模型对象。只有声明了 OpenAI 协议的模型可见；模型 ID 可以带斜杠分隔的发布方前缀。不存在或没有声明 OpenAI 协议的模型返回 404。
* <a href="/docs/api/compatible/openai/createEmbedding">文本向量</a>：转发方式与对话（chat completions）一致，用量算在同一份计费里。 未知顶层字段原样转发给同协议上游，由上游决定是否接受；已声明字段的类型与取值范围仍会校验，不合法时返回 400 并点名字段。
* <a href="/docs/api/compatible/openai/createVideo">创建视频</a>：异步生成视频：创建任务后轮询状态，完成后下载内容。按输出秒数计费，每秒价格见 GET /model/v1/models 的 pricing.video\_second（USD/秒）。请显式选择已注册的视频模型，例如 wan2.7-t2v。
* <a href="/docs/api/compatible/openai/listVideos">列出视频</a>：列出本账号的视频任务。limit 为 1 到 100，order 为 asc 或 desc，after 必须引用存在的任务。
* <a href="/docs/api/compatible/openai/retrieveVideo">读取视频</a>：读取任务的当前状态和进度。status 为 queued 或 in\_progress 时继续轮询，failed 时查看 error，completed 后才能下载内容。任务不存在返回 404。
* <a href="/docs/api/compatible/openai/downloadVideoContent">下载视频内容</a>：任务 completed 后下载视频文件（video，MP4）或缩略图（thumbnail）；spritesheet 返回 400，index 只支持 0。任务不存在返回 404。
* <a href="/docs/api/compatible/openai/deleteVideo">删除视频</a>：删除任务及其生成的内容。任务不存在返回 404。
* <a href="/docs/api/compatible/openai/remixVideo">混剪视频</a>：未支持，调用固定返回 400（invalid\_request\_error，消息为 Video remix is not supported）；不要重试。
* <a href="/docs/api/compatible/openai/openaiAudioTranscriptionsCreate">转写音频</a>：标准请求字段；不能表达的参数返回 input\_not\_representable。
* <a href="/docs/api/compatible/openai/createFile">上传文件</a>：单文件最多 100 MB（104857600 字节）；按内容识别 PDF、Office、图片、音频、视频与 UTF-8 文本。purpose 支持 user\_data / assistants / vision；其他用途、空文件、不支持类型和超限均返回 400。不支持 Uploads 分片。只接受表单 file、purpose、expires\_after\[anchor]、expires\_after\[seconds]；其他表单字段或任何查询参数返回 400 invalid\_request\_error，消息为 "Unrecognized request argument supplied: \<字段>"，param 为该字段。
* <a href="/docs/api/compatible/openai/listFiles">列出文件</a>：只接受查询参数 after、order、limit、purpose；其他查询参数返回 400 invalid\_request\_error，消息为 "Unrecognized request argument supplied: \<参数>"，param 为该参数。

参数与字段的权威定义以 [OpenAI 官方文档](https://platform.openai.com/docs/api-reference)为准。

错误按 OpenAI 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 对话

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful chat completion response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| choices | array&lt;object&gt; | List of completion choices |
| choices[].finish_reason | string &#124; null |  |
| choices[].index | integer | Choice index |
| choices[].logprobs | object &#124; null | Log probabilities for the completion |
| choices[].message | object | Assistant message for requests and responses |
| created | integer | Unix timestamp of creation |
| id | string | Unique completion identifier |
| model | string | Model used for completion |
| object | string |  |
| openrouter_metadata | object | Routing report: what was requested, how the router chose, and what was attempted. |
| openrouter_metadata.attempt | integer | Number of the attempt that served the request, starting at 1. |
| openrouter_metadata.attempts | array&lt;object&gt; | Every attempt that was made, in order. |
| openrouter_metadata.endpoints | object | Which endpoints were available and which one was chosen. |
| openrouter_metadata.generation_time | integer | Milliseconds measured for the generation, from dispatching the upstream request until its response body ended. Divide the completion token count by this for throughput. Absent when no upstream request was dispatched. |
| openrouter_metadata.is_byok | boolean | Whether the request used a key supplied by the caller. |
| openrouter_metadata.params | object | Router parameters that applied to the request. |
| openrouter_metadata.pipeline | array&lt;object&gt; | Stages the request went through before and after the model call. |
| openrouter_metadata.region | string &#124; null | Region that served the request; null when unknown. |
| openrouter_metadata.requested | string | The model or alias the request asked for. |
| openrouter_metadata.strategy | string | How the router picked the model or provider for this request. |
| openrouter_metadata.summary | string | One-line summary of the routing decision. |
| service_tier | string &#124; null | The service tier used by the upstream provider for this request |
| system_fingerprint | string &#124; null | System fingerprint |
| usage | object | Token usage statistics |
| usage.completion_tokens | integer | Number of tokens in the completion |
| usage.completion_tokens_details | object &#124; null | Detailed completion token usage |
| usage.cost | number &#124; null | Cost of the completion |
| usage.cost_details | object &#124; null | Breakdown of upstream inference costs |
| usage.is_byok | boolean | Whether a request was made using a Bring Your Own Key configuration |
| usage.prompt_tokens | integer | Number of tokens in the prompt |
| usage.prompt_tokens_details | object &#124; null | Detailed prompt token usage |
| usage.server_tool_use_details | object &#124; null | Usage for server-side tool execution (e.g., web search) |
| usage.total_tokens | integer | Total number of tokens |

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | object | Streaming chat completion chunk |
| data.choices | array&lt;object&gt; | List of streaming chunk choices |
| data.created | integer | Unix timestamp of creation |
| data.error | object | Error information |
| data.id | string | Unique chunk identifier |
| data.model | string | Model used for completion |
| data.object | string |  |
| data.openrouter_metadata | object | Routing report: what was requested, how the router chose, and what was attempted. |
| data.service_tier | string &#124; null | The service tier used by the upstream provider for this request |
| data.system_fingerprint | string | System fingerprint |
| data.usage | object | Token usage statistics |

# 生成响应

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| background | boolean &#124; null | Whether the response was started in background mode. |
| completed_at | integer &#124; null | Unix time in seconds at which the response finished; null while it has not finished. |
| created_at | integer | Unix time in seconds at which the response was created. |
| error | object &#124; null | Error information returned from the API |
| error.code | string | Machine-readable error code. |
| error.message | string | Human-readable error message. |
| frequency_penalty | number &#124; null | The frequency penalty that applied to the request, if any. |
| id | string | Unique id of the response; use it as response_id to retrieve, cancel or delete it, or as previous_response_id to continue the conversation. |
| incomplete_details | object &#124; null | Why the response stopped before finishing; null for complete responses. |
| incomplete_details.reason | string | Why the response is incomplete. |
| instructions | string &#124; array&lt;object&gt; &#124; null | Input of the request: a string or an array of input items. |
| max_output_tokens | integer &#124; null | Upper bound on generated tokens that applied to the request; null when none was set. |
| max_tool_calls | integer &#124; null | Upper bound on built-in tool calls that applied to the request; null when none was set. |
| metadata | object &#124; null | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. |
| model | string | Model that produced the response. |
| object | string | Object type; always &#96;response&#96;. |
| output | array&lt;object&gt; | Items the model produced, in order: messages, reasoning, tool calls and tool results. |
| output[].content | array&lt;object&gt; &#124; array &#124; null &#124; string | Content parts of the message: output text or refusal. / Reasoning text parts, when the provider returns them. / Text content of the fetched page. |
| output[].id | string | Id of the message item. / Id of the reasoning item. / Id of the function call item. / Id of the web search call item. / Id of the file search call item. / Id of the image generation call item. / Id of the code interpreter call item. / Id of the computer call item. / Id of the datetime server tool item. / Id of the web search server tool item. / Id of the code interpreter server tool item. / Id of the file search server tool item. / Id of the image generation server tool item. / Id of the browser use server tool item. / Id of the bash server tool item. / Id of the text editor server tool item. / Id of the apply_patch server tool item. / Id of the apply_patch call item. / Id of the shell call item. / Id of the shell call output item. / Id of the shell server tool item. / Id of the web fetch server tool item. / Id of the tool search server tool item. / Id of the memory server tool item. / Id of the MCP server tool item. / Id of the model search server tool item. / Id of the fusion server tool item. / Id of the advisor server tool item. / Id of the subagent server tool item. / Id of the files server tool item. / Id of the custom tool call item. |
| output[].phase | string &#124; null | The phase of an assistant message. Use &#96;commentary&#96; for an intermediate assistant message and &#96;final_answer&#96; for the final assistant message. For follow-up requests with models like &#96;gpt-5.3-codex&#96; and later, preserve and resend phase on all assistant messages. Omitting it can degrade performance. Not used for user messages. |
| output[].role | string | Role of the author; always assistant. |
| output[].status | string | Status of the message item. / Status of the reasoning item. / Status of the function call item. / Status of a web search call. / Status of a web search call. / Status of an image generation call. / Status of the code interpreter call. / Status of the computer call item. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call that can fail. / Status of a tool call. / Status of a tool call. / Lifecycle state of an &#96;apply_patch_call&#96; output item. / Status of a shell call or its output. / Status of a shell call or its output. / Status of a tool call that can fail. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call that can fail. / Status of a tool call that can fail. / Status of a tool call. / Status of the custom tool call item. |
| output[].type | string | Always &#96;message&#96;. Discriminator that marks this object as a OutputMessage in a &#96;type&#96;-tagged union. / Always &#96;reasoning&#96;. Discriminator that marks this object as a OutputItemReasoning in a &#96;type&#96;-tagged union. / Always &#96;function_call&#96;. Discriminator that marks this object as a OutputItemFunctionCall in a &#96;type&#96;-tagged union. / Always &#96;web_search_call&#96;. Discriminator that marks this object as a OutputItemWebSearchCall in a &#96;type&#96;-tagged union. / Always &#96;file_search_call&#96;. Discriminator that marks this object as a OutputItemFileSearchCall in a &#96;type&#96;-tagged union. / Always &#96;image_generation_call&#96;. Discriminator that marks this object as a OutputItemImageGenerationCall in a &#96;type&#96;-tagged union. / Always &#96;code_interpreter_call&#96;. Discriminator that marks this object as a OutputItemCodeInterpreterCall in a &#96;type&#96;-tagged union. / Always &#96;computer_call&#96;. Discriminator that marks this object as a OutputComputerCallItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:datetime&#96;. Discriminator that marks this object as a OutputDatetimeItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:web_search&#96;. Discriminator that marks this object as a OutputWebSearchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:code_interpreter&#96;. Discriminator that marks this object as a OutputCodeInterpreterServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:file_search&#96;. Discriminator that marks this object as a OutputFileSearchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:image_generation&#96;. Discriminator that marks this object as a OutputImageGenerationServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:browser_use&#96;. Discriminator that marks this object as a OutputBrowserUseServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:bash&#96;. Discriminator that marks this object as a OutputBashServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:text_editor&#96;. Discriminator that marks this object as a OutputTextEditorServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:apply_patch&#96;. Discriminator that marks this object as a OutputApplyPatchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;apply_patch_call&#96;. Discriminator that marks this object as a OutputApplyPatchCallItem in a &#96;type&#96;-tagged union. / Always &#96;shell_call&#96;. Discriminator that marks this object as a OutputShellCallItem in a &#96;type&#96;-tagged union. / Always &#96;shell_call_output&#96;. Discriminator that marks this object as a OutputShellCallOutputItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:shell&#96;. Discriminator that marks this object as a OutputShellServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:web_fetch&#96;. Discriminator that marks this object as a OutputWebFetchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:tool_search&#96;. Discriminator that marks this object as a OutputToolSearchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:memory&#96;. Discriminator that marks this object as a OutputMemoryServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:mcp&#96;. Discriminator that marks this object as a OutputMcpServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:experimental__search_models&#96;. Discriminator that marks this object as a OutputSearchModelsServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:fusion&#96;. Discriminator that marks this object as a OutputFusionServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:advisor&#96;. Discriminator that marks this object as a OutputAdvisorServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:subagent&#96;. Discriminator that marks this object as a OutputSubagentServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:files&#96;. Discriminator that marks this object as a OutputFilesServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;custom_tool_call&#96;. Discriminator that marks this object as a OutputCustomToolCallItem in a &#96;type&#96;-tagged union. |
| output[].encrypted_content | string &#124; null | Opaque encrypted reasoning; send it back unchanged to let the model continue its reasoning on the next turn. |
| output[].summary | array&lt;object&gt; | Summary parts of the reasoning. |
| output[].format | string &#124; null | Wire format of the reasoning details, which names the provider family that produced them. |
| output[].signature | string &#124; null | A signature for the reasoning content, used for verification |
| output[].arguments | string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; null | JSON-encoded arguments the model produced for the function. / The raw tool-call arguments string as emitted by the model. / The raw tool-call arguments string as emitted by the model. Echo back unchanged when replaying history; used verbatim to preserve provider prompt-cache prefixes. / The raw tool-call arguments string as emitted by the model. / The JSON arguments submitted to the search tool (e.g. &#123;"query":"Claude"&#125;) / The raw tool-call arguments string as emitted by the model. |
| output[].async | boolean | True when the model called a tool declared with &#96;async: true&#96; and may continue its turn before the output is returned. Return the result in a later request as a &#96;function_call_output&#96; with this &#96;call_id&#96;. |
| output[].call_id | string &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; null &#124; string | Id of the call; the function_call_output item that answers it repeats it as call_id. / Id of the call; the computer_call_output item that answers it repeats it as call_id. / The model-generated tool call id from the originating turn. / Id of the apply_patch tool call. / Id of the call; the apply_patch_call_output item that answers it repeats it as call_id. / Id of the call; the shell_call_output item that answers it repeats it as call_id. / Id of the shell call this output answers. / The model-generated tool call id from the originating turn. / EXPERIMENTAL — subject to change without notice. The &#96;call_id&#96; of the tool call that spawned this subagent. This id will also be included as the &#96;subagent_id&#96; on any &#96;function_call&#96; items created by the subagent. This must be returned in the request so the &#96;function_call&#96; can be matched with the correct subagent. A suspended &#96;in_progress&#96; item is announced once and never re-emitted or terminally closed — completion arrives as a new item with the same &#96;call_id&#96;. / The model-generated tool call id from the originating turn. / Id of the call; the custom_tool_call_output item that answers it repeats it as call_id. |
| output[].name | string | Name of the function being called. / Configured name of the subagent that executed the task (the &#96;name&#96; on its tool entry). Present only for named subagents; omitted for an unnamed (default) subagent. / Name of the custom tool being called. |
| output[].namespace | string | Namespace qualifier for tools registered as part of a namespace tool group (e.g. an MCP server) |
| output[].subagent_id | string | EXPERIMENTAL — subject to change without notice. String id that matches the &#96;call_id&#96; of the &#96;openrouter:subagent&#96; server tool call that spawned the subagent. Present on every &#96;function_call&#96; item the subagent projects; absent on ordinary function calls. |
| output[].subagent_items | array&lt;object&gt; | EXPERIMENTAL — subject to change without notice. The subagent's output items produced on this turn. Treat this as an opaque object; you must replay it in the request so that the subagent can continue execution of the tool with the same context. If a subagent created multiple parallel tool calls, only the first tool call will have this field. The other tool calls will only have &#96;subagent_id&#96;. Present only if the tool call originates from a subagent spawned by the &#96;openrouter:subagent&#96; server tool. |
| output[].action | object &#124; any &#124; object &#124; string &#124; object &#124; object &#124; string | The search action the model took: a search, opening a page, or finding a pattern in a page. / The action the model asks the client to perform on the computer. / The search action performed, matching OpenAI web_search_call.action shape. Includes the query the model issued and optional source URLs returned by the search provider. / The browser action that was performed. / The commands the model asks the client to run. / The commands that were run. / Memory action that was performed. |
| output[].queries | array&lt;string&gt; | Queries the model ran against the vector stores. / Queries that ran against the vector stores. |
| output[].result | string &#124; null &#124; string | Base64-encoded generated image; null while generation has not finished. / The generated image as a base64-encoded string or URL, matching OpenAI image_generation_call format / JSON-serialized result of the file operation. |
| output[].prompt | string | The prompt (possibly rewritten) that the image was generated from. / The prompt the executor sent to the advisor. |
| output[].code | string &#124; null &#124; string | The code the interpreter ran; null while it is still being written. / The code that ran. |
| output[].container_id | string | Id of the container the code ran in. / The canonical container id the command ran under — the &#96;&#123;container_id&#125;&#96; for the Container Files API, reusable as a &#96;container_reference&#96; in later requests. Present on every sandbox-executed call, even when no files changed. / The canonical container id the command ran under — the &#96;&#123;container_id&#125;&#96; for the Container Files API, reusable as a &#96;container_reference&#96; in later requests. Present on every sandbox-executed call, even when no files changed. / The canonical container id the command ran under — the &#96;&#123;container_id&#125;&#96; for the Container Files API, reusable as a &#96;container_reference&#96; in later requests. Present on every sandbox-executed call, even when no files changed. |
| output[].outputs | array &#124; null | Outputs of the run: logs and images; null while the run has not finished. |
| output[].pending_safety_checks | array&lt;object&gt; | Safety checks that must be acknowledged before the action is performed. |
| output[].datetime | string | ISO 8601 datetime string |
| output[].timezone | string | IANA timezone name |
| output[].exitCode | integer | Exit code of the run; 0 means success. / Exit code of the command; 0 means success. |
| output[].language | string | Language of the code that ran. |
| output[].stderr | string | Standard error output of the code. / Standard error output of the command. |
| output[].stdout | string | Standard output of the code. / Standard output of the command. |
| output[].imageB64 | string | Base64-encoded generated image. |
| output[].imageUrl | string | URL of the generated image. |
| output[].revisedPrompt | string | Prompt after the image model rewrote it. |
| output[].screenshotB64 | string | Base64-encoded screenshot taken after the action. |
| output[].command | string | The bash command that ran. / Editor command that ran. |
| output[].error | string | The error message when the sandbox call failed before producing a result (for example, the per-user container limit was reached). Set together with &#96;status: 'failed'&#96;; absent on a successful call. A non-zero &#96;exitCode&#96; is a command failure, not a tool failure. / The error message when the sandbox call failed before producing a result (for example, the per-user container limit was reached). Set together with &#96;status: 'incomplete'&#96; and an empty &#96;output&#96;; absent on a successful call. / The error message when the sandbox call failed before producing a result (for example, the per-user container limit was reached). Set together with &#96;status: 'failed'&#96;; absent on a successful call. &#96;output&#96; is omitted when &#96;error&#96; is set. / The error message if the fetch failed. / Error message when the fusion run did not produce an analysis result. / Error message when the advisor call did not produce advice. Set together with &#96;status: 'failed'&#96; on the terminal item. / Error message when the subagent task did not produce an outcome. Set together with &#96;status: 'failed'&#96; on the terminal item. / Error message when the file operation failed. |
| output[].files | array&lt;object&gt; | Citations for the files the sandbox command created or modified, most-recently-touched first (at most 10). Retrieve them via the Container Files API. |
| output[].filePath | string | Path of the file the command worked on. |
| output[].operation | object &#124; string | The patch operation requested by an &#96;apply_patch_call&#96;. &#96;create_file&#96; and &#96;update_file&#96; carry a V4A diff; &#96;delete_file&#96; omits it. / The file operation performed (list, read, write, or edit). |
| output[].max_output_length | integer &#124; null | Maximum number of characters of output that was kept; null for no limit. |
| output[].output | array&lt;object&gt; | Output of each command, in the order the commands ran. |
| output[].httpStatus | integer | The HTTP status code returned by the upstream URL fetch. |
| output[].title | string | Title of the fetched page. |
| output[].url | string | URL that was fetched. |
| output[].query | string | The tool search query. / The model search query. |
| output[].key | string | Key of the memory entry. |
| output[].value | any | Value of the memory entry; absent for reads that found nothing and for deletes. |
| output[].serverLabel | string | Label of the MCP server. |
| output[].toolName | string | Name of the MCP tool that was called. |
| output[].analysis | object | Structured analysis produced by the fusion analyst model. |
| output[].failed_models | array&lt;object&gt; | Models that were requested as part of the analysis panel but did not produce a response. Present when at least one requested analysis model failed. The fusion result is still usable but was produced from a degraded panel. |
| output[].failure_reason | string | Typed failure reason when the fusion run failed. Possible values include: all_panels_failed, insufficient_credits, rate_limited, invalid_model, judge_not_valid_json, judge_schema_mismatch, judge_upstream_error, judge_empty_completion. The four analysis-stage codes keep their pre-rename &#96;judge_&#96; spelling so existing consumers keep matching. The consumer-cancellation code is &#96;cancelled&#96;. |
| output[].responses | array&lt;object&gt; | Analysis models that produced a response in this fusion run, with each model's full panel content. |
| output[].sources | array&lt;object&gt; | Web pages the analysis panels and analyst retrieved via web search during this fusion run, deduplicated by URL across the whole run. Present when at least one model cited a source. |
| output[].advice | string | The advisor model's response (the advice text returned to the executor). |
| output[].instance_name | string | Provider-safe function name of the specific advisor instance that produced this item (e.g. &#96;openrouter_advisor__1&#96;). Present only when more than one advisor tool is configured; omitted for the default single advisor. Echo this field back unchanged so the advisor's cross-request memory stays namespaced to the correct instance. This identity is positional: it is derived from the index of the advisor entry in the request &#96;tools&#96; array, so clients must keep the order of advisor tool entries stable across requests in a conversation. Reordering or inserting advisor entries shifts these names and causes each advisor's cross-request memory to be attributed to the wrong instance. / Provider-safe function name of the specific subagent instance that produced this item (e.g. &#96;openrouter_subagent__1&#96;). Present only on items from non-default instances — the second and later subagent entries in the request &#96;tools&#96; array. The first (default) instance omits it, even when multiple subagents are configured. When a replayed item echoes this field back, the transcript rehydrates the call under that instance's tool. This identity is positional: it is derived from the index of the subagent entry in the request &#96;tools&#96; array, so keep the order of subagent entries stable across requests in a conversation. |
| output[].model | string | Slug of the advisor model that was consulted. / Slug of the worker model that executed the task. |
| output[].outcome | string | The worker model's result (the outcome text returned to the delegating model). |
| output[].task_description | string | The task description the delegating model sent to the worker. |
| output[].task_name | string | The short task identifier the delegating model supplied. |
| output[].file_id | string | The target file id supplied in the tool-call arguments. |
| output[].filename | string | The target filename supplied in the tool-call arguments. |
| output[].input | string | Free-form input the model produced for the custom tool. |
| output_text | string | Convenience concatenation of all output text of the response. |
| parallel_tool_calls | boolean | Whether the model was allowed to call several tools in one turn. |
| presence_penalty | number &#124; null | The presence penalty that applied to the request, if any. |
| previous_response_id | string &#124; null | Id of the response this one continued; null when it started a new conversation. |
| prompt | object &#124; null | Reference to a stored prompt template with its variables. |
| prompt.id | string | Id of the stored prompt template. |
| prompt.variables | object &#124; null | Values for the template variables, keyed by variable name; a value is a string or an input text, image or file part. |
| prompt_cache_key | string &#124; null | Cache key the request supplied to improve prompt cache hits; null when none was set. |
| prompt_cache_options | object &#124; null | Request-level prompt-cache controls. &#96;mode: "explicit"&#96; disables OpenAI-managed breakpoints so only blocks marked with &#96;prompt_cache_breakpoint&#96; are cached. Only supported by OpenAI GPT-5.6 and newer. |
| prompt_cache_options.mode | string | Prompt cache mode; explicit caches only the blocks marked with prompt_cache_breakpoint. |
| prompt_cache_options.ttl | string &#124; null | Lifetime of cache entries, for example 30m; null leaves the provider default. |
| reasoning | object &#124; null | Reasoning settings that applied: effort, summary verbosity, mode and context. |
| reasoning.context | string &#124; null | Controls which reasoning is available to the model. &#96;auto&#96; uses the model default (same as omitting); &#96;all_turns&#96; includes reasoning from earlier turns passed in input; &#96;current_turn&#96; limits to the current turn only. Only supported by OpenAI GPT-5.6 and newer. |
| reasoning.effort | string &#124; null | How much reasoning the model should spend. |
| reasoning.mode | string &#124; null | Selects the reasoning mode. &#96;standard&#96; is the default; &#96;pro&#96; engages deeper reasoning on models that support it, billed at standard token rates. Only supported by OpenAI GPT-5.6 and newer. |
| reasoning.summary | string &#124; null | How detailed the reasoning summary should be. |
| safety_identifier | string &#124; null | End-user identifier the request supplied for abuse monitoring; null when none was set. |
| service_tier | string &#124; null | Service tier the provider used for the response; null when not reported. |
| status | string | Lifecycle status of the response. |
| store | boolean | Whether the response is stored so it can be retrieved later. |
| temperature | number &#124; null | Sampling temperature that applied to the request, if any. |
| text | object | Text output configuration including format and verbosity |
| text.format | object | Text response format configuration |
| text.verbosity | string &#124; null | How long the answer should be. |
| tool_choice | string &#124; object | How the model picks tools: a mode string or a specific tool. |
| tool_choice.name | string | Name of the function or tool the model must call. |
| tool_choice.type | string | Kind of tool the model must call. / Always &#96;allowed_tools&#96;. Discriminator that marks this object as a ToolChoiceAllowed in a &#96;type&#96;-tagged union. / Kind of tool the model must call. / Kind of tool the model must call. |
| tool_choice.mode | string | auto lets the model pick among the allowed tools or none; required forces a call to one of them. |
| tool_choice.tools | array&lt;object&gt; | The allowed tools, each as a tool reference such as &#123;type: function, name&#125;. |
| tools | array&lt;object&gt; | Tools that were available to the model for this response. |
| tools[].description | string &#124; null &#124; string &#124; string | What the function does and when to use it; the model reads this to decide whether to call it. / What the custom tool does and when to use it. / What the group of tools is for. |
| tools[].name | string | Name of the function; the model uses it in function_call items. / Name of the custom tool. / Name of the namespace that groups the tools. |
| tools[].parameters | object &#124; null | JSON Schema of the function arguments; null when the function takes none. |
| tools[].strict | boolean &#124; null | Whether to enforce strict argument validation against the schema; null leaves the provider default. |
| tools[].type | string | Always &#96;function&#96;. Discriminator that marks this object as a FunctionTool in a &#96;type&#96;-tagged union. / Always &#96;web_search_preview&#96;. Discriminator that marks this object as a Preview_WebSearchServerTool in a &#96;type&#96;-tagged union. / Always &#96;web_search_preview_2025_03_11&#96;. Discriminator that marks this object as a Preview_20250311_WebSearchServerTool in a &#96;type&#96;-tagged union. / Always &#96;web_search&#96;. Discriminator that marks this object as a Legacy_WebSearchServerTool in a &#96;type&#96;-tagged union. / Always &#96;web_search_2025_08_26&#96;. Discriminator that marks this object as a WebSearchServerTool in a &#96;type&#96;-tagged union. / Comparison operator. / Always &#96;computer_use_preview&#96;. Discriminator that marks this object as a ComputerUseServerTool in a &#96;type&#96;-tagged union. / Always &#96;code_interpreter&#96;. Discriminator that marks this object as a CodeInterpreterServerTool in a &#96;type&#96;-tagged union. / Always &#96;mcp&#96;. Discriminator that marks this object as a McpServerTool in a &#96;type&#96;-tagged union. / Always &#96;image_generation&#96;. Discriminator that marks this object as a ImageGenerationServerTool in a &#96;type&#96;-tagged union. / Always &#96;local_shell&#96;. Discriminator that marks this object as a CodexLocalShellTool in a &#96;type&#96;-tagged union. / Always &#96;shell&#96;. Discriminator that marks this object as a ShellServerTool in a &#96;type&#96;-tagged union. / Always &#96;apply_patch&#96;. Discriminator that marks this object as a ApplyPatchServerTool in a &#96;type&#96;-tagged union. / Always &#96;custom&#96;. Discriminator that marks this object as a CustomTool in a &#96;type&#96;-tagged union. / Always &#96;namespace&#96;. Discriminator that marks this object as a NamespaceTool in a &#96;type&#96;-tagged union. |
| tools[].async | boolean | Lets the model keep working after calling this tool instead of waiting for its output. The tool is still executed by the client; return the result in a later request as a &#96;function_call_output&#96; with the original &#96;call_id&#96;. Only honored by providers whose Responses API supports async tools; ignored elsewhere. |
| tools[].defer_loading | boolean | Withhold this tool from the model until &#96;openrouter:tool_search&#96; finds it. Requires the tool search server tool; at least one tool must remain non-deferred. |
| tools[].engine | string | Which search engine to use. "auto" (default) uses native if the provider supports it, otherwise Exa. "native" forces the provider's built-in search. "exa" forces the Exa search API. "firecrawl" uses Firecrawl (requires BYOK). "parallel" uses the Parallel search API. "perplexity" uses the Perplexity Search API (raw ranked results). |
| tools[].filters | object &#124; null | Restricts web search by domain. / Attribute filter applied to the search: a comparison or a compound filter. |
| tools[].max_results | integer | Maximum number of search results to return per search call. Defaults to 5. Applies to Exa, Firecrawl, Parallel, and Perplexity engines; ignored with native provider search. Perplexity supports a maximum of 20; values above 20 are clamped. |
| tools[].max_uses | integer | Maximum number of web searches the model may perform in a single request. Once reached, further search calls return an error result instead of executing. Applies to the Exa, Firecrawl, Parallel, and Perplexity engines. With native provider search, forwarded only to Anthropic (as &#96;max_uses&#96;); other native search providers have no equivalent parameter and ignore it. |
| tools[].mode | string | Engine-native search mode. Exa supports instant, fast, auto (default), deep-lite, deep, and deep-reasoning. Parallel supports turbo, fast, basic (default), and advanced. Modes unsupported by the selected engine are ignored. |
| tools[].search_context_size | string | Size of the search context for web search tools |
| tools[].user_location | object &#124; null | Approximate location of the user, used to bias web search results. / User location information for web search / User location information for web search |
| tools[].max_num_results | integer | Maximum number of results to return, between 1 and 50. |
| tools[].ranking_options | object | Ranking options for the search. |
| tools[].vector_store_ids | array&lt;string&gt; | Ids of the vector stores to search. |
| tools[].display_height | integer | Height of the computer display in pixels. |
| tools[].display_width | integer | Width of the computer display in pixels. |
| tools[].environment | string | Kind of environment that is controlled. |
| tools[].container | string &#124; object | Container for the code to run in: a container id or an automatic container with files. |
| tools[].allowed_tools | array&lt;string&gt; &#124; object &#124; null | Tools of the server the model may use: a list of names or a filter. |
| tools[].authorization | string | OAuth access token for the MCP server. |
| tools[].connector_id | string | Id of a built-in connector; give this or server_url. |
| tools[].headers | object &#124; null | HTTP headers sent to the MCP server; null for none. |
| tools[].require_approval | object &#124; string &#124; null | Whether tool calls need approval before they run: always, never, or a filter per tool. |
| tools[].server_description | string | What the MCP server is for, which helps the model decide when to use it. |
| tools[].server_label | string | Label that names the MCP server in the conversation. |
| tools[].server_url | string | URL of the MCP server; give this or connector_id. |
| tools[].background | string | Background of the generated image. |
| tools[].input_fidelity | string &#124; null | How closely to preserve details of input images; null uses the default. |
| tools[].input_image_mask | object | Mask that marks the region of the input image to edit. |
| tools[].model | string | Image model to use. |
| tools[].moderation | string | Moderation level applied to the generated image. |
| tools[].output_compression | integer | Compression level from 0 to 100 for jpeg and webp output. |
| tools[].output_format | string | File format of the generated image. |
| tools[].partial_images | integer | Number of partial images to stream while generating, from 0 to 3. |
| tools[].quality | string | Quality of the generated image. |
| tools[].size | string | Size of the generated image; auto lets the model choose. |
| tools[].format | object | Format of the tool input: free text or a grammar. |
| tools[].tools | array&lt;object&gt; | Function tools in the namespace. |
| top_logprobs | integer | Number of most likely tokens whose log probabilities were requested per position. |
| top_p | number &#124; null | Nucleus sampling value that applied to the request, if any. |
| truncation | string &#124; null | How to handle input that exceeds the context window. |
| usage | object &#124; null | Token usage information for the response |
| usage.input_tokens | integer | Number of input tokens, cached tokens included. |
| usage.input_tokens_details | object | Breakdown of the input tokens. |
| usage.output_tokens | integer | Number of output tokens, reasoning tokens included. |
| usage.output_tokens_details | object | Breakdown of the output tokens. |
| usage.total_tokens | integer | Input plus output tokens. |
| usage.cost | number &#124; null | Cost of the completion |
| usage.cost_details | object | Breakdown of the upstream inference cost. |
| usage.is_byok | boolean | Whether a request was made using a Bring Your Own Key configuration |
| usage.server_tool_use_details | object &#124; null | Usage for server-side tool execution (e.g., web search) |
| user | string &#124; null | End-user identifier the request supplied; null when none was set. |
| error_type | string | Canonical OpenRouter error type, stable across all API formats |
| openrouter_metadata | object | Routing report: what was requested, how the router chose, and what was attempted. |
| openrouter_metadata.attempt | integer | Number of the attempt that served the request, starting at 1. |
| openrouter_metadata.attempts | array&lt;object&gt; | Every attempt that was made, in order. |
| openrouter_metadata.endpoints | object | Which endpoints were available and which one was chosen. |
| openrouter_metadata.generation_time | integer | Milliseconds measured for the generation, from dispatching the upstream request until its response body ended. Divide the completion token count by this for throughput. Absent when no upstream request was dispatched. |
| openrouter_metadata.is_byok | boolean | Whether the request used a key supplied by the caller. |
| openrouter_metadata.params | object | Router parameters that applied to the request. |
| openrouter_metadata.pipeline | array&lt;object&gt; | Stages the request went through before and after the model call. |
| openrouter_metadata.region | string &#124; null | Region that served the request; null when unknown. |
| openrouter_metadata.requested | string | The model or alias the request asked for. |
| openrouter_metadata.strategy | string | How the router picked the model or provider for this request. |
| openrouter_metadata.summary | string | One-line summary of the routing decision. |

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | object | Union of all possible event types emitted during response streaming |
| data.response | object | Complete non-streaming response from the Responses API |
| data.sequence_number | integer | Position of this event in the stream. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream. |
| data.type | string | Always &#96;response.created&#96;. Discriminator that marks this object as a CreatedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.in_progress&#96;. Discriminator that marks this object as a InProgressEvent in a &#96;type&#96;-tagged union. / Always &#96;response.completed&#96;. Discriminator that marks this object as a CompletedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.incomplete&#96;. Discriminator that marks this object as a IncompleteEvent in a &#96;type&#96;-tagged union. / Always &#96;response.failed&#96;. Discriminator that marks this object as a FailedEvent in a &#96;type&#96;-tagged union. / Always &#96;error&#96;. Discriminator that marks this object as a BaseErrorEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_item.added&#96;. Discriminator that marks this object as a OutputItemAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_item.done&#96;. Discriminator that marks this object as a OutputItemDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.content_part.added&#96;. Discriminator that marks this object as a BaseContentPartAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.content_part.done&#96;. Discriminator that marks this object as a BaseContentPartDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_text.delta&#96;. Discriminator that marks this object as a BaseTextDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_text.done&#96;. Discriminator that marks this object as a BaseTextDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.refusal.delta&#96;. Discriminator that marks this object as a BaseRefusalDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.refusal.done&#96;. Discriminator that marks this object as a BaseRefusalDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_text.annotation.added&#96;. Discriminator that marks this object as a BaseAnnotationAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.function_call_arguments.delta&#96;. Discriminator that marks this object as a BaseFunctionCallArgsDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.function_call_arguments.done&#96;. Discriminator that marks this object as a BaseFunctionCallArgsDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_text.delta&#96;. Discriminator that marks this object as a BaseReasoningDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_text.done&#96;. Discriminator that marks this object as a BaseReasoningDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_summary_part.added&#96;. Discriminator that marks this object as a BaseReasoningSummaryPartAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_summary_part.done&#96;. Discriminator that marks this object as a BaseReasoningSummaryPartDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_summary_text.delta&#96;. Discriminator that marks this object as a BaseReasoningSummaryTextDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_summary_text.done&#96;. Discriminator that marks this object as a BaseReasoningSummaryTextDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.image_generation_call.in_progress&#96;. Discriminator that marks this object as a OpenAIResponsesImageGenCallInProgress in a &#96;type&#96;-tagged union. / Always &#96;response.image_generation_call.generating&#96;. Discriminator that marks this object as a OpenAIResponsesImageGenCallGenerating in a &#96;type&#96;-tagged union. / Always &#96;response.image_generation_call.partial_image&#96;. Discriminator that marks this object as a OpenAIResponsesImageGenCallPartialImage in a &#96;type&#96;-tagged union. / Always &#96;response.image_generation_call.completed&#96;. Discriminator that marks this object as a OpenAIResponsesImageGenCallCompleted in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call.in_progress&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallInProgress in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call.interpreting&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallInterpreting in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call.completed&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallCompleted in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call_code.delta&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallCodeDelta in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call_code.done&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallCodeDone in a &#96;type&#96;-tagged union. / Always &#96;response.web_search_call.in_progress&#96;. Discriminator that marks this object as a OpenAIResponsesWebSearchCallInProgress in a &#96;type&#96;-tagged union. / Always &#96;response.web_search_call.searching&#96;. Discriminator that marks this object as a OpenAIResponsesWebSearchCallSearching in a &#96;type&#96;-tagged union. / Always &#96;response.web_search_call.completed&#96;. Discriminator that marks this object as a OpenAIResponsesSearchCompleted in a &#96;type&#96;-tagged union. / Always &#96;response.custom_tool_call_input.delta&#96;. Discriminator that marks this object as a BaseCustomToolCallInputDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.custom_tool_call_input.done&#96;. Discriminator that marks this object as a BaseCustomToolCallInputDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.apply_patch_call_operation_diff.delta&#96;. Discriminator that marks this object as a ApplyPatchCallOperationDiffDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.apply_patch_call_operation_diff.done&#96;. Discriminator that marks this object as a ApplyPatchCallOperationDiffDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.in_progress&#96;. Discriminator that marks this object as a FusionCallInProgressEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.added&#96;. Discriminator that marks this object as a FusionCallPanelAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.delta&#96;. Discriminator that marks this object as a FusionCallPanelDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.reasoning.delta&#96;. Discriminator that marks this object as a FusionCallPanelReasoningDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.completed&#96;. Discriminator that marks this object as a FusionCallPanelCompletedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.failed&#96;. Discriminator that marks this object as a FusionCallPanelFailedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.analysis.in_progress&#96;. Discriminator that marks this object as a FusionCallAnalysisInProgressEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.analysis.completed&#96;. Discriminator that marks this object as a FusionCallAnalysisCompletedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.completed&#96;. Discriminator that marks this object as a FusionCallCompletedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.debug&#96;. Discriminator that marks this object as a DebugEvent in a &#96;type&#96;-tagged union. |
| data.code | string &#124; null &#124; string | Error code; null when the upstream gave none. / The complete code the interpreter runs. |
| data.message | string | Human-readable error message. |
| data.param | string &#124; null | Name of the request parameter the error is about; null when it is not about a parameter. |
| data.item | object | An output item from the response |
| data.output_index | integer | Index of the item in the response output array that this event belongs to. |
| data.content_index | integer | Index of the content part inside the output item that this event belongs to. |
| data.item_id | string | Id of the output item this event belongs to; it equals the id of that item in the response output. |
| data.part | object | The content part as it starts: output text or refusal. / The content part in its final form: output text or refusal. / A reasoning summary part. / A reasoning summary part. |
| data.delta | string | Text fragment to append to the output text of this content part. / Refusal text fragment to append. / Fragment of the JSON-encoded function arguments to append. / Reasoning text fragment to append. / Reasoning summary text fragment to append. / Fragment of the code the interpreter will run, to append. / Fragment of the custom tool call input to append. / Fragment of the patch diff to append. / Text fragment the panel model produced. / Reasoning text fragment the panel model produced. |
| data.logprobs | array&lt;object&gt; | Log probabilities of the tokens in this fragment, when requested. / Log probabilities of the tokens in the complete text, when requested. |
| data.text | string | The complete output text of this content part. / The complete reasoning text of this content part. / The complete reasoning summary text of this part. |
| data.refusal | string | The complete refusal text. |
| data.annotation | object | Annotation attached to output text: a file citation, URL citation or file path. |
| data.annotation_index | integer | Index of the new annotation inside the content part's annotations array. |
| data.arguments | string | The complete JSON-encoded arguments of the function call. |
| data.name | string | Name of the function being called. |
| data.summary_index | integer | Index of the reasoning summary part inside the reasoning item that this event belongs to. |
| data.partial_image_b64 | string | Base64-encoded partial image produced while generation is still running. |
| data.partial_image_index | integer | Zero-based index of this partial image among the partial images of the call. |
| data.input | string | The complete input of the custom tool call. |
| data.diff | string | The complete patch diff. |
| data.model | string | Slug of the panel model that started. / Slug of the panel model that produced the fragment. / Slug of the panel model that produced the fragment. / Slug of the panel model that finished. / Slug of the panel model that failed. |
| data.content | string | The complete answer of the panel model. |
| data.error | string | Error message that explains why the panel model failed. |
| data.status_code | integer | HTTP status code of the failed upstream call, when one is available. |
| data.analyst_model | string | Slug of the model producing the structured analysis. |
| data.judge_model | string | Deprecated alias of &#96;analyst_model&#96;, kept so existing consumers keep working. Always carries the same value. Use &#96;analyst_model&#96;. |
| data.analysis | object | Structured analysis produced by the fusion analyst model. |
| data.debug | object | Debug information. |

# 读取响应

先调用「生成响应」，用返回的 ID 替换 resp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 删除响应

先调用「生成响应」，用返回的 ID 替换 resp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API delete response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 

先调用「生成响应」，用返回的 ID 替换 resp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API cancel response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 列出响应输入项

先调用「生成响应」，用返回的 ID 替换 resp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API input item list

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API compact response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API input token count

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 创建会话

## 响应 [#响应]

### HTTP 200 [#http-200]

The created conversation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the conversation, such as &#96;conv_...&#96;; use it as &#96;conversation_id&#96; in conversation calls and as &#96;conversation&#96; in createResponse. |
| object | string | Object type; always &#96;conversation&#96;. |
| created_at | integer | Unix time in seconds at which the conversation was created. |
| metadata | object | Up to 16 string key/value pairs; keys at most 64 characters and values at most 512. |

# 读取会话

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The conversation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the conversation, such as &#96;conv_...&#96;; use it as &#96;conversation_id&#96; in conversation calls and as &#96;conversation&#96; in createResponse. |
| object | string | Object type; always &#96;conversation&#96;. |
| created_at | integer | Unix time in seconds at which the conversation was created. |
| metadata | object | Up to 16 string key/value pairs; keys at most 64 characters and values at most 512. |

# 更新会话

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The updated conversation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the conversation, such as &#96;conv_...&#96;; use it as &#96;conversation_id&#96; in conversation calls and as &#96;conversation&#96; in createResponse. |
| object | string | Object type; always &#96;conversation&#96;. |
| created_at | integer | Unix time in seconds at which the conversation was created. |
| metadata | object | Up to 16 string key/value pairs; keys at most 64 characters and values at most 512. |

# 删除会话

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Deletion confirmation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| object | string |  |
| deleted | boolean |  |

# 创建会话条目

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The items just added

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;list&#96;. |
| data | array&lt;object&gt; | Items of the conversation, in the order the list requested. |
| first_id | string | Id of the first item of this page; null for an empty page. |
| last_id | string | Id of the last item of this page; null for an empty page. |
| has_more | boolean | Whether more items exist beyond this page; pass &#96;last_id&#96; as &#96;after&#96; to read them. |

# 列出会话条目

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The conversation's items

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;list&#96;. |
| data | array&lt;object&gt; | Items of the conversation, in the order the list requested. |
| first_id | string | Id of the first item of this page; null for an empty page. |
| last_id | string | Id of the last item of this page; null for an empty page. |
| has_more | boolean | Whether more items exist beyond this page; pass &#96;last_id&#96; as &#96;after&#96; to read them. |

# 读取会话条目

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。 条目 ID 取自「添加对话条目」或「列出对话条目」，替换 item\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The item

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 删除会话条目

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。 条目 ID 取自「添加对话条目」或「列出对话条目」，替换 item\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The conversation, with the item removed

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the conversation, such as &#96;conv_...&#96;; use it as &#96;conversation_id&#96; in conversation calls and as &#96;conversation&#96; in createResponse. |
| object | string | Object type; always &#96;conversation&#96;. |
| created_at | integer | Unix time in seconds at which the conversation was created. |
| metadata | object | Up to 16 string key/value pairs; keys at most 64 characters and values at most 512. |

# 生成图像

## 响应 [#响应]

### HTTP 200 [#http-200]

Image generation response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| created | integer |  |
| data | array&lt;object&gt; |  |
| data[].url | string |  |
| data[].b64_json | string |  |
| data[].revised_prompt | string |  |

# 列出模型

## 响应 [#响应]

### HTTP 200 [#http-200]

Returns a list of models or RSS feed

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | List of available models |
| data[].alias_target | object | Concrete model targeted by this tilde-latest alias, when applicable |
| data[].architecture | object | Model architecture information |
| data[].benchmarks | object | Third-party benchmark rankings for this model. Omitted when no benchmark data is available. |
| data[].canonical_slug | string | Canonical slug for the model |
| data[].context_length | integer &#124; null | Maximum context length in tokens |
| data[].created | integer | Unix timestamp of when the model was created |
| data[].default_parameters | object &#124; null | Default parameters for this model |
| data[].description | string | Description of the model |
| data[].expiration_date | string &#124; null | The date after which the model may be removed. ISO 8601 date string (YYYY-MM-DD) or null if no expiration. |
| data[].hugging_face_id | string &#124; null | Hugging Face model identifier, if applicable |
| data[].id | string | Unique identifier for the model |
| data[].knowledge_cutoff | string &#124; null | The date up to which the model was trained on data. ISO 8601 date string (YYYY-MM-DD) or null if unknown. |
| data[].links | object | Related API endpoints and resources for this model. |
| data[].name | string | Display name of the model |
| data[].per_request_limits | object &#124; null | Per-request token limits |
| data[].pricing | object | Pricing information for the model |
| data[].reasoning | object | Reasoning effort configuration. Omitted for non-reasoning models and dynamic router models. |
| data[].supported_parameters | array&lt;string&gt; | List of supported parameters for this model |
| data[].supported_voices | array &#124; null | List of supported voice identifiers for TTS models. Null for non-TTS models. |
| data[].top_provider | object | Information about the top provider for this model |
| links | object | Pagination links |
| links.next | string &#124; null | URL for the next page of results, or null if this is the last page |
| total_count | integer | Total number of models matching the query |

# 读取模型

## 响应 [#响应]

### HTTP 200 [#http-200]

The matching OpenRouter model list entry.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| alias_target | object | Concrete model targeted by this tilde-latest alias, when applicable |
| alias_target.name | string | Human-readable name of the concrete model targeted by this alias |
| alias_target.slug | string | Routable model ID of the concrete target, matching that model row's id |
| architecture | object | Model architecture information |
| architecture.input_modalities | array&lt;string&gt; | Supported input modalities |
| architecture.instruct_type | string &#124; null | Instruction format type |
| architecture.modality | string &#124; null | Primary modality of the model |
| architecture.output_modalities | array&lt;string&gt; | Supported output modalities |
| architecture.tokenizer | string | Tokenizer type used by the model |
| benchmarks | object | Third-party benchmark rankings for this model. Omitted when no benchmark data is available. |
| benchmarks.artificial_analysis | object | Artificial Analysis benchmark index scores. |
| benchmarks.design_arena | array&lt;object&gt; | Design Arena ELO rankings across arena+category pairs. |
| canonical_slug | string | Canonical slug for the model |
| context_length | integer &#124; null | Maximum context length in tokens |
| created | integer | Unix timestamp of when the model was created |
| default_parameters | object &#124; null | Default parameters for this model |
| default_parameters.frequency_penalty | number &#124; null |  |
| default_parameters.presence_penalty | number &#124; null |  |
| default_parameters.repetition_penalty | number &#124; null |  |
| default_parameters.temperature | number &#124; null |  |
| default_parameters.top_k | integer &#124; null |  |
| default_parameters.top_p | number &#124; null |  |
| description | string | Description of the model |
| expiration_date | string &#124; null | The date after which the model may be removed. ISO 8601 date string (YYYY-MM-DD) or null if no expiration. |
| hugging_face_id | string &#124; null | Hugging Face model identifier, if applicable |
| id | string | Unique identifier for the model |
| knowledge_cutoff | string &#124; null | The date up to which the model was trained on data. ISO 8601 date string (YYYY-MM-DD) or null if unknown. |
| links | object | Related API endpoints and resources for this model. |
| links.details | string | URL for the model details/endpoints API |
| name | string | Display name of the model |
| per_request_limits | object &#124; null | Per-request token limits |
| per_request_limits.completion_tokens | number | Maximum completion tokens per request |
| per_request_limits.prompt_tokens | number | Maximum prompt tokens per request |
| pricing | object | Pricing information for the model |
| pricing.audio | string | Price in USD per audio input token |
| pricing.audio_output | string | Price in USD per audio output token |
| pricing.completion | string | Price in USD per token for completion (output) generation |
| pricing.discount | number | Fractional discount applied to this endpoint's pricing; the price is multiplied by (1 - discount) (0 = no discount, 1 = free) |
| pricing.image | string | Price in USD per image; present only for a flat registry price |
| pricing.image_output | string | Price in USD per output image |
| pricing.image_token | string | Price in USD per image token |
| pricing.input_audio_cache | string | Price in USD per cached audio input token |
| pricing.input_cache_read | string | Price in USD per cached input token (read) |
| pricing.input_cache_write | string | Price per cache-write token, in USD per token. For providers with multiple cache TTLs (e.g. Anthropic), this is the default (5-minute) cache-write rate. |
| pricing.input_cache_write_1h | string | Price per 1-hour cache-write token, in USD per token. Only present for providers that price an extended (1-hour) cache TTL separately, such as Anthropic. |
| pricing.internal_reasoning | string | Price in USD per internal reasoning token |
| pricing.overrides | array&lt;object&gt; | Conditional overrides of the base pricing (e.g. long-context or time-based pricing). An entry applies when all of its condition fields (e.g. min_prompt_tokens, or the utc_start/utc_end time window) match the request; among applicable entries, later entries win per key; price keys absent from an entry inherit the base price. The top-level pricing keys always reflect the price that applies under default conditions. |
| pricing.prompt | string | Price in USD per token for prompt (input) processing |
| pricing.request | string | Price in USD per request |
| pricing.web_search | string | Price in USD per web search |
| pricing.video_second | string | Praxis extension: USD per second of output video. |
| pricing.audio_input_minute | string | Praxis extension: USD per minute of input audio. |
| pricing.audio_output_minute | string | Praxis extension: USD per minute of output audio. |
| pricing.input_character | string | Praxis extension: USD per input character. |
| pricing.page | string | Praxis extension: USD per OCR page. |
| reasoning | object | Reasoning effort configuration. Omitted for non-reasoning models and dynamic router models. |
| reasoning.default_effort | string &#124; null | Default reasoning effort when the client enables reasoning without specifying effort. Maps to &#96;reasoning.effort&#96; in chat requests. When &#96;"none"&#96;, prefer omitting effort unless the user explicitly disables reasoning. |
| reasoning.default_enabled | boolean | Default reasoning enabled state when the client does not set &#96;reasoning.enabled&#96;. |
| reasoning.mandatory | boolean | When true, reasoning cannot be disabled and effort "none" is rejected. |
| reasoning.supported_efforts | array &#124; null | Allowed reasoning effort values for this model, in descending effort order (highest first). Null means no allowlist — all gateway effort values are accepted. |
| reasoning.supports_max_tokens | boolean | Present and &#96;true&#96; when the model accepts &#96;reasoning.max_tokens&#96; in requests (Anthropic-style) instead of or in addition to &#96;reasoning.effort&#96;. Omitted otherwise. |
| supported_parameters | array&lt;string&gt; | List of supported parameters for this model |
| supported_voices | array &#124; null | List of supported voice identifiers for TTS models. Null for non-TTS models. |
| top_provider | object | Information about the top provider for this model |
| top_provider.context_length | integer &#124; null | Context length from the top provider |
| top_provider.is_moderated | boolean | Whether the top provider moderates content |
| top_provider.max_completion_tokens | integer &#124; null | Maximum completion tokens from the top provider. Input and output tokens share the context window, so the effective maximum output for a request is further limited by the context remaining after input tokens. |

# 文本向量

## 响应 [#响应]

### HTTP 200 [#http-200]

Embedding response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | List of embedding objects |
| data[].embedding | array&lt;number&gt; &#124; string | Embedding vector as an array of floats or a base64 string |
| data[].index | integer | Index of the embedding in the input list |
| data[].object | string |  |
| id | string | Unique identifier for the embeddings response |
| model | string | The model used for embeddings |
| object | string |  |
| usage | object | Token usage statistics |
| usage.cost | number | Cost of the request in credits |
| usage.cost_details | object &#124; null | Breakdown of upstream inference costs |
| usage.is_byok | boolean | Whether a request was made using a Bring Your Own Key configuration |
| usage.prompt_tokens | integer | Number of tokens in the input |
| usage.prompt_tokens_details | object | Per-modality token breakdown. Only present when the input contains 2+ modalities (e.g. text + image) and the upstream provider returns modality-level usage data. Only non-zero modality counts are included. |
| usage.total_tokens | integer | Total number of tokens used |

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string | Not used for embeddings - embeddings do not support streaming |

# 创建视频

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the video job; pass it as &#96;video_id&#96; to retrieve, download or delete it. |
| object | string | Object type; always &#96;video&#96;. |
| model | string | Model that generates the video. |
| status | string | Lifecycle of the job. Poll until it is &#96;completed&#96; or &#96;failed&#96;. |
| progress | integer | Progress from 0 to 100. It is 0 until the job completes and 100 once it has. |
| created_at | integer | Unix time in seconds at which the job was created. |
| completed_at | integer &#124; null | Unix time in seconds at which the job completed; null until then. |
| expires_at | integer &#124; null | Unix time in seconds after which the output expires; null because outputs currently have no expiry. |
| seconds | string | Length of the video in seconds, as a string; for a completed job it is the delivered length. |
| size | string | Resolution of the video as &#96;WIDTHxHEIGHT&#96;; null when the provider did not report one. |
| prompt | string &#124; null | Prompt the job was created with. |
| remixed_from_video_id | null | Always null; remix is not supported. |
| error | object &#124; null | Why the job failed; null unless status is &#96;failed&#96;. |
| error.code | string | Machine-readable failure code. |
| error.message | string | Human-readable failure message. |
| polling_url | string | Relative URL to poll for the job state; same as retrieveVideo for this job. |
| unsigned_urls | array&lt;string&gt; | Relative URLs of the finished output; empty until the video is ready. Download them with the same API key. |
| usage | object | Cost of the job; present once a price applies. |
| usage.cost | number | Cost of the job in USD: delivered seconds times the per-second price once completed, 0 while running. |

# 列出视频

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;list&#96;. |
| data | array&lt;object&gt; | Video jobs of the caller, newest first by default. |
| data[].id | string | Id of the video job; pass it as &#96;video_id&#96; to retrieve, download or delete it. |
| data[].object | string | Object type; always &#96;video&#96;. |
| data[].model | string | Model that generates the video. |
| data[].status | string | Lifecycle of the job. Poll until it is &#96;completed&#96; or &#96;failed&#96;. |
| data[].progress | integer | Progress from 0 to 100. It is 0 until the job completes and 100 once it has. |
| data[].created_at | integer | Unix time in seconds at which the job was created. |
| data[].completed_at | integer &#124; null | Unix time in seconds at which the job completed; null until then. |
| data[].expires_at | integer &#124; null | Unix time in seconds after which the output expires; null because outputs currently have no expiry. |
| data[].seconds | string | Length of the video in seconds, as a string; for a completed job it is the delivered length. |
| data[].size | string | Resolution of the video as &#96;WIDTHxHEIGHT&#96;; null when the provider did not report one. |
| data[].prompt | string &#124; null | Prompt the job was created with. |
| data[].remixed_from_video_id | null | Always null; remix is not supported. |
| data[].error | object &#124; null | Why the job failed; null unless status is &#96;failed&#96;. |
| data[].polling_url | string | Relative URL to poll for the job state; same as retrieveVideo for this job. |
| data[].unsigned_urls | array&lt;string&gt; | Relative URLs of the finished output; empty until the video is ready. Download them with the same API key. |
| data[].usage | object | Cost of the job; present once a price applies. |
| has_more | boolean | Whether more jobs exist beyond this page; pass &#96;last_id&#96; as &#96;after&#96; to read them. |
| first_id | string &#124; null | Id of the first job in this page; null for an empty page. |
| last_id | string &#124; null | Id of the last job in this page; null for an empty page. |

# 读取视频

先调用「创建视频」，用返回的 ID 替换 video\_123；下载前须轮询至 completed。

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the video job; pass it as &#96;video_id&#96; to retrieve, download or delete it. |
| object | string | Object type; always &#96;video&#96;. |
| model | string | Model that generates the video. |
| status | string | Lifecycle of the job. Poll until it is &#96;completed&#96; or &#96;failed&#96;. |
| progress | integer | Progress from 0 to 100. It is 0 until the job completes and 100 once it has. |
| created_at | integer | Unix time in seconds at which the job was created. |
| completed_at | integer &#124; null | Unix time in seconds at which the job completed; null until then. |
| expires_at | integer &#124; null | Unix time in seconds after which the output expires; null because outputs currently have no expiry. |
| seconds | string | Length of the video in seconds, as a string; for a completed job it is the delivered length. |
| size | string | Resolution of the video as &#96;WIDTHxHEIGHT&#96;; null when the provider did not report one. |
| prompt | string &#124; null | Prompt the job was created with. |
| remixed_from_video_id | null | Always null; remix is not supported. |
| error | object &#124; null | Why the job failed; null unless status is &#96;failed&#96;. |
| error.code | string | Machine-readable failure code. |
| error.message | string | Human-readable failure message. |
| polling_url | string | Relative URL to poll for the job state; same as retrieveVideo for this job. |
| unsigned_urls | array&lt;string&gt; | Relative URLs of the finished output; empty until the video is ready. Download them with the same API key. |
| usage | object | Cost of the job; present once a price applies. |
| usage.cost | number | Cost of the job in USD: delivered seconds times the per-second price once completed, 0 while running. |

# 下载视频内容

先调用「创建视频」，用返回的 ID 替换 video\_123；下载前须轮询至 completed。

## 响应 [#响应]

### HTTP 200 [#http-200]

Video or thumbnail bytes

**video/mp4**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

**image/jpeg**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

# 删除视频

先调用「创建视频」，用返回的 ID 替换 video\_123；下载前须轮询至 completed。

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the deleted video job. |
| object | string | Object type; always &#96;video.deleted&#96;. |
| deleted | boolean | Always true; the job is no longer readable. |

# 

先调用「创建视频」，用返回的 ID 替换 video\_123；下载前须轮询至 completed。

## 响应 [#响应]

此端点没有声明成功响应。

# 转写音频

## 响应 [#响应]

### HTTP 200 [#http-200]

Transcription in the requested format.

**text/plain**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string |  |

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| text | string |  |
| task | string |  |
| language | string |  |
| duration | number |  |
| segments | array&lt;object&gt; |  |
| segments[].id | integer |  |
| segments[].start | number |  |
| segments[].end | number |  |
| segments[].text | string |  |
| segments[].temperature | number |  |
| segments[].avg_logprob | number |  |
| segments[].compression_ratio | number |  |
| segments[].no_speech_prob | number |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | The file identifier, which can be referenced in the API endpoints. |
| bytes | integer | The size of the file, in bytes. |
| created_at | integer | The Unix timestamp (in seconds) for when the file was created. |
| expires_at | integer | The Unix timestamp (in seconds) for when the file will expire. |
| filename | string | The name of the file. |
| object | string | The object type, which is always &#96;file&#96;. |
| purpose | string | The intended purpose of the file. Supported values are &#96;assistants&#96;, &#96;assistants_output&#96;, &#96;batch&#96;, &#96;batch_output&#96;, &#96;fine-tune&#96;, &#96;fine-tune-results&#96;, &#96;vision&#96;, and &#96;user_data&#96;. |
| status | string | Deprecated. The current status of the file, which can be either &#96;uploaded&#96;, &#96;processed&#96;, or &#96;error&#96;. |
| status_details | string | Deprecated. For details on why a fine-tuning training file failed validation, see the &#96;error&#96; field on &#96;fine_tuning.job&#96;. |

# 列出文件

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string |  |
| data | array&lt;object&gt; |  |
| data[].id | string | The file identifier, which can be referenced in the API endpoints. |
| data[].bytes | integer | The size of the file, in bytes. |
| data[].created_at | integer | The Unix timestamp (in seconds) for when the file was created. |
| data[].expires_at | integer | The Unix timestamp (in seconds) for when the file will expire. |
| data[].filename | string | The name of the file. |
| data[].object | string | The object type, which is always &#96;file&#96;. |
| data[].purpose | string | The intended purpose of the file. Supported values are &#96;assistants&#96;, &#96;assistants_output&#96;, &#96;batch&#96;, &#96;batch_output&#96;, &#96;fine-tune&#96;, &#96;fine-tune-results&#96;, &#96;vision&#96;, and &#96;user_data&#96;. |
| data[].status | string | Deprecated. The current status of the file, which can be either &#96;uploaded&#96;, &#96;processed&#96;, or &#96;error&#96;. |
| data[].status_details | string | Deprecated. For details on why a fine-tuning training file failed validation, see the &#96;error&#96; field on &#96;fine_tuning.job&#96;. |
| first_id | string |  |
| last_id | string |  |
| has_more | boolean |  |

# 检索文件

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | The file identifier, which can be referenced in the API endpoints. |
| bytes | integer | The size of the file, in bytes. |
| created_at | integer | The Unix timestamp (in seconds) for when the file was created. |
| expires_at | integer | The Unix timestamp (in seconds) for when the file will expire. |
| filename | string | The name of the file. |
| object | string | The object type, which is always &#96;file&#96;. |
| purpose | string | The intended purpose of the file. Supported values are &#96;assistants&#96;, &#96;assistants_output&#96;, &#96;batch&#96;, &#96;batch_output&#96;, &#96;fine-tune&#96;, &#96;fine-tune-results&#96;, &#96;vision&#96;, and &#96;user_data&#96;. |
| status | string | Deprecated. The current status of the file, which can be either &#96;uploaded&#96;, &#96;processed&#96;, or &#96;error&#96;. |
| status_details | string | Deprecated. For details on why a fine-tuning training file failed validation, see the &#96;error&#96; field on &#96;fine_tuning.job&#96;. |

# 删除文件

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| object | string |  |
| deleted | boolean |  |

# 检索文件内容

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/octet-stream**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

# 知识库

官方 openai Python SDK 可直接使用知识库、文件和批次操作。两个地址访问同一份数据。

`https://api.deepraxis.ai/openai/v1`

[快速开始：官方 Python SDK](/docs/cloud/services/knowledge/quickstart)

## 当前差异 [#当前差异]

搜索按块返回，同一文件可能出现多次；max\_num\_results 计算块数。rewrite\_query 为 true 时先用小模型改写查询（按模型用量计费，失败时回退原查询），改写所用模型只能在原生 API 的 models 中设置，兼容接口传 models 返回 400。搜索 has\_more 恒为 false、next\_page 恒为 null。description 接受后丢弃。expand=files 与 expand\[]=files 为 Praxis 扩展；未知值忽略。

删除知识库后保留 7 天，读取仍可返回 200 completed，但写入和搜索返回 409。恢复、失败重试、分段、事件和混合搜索权重请使用原生 API；兼容接口不返回 praxis、chunk\_id、page 或 span。usage\_bytes 为抽取文本块的字节数。未知请求字段当前会被忽略。

[原生 API](/docs/api/native/knowledge) · [错误码](/docs/api/native/knowledge/errors)

| 方法     | 路径                                                                               | 操作     |
| ------ | -------------------------------------------------------------------------------- | ------ |
| POST   | /openai/v1/vector\_stores                                                        | 创建知识库  |
| GET    | /openai/v1/vector\_stores                                                        | 列出知识库  |
| GET    | /openai/v1/vector\_stores/\{vector\_store\_id}                                   | 读取知识库  |
| POST   | /openai/v1/vector\_stores/\{vector\_store\_id}                                   | 更新知识库  |
| DELETE | /openai/v1/vector\_stores/\{vector\_store\_id}                                   | 删除知识库  |
| POST   | /openai/v1/vector\_stores/\{vector\_store\_id}/search                            | 搜索知识库  |
| POST   | /openai/v1/vector\_stores/\{vector\_store\_id}/files                             | 添加文件   |
| GET    | /openai/v1/vector\_stores/\{vector\_store\_id}/files                             | 列出文件   |
| GET    | /openai/v1/vector\_stores/\{vector\_store\_id}/files/\{file\_id}                 | 读取文件   |
| POST   | /openai/v1/vector\_stores/\{vector\_store\_id}/files/\{file\_id}                 | 更新文件属性 |
| DELETE | /openai/v1/vector\_stores/\{vector\_store\_id}/files/\{file\_id}                 | 移除文件   |
| GET    | /openai/v1/vector\_stores/\{vector\_store\_id}/files/\{file\_id}/content         | 读取抽取内容 |
| POST   | /openai/v1/vector\_stores/\{vector\_store\_id}/file\_batches                     | 创建文件批次 |
| GET    | /openai/v1/vector\_stores/\{vector\_store\_id}/file\_batches/\{batch\_id}        | 读取文件批次 |
| POST   | /openai/v1/vector\_stores/\{vector\_store\_id}/file\_batches/\{batch\_id}/cancel | 取消文件批次 |
| GET    | /openai/v1/vector\_stores/\{vector\_store\_id}/file\_batches/\{batch\_id}/files  | 列出批次文件 |

## 创建知识库 [#创建知识库]

`POST /openai/v1/vector_stores`

创建知识库。可用 file\_ids 添加已有 File 并异步入库；后续调用使用返回的 id。最小请求体：\{"name":"Refund policies"}。

### 请求体 [#请求体]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | string | 可选; 省略时为空字符串；不接受 null。; 最长字符数: 256; 默认: "" |
| metadata | object / null | 可选; 知识库自定义字符串元数据；省略或 null 得到空对象。; 默认: &#123;&#125; |
| expires_after | object / null | 可选; 从最近活动计算的过期策略；省略或 null 表示不自动过期。; 默认: null |
| expires_after (1).anchor | "last_active_at" | 必填; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必填; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| file_ids | string[] | 可选; 要加入的已有文件 ID；每库最多 10,000 个文件。 |
| chunking_strategy | object / object | 可选; auto 等同于每段 800 token、重叠 400 token。; 默认: &#123;"type":"auto"&#125; |
| chunking_strategy (1).type | "auto" | 必填; auto 使用默认静态分段：800 个估算 token，重叠 400 个。 |
| chunking_strategy (2).type | "static" | 必填; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (2).static | object | 必填; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (2).static.max_chunk_size_tokens | integer | 必填; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (2).static.chunk_overlap_tokens | integer | 必填; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| description | string | 可选; 不生效: 接受后丢弃，不保存也不返回；当前不校验类型。 |

### 请求示例 [#请求示例]

```bash
curl -X POST "https://api.deepraxis.ai/openai/v1/vector_stores" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"name\":\"Refund policies\"}"
```

### 响应 [#响应]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| status | "in_progress" / "completed" / "expired" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。 |
| usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 列出知识库 [#列出知识库]

`GET /openai/v1/vector_stores`

列出调用方可见的知识库，默认最新在前。将 last\_id 作为 after 读取下一页，例如 ?limit=20。

### 参数 [#参数]

| 名称     | 位置与类型                 | 说明                                    |
| ------ | --------------------- | ------------------------------------- |
| after  | query: string         | 上一页的 ID 游标。 最短字符数: 1                  |
| before | query: string         | 返回此 ID 之前的条目。 最短字符数: 1                |
| limit  | query: integer        | 每页条数。 最小: 1; 最大: 100; 默认: 20          |
| order  | query: "asc" / "desc" | 知识库和文件默认按创建时间降序；分段默认按序号升序。 默认: "desc" |

### 请求示例 [#请求示例-1]

```bash
curl -X GET "https://api.deepraxis.ai/openai/v1/vector_stores" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-1]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| data[].id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| data[].name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| data[].status | "in_progress" / "completed" / "expired" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。 |
| data[].usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| data[].file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| data[].file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| data[].file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| data[].file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| data[].file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| data[].file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| data[].created_at | integer | 必有; Unix 时间戳，单位秒。 |
| data[].last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| data[].expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| data[].expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| data[].expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| data[].expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| data[].metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |
| first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取知识库 [#读取知识库]

`GET /openai/v1/vector_stores/{vector_store_id}`

使用创建或列表返回的 id 读取知识库。添加 ?expand=files 可同时返回附件首页。已删除的库返回 404。

### 参数 [#参数-1]

| 名称                | 位置与类型             | 说明                                     |
| ----------------- | ----------------- | -------------------------------------- |
| vector\_store\_id | path: string      | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1   |
| expand            | query: "files"\[] | 两个地址均支持的 Praxis 扩展：files 附带文件首页；未知值忽略。 |
| expand\[]         | query: "files"\[] | 两个地址均支持的 Praxis 扩展：files 附带文件首页；未知值忽略。 |

### 请求示例 [#请求示例-2]

```bash
curl -X GET "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-2]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| (1).id | string | 必有; 资源 ID。; 最短字符数: 1 |
| (1).object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| (1).name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| (1).status | "in_progress" / "completed" / "expired" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。 |
| (1).usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| (1).file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| (1).file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| (1).file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| (1).file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| (1).file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| (1).file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| (1).created_at | integer | 必有; Unix 时间戳，单位秒。 |
| (1).last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| (1).expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| (1).expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| (1).expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| (1).expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| (1).metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |
| (2).files | object | 可选; 仅在 expand=files 时返回文件首页。 |
| (2).files.object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| (2).files.data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| (2).files.data[].id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| (2).files.data[].object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| (2).files.data[].vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| (2).files.data[].status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| (2).files.data[].last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| (2).files.data[].last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| (2).files.data[].last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| (2).files.data[].usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| (2).files.data[].created_at | integer | 必有; Unix 时间戳，单位秒。 |
| (2).files.data[].chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| (2).files.data[].chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| (2).files.data[].chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| (2).files.data[].chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| (2).files.data[].chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| (2).files.data[].chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| (2).files.data[].attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| (2).files.first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| (2).files.last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| (2).files.has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 更新知识库 [#更新知识库]

`POST /openai/v1/vector_stores/{vector_store_id}`

使用返回的 id 修改活跃知识库。省略的字段不变；metadata 替换整个对象。请求体示例：\{"name":"Refund policies"}。

### 参数 [#参数-2]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求体 [#请求体-1]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | string / null | 可选; null 将名称清空为空字符串；省略的字段不变。 |
| metadata | object / null | 可选; 替换全部元数据；null 清空为一个空对象。 |
| expires_after | object / null | 可选; null 取消自动过期。 |
| expires_after (1).anchor | "last_active_at" | 必填; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必填; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |

### 请求示例 [#请求示例-3]

```bash
curl -X POST "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"name\":\"Support policies\"}"
```

### 响应 [#响应-3]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| status | "in_progress" / "completed" / "expired" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。 |
| usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 删除知识库 [#删除知识库]

`DELETE /openai/v1/vector_stores/{vector_store_id}`

删除后读取和重复 DELETE 返回 404 not\_found\_error，列表不含已删除库；自有面可在 7 天内恢复。

### 参数 [#参数-3]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求示例 [#请求示例-4]

```bash
curl -X DELETE "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-4]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.deleted" | 必有; 对象标记；vector_store.deleted 表示此操作回执。 |
| deleted | true | 必有; 确认兼容面的知识库删除；后续访问返回未找到。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 搜索知识库 [#搜索知识库]

`POST /openai/v1/vector_stores/{vector_store_id}/search`

每文件一条，content 为按分数降序的命中块；max\_num\_results 计文件，从最多 50 个召回分段聚合。has\_more 表示文件结果截断，next\_page 仍为 null。

### 参数 [#参数-4]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求体 [#请求体-2]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| query | string / string[] | 必填; 非空白文本；多个查询以换行连接后共同搜索。 |
| filters | object / object / object | 可选; 按类型严格匹配文件属性；根条件以下最多嵌套 20 层。 |
| filters (1).type | "eq" / "ne" / "gt" / "gte" / "lt" / "lte" | 必填; eq 等于，ne 不等于，gt 大于，gte 大于等于，lt 小于，lte 小于等于；属性必须存在且值类型一致。 |
| filters (1).key | string | 必填; 要比较的文件属性原始键名，标点也是键名的一部分。; 最短字符数: 1 |
| filters (1).value | string / number / boolean | 必填; 不进行类型转换的比较值。 |
| filters (2).type | "in" / "nin" | 必填; in 匹配数组中的值；nin 匹配不在数组中的值。属性不存在时均不匹配。 |
| filters (2).key | string | 必填; 要比较的文件属性原始键名，标点也是键名的一部分。; 最短字符数: 1 |
| filters (2).value | string / number[] | 必填; 不进行类型转换的字符串或数值成员列表。 |
| filters (3).type | "and" / "or" | 必填; and 要求所有子条件匹配；or 要求至少一个子条件匹配。 |
| filters (3).filters | object / object / object[] | 必填; 按选定 and/or 运算符组合的非空子条件列表。; 最少条数: 1 |
| filters (3).filters[] | object / object / object | 递归使用同一筛选结构，嵌套上限 20 层。 |
| max_num_results | integer | 可选; 从最多 50 个召回分段聚合后，最多返回的不同文件数。; 最小: 1; 最大: 50; 默认: 10 |
| rewrite_query | boolean | 可选; 支持: 为 true 时，先用该库 query_rewrite 角色的模型把每条查询改写为简洁的检索查询；检索使用改写结果，search_query 返回改写后的查询。每次改写是一次小模型调用，按模型用量计费。改写失败、超时（5 秒）或为空时，该条查询回退为原文，搜索照常完成。省略或为 false 时不调用模型。 |
| next_page | string | 可选; 不生效: 搜索不支持翻页；提供游标不生效。 |
| ranking_options | object | 可选; 控制结果排序与纳入结果的最低分数。 |
| ranking_options.ranker | "none" / "auto" / "default-2024-11-15" | 可选; 只有 default-2024-11-15 请求重排；none、auto 和省略时使用初始排序。尚未单独实测重排效果。 |
| ranking_options.score_threshold | number | 可选; 最低分数；分数不是相关性概率。尚未单独实测阈值效果。; 最小: 0; 最大: 1; 默认: 0 |
| ranking_options.hybrid_search | object | 可选; 不支持: 在 /openai/v1 返回 400 INVALID_PARAMS；设置权重请使用 /knowledge/v1。; Praxis 扩展 |
| ranking_options.hybrid_search.embedding_weight | number | 必填; 语义检索相对权重；零表示禁用语义检索。; 最小: 0; 默认: 0.7 |
| ranking_options.hybrid_search.text_weight | number | 必填; 关键词检索相对权重；零表示禁用关键词检索。; 最小: 0; 默认: 0.3 |
| praxis | object | 可选; 不生效: 兼容响应会删除 praxis，包括搜索解释。 |
| praxis.explain | boolean | 可选; 请求生成解释；兼容响应不返回这些解释。 |

### 请求示例 [#请求示例-5]

```bash
curl -X POST "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/search" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"query\":\"When will I receive my refund?\",\"max_num_results\":5}"
```

### 响应 [#响应-5]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "vector_store.search_results.page" | 必有; 对象标记；vector_store.search_results.page 表示搜索结果页。 |
| search_query | string[] | 必有; 实际用于检索的查询，与输入一一对应；rewrite_query 为 true 时为改写后的查询，否则原样返回。 |
| data | object[] | 必有; 每个文件返回一条；content 包含该文件命中的分段。 |
| data[].file_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].filename | string | 必有; 命中文件的源文件名。 |
| data[].score | number | 必有; 该文件命中分段的最高分数。; 最小: 0; 最大: 1 |
| data[].attributes | object / null | 必有; 用于筛选的当前文件属性；未设置时为 null。 |
| data[].content | object[] | 必有; 按分段分数降序排列的命中分段。 |
| data[].content[].type | "text" | 必有; text 表示提取出的文本分段。 |
| data[].content[].text | string | 必有; 命中分段的提取文本，可能与相邻分段重叠。 |
| has_more | boolean | 必有; 过滤后的文件数超过 max_num_results 时为 true；next_page 仍为 null。; 支持:  |
| next_page | null | 必有; 不生效: 恒为 null，没有下一页搜索结果。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 添加文件 [#添加文件]

`POST /openai/v1/vector_stores/{vector_store_id}/files`

异步处理。重复加入同一文件返回已有记录，不应用新的属性或分段策略。

### 参数 [#参数-5]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求体 [#请求体-3]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| file_id | string | 必填; 上传文件返回的已有源 File ID；文件必须对调用方可见。; 最短字符数: 1 |
| attributes | object / null | 可选; 新附件的搜索筛选属性；省略或 null 表示不设置。重复加入已有文件不改变属性。 |
| chunking_strategy | object / object | 可选; auto 等同于每段 800 token、重叠 400 token。; 默认: &#123;"type":"auto"&#125; |
| chunking_strategy (1).type | "auto" | 必填; auto 使用默认静态分段：800 个估算 token，重叠 400 个。 |
| chunking_strategy (2).type | "static" | 必填; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (2).static | object | 必填; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (2).static.max_chunk_size_tokens | integer | 必填; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (2).static.chunk_overlap_tokens | integer | 必填; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |

### 请求示例 [#请求示例-6]

```bash
curl -X POST "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/files" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"file_id\":\"${FILE_ID}\"}"
```

### 响应 [#响应-6]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 列出文件 [#列出文件]

`GET /openai/v1/vector_stores/{vector_store_id}/files`

列出附件及入库状态，默认最新附件在前。使用 last\_id 作为 after 继续查询；?filter=failed 筛选可重新入库的失败文件。

### 参数 [#参数-6]

| 名称                | 位置与类型                                                        | 说明                                                                                    |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| vector\_store\_id | path: string                                                 | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1                                                  |
| after             | query: string                                                | 上一页的 ID 游标。 最短字符数: 1                                                                  |
| before            | query: string                                                | 返回此 ID 之前的条目。 最短字符数: 1                                                                |
| limit             | query: integer                                               | 每页条数。 最小: 1; 最大: 100; 默认: 20                                                          |
| order             | query: "asc" / "desc"                                        | 知识库和文件默认按创建时间降序；分段默认按序号升序。 默认: "desc"                                                 |
| filter            | query: "in\_progress" / "completed" / "failed" / "cancelled" | in\_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。省略时包含全部状态。 |

### 请求示例 [#请求示例-7]

```bash
curl -X GET "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/files" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-7]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| data[].id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| data[].object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| data[].vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| data[].last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| data[].last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| data[].last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| data[].usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| data[].created_at | integer | 必有; Unix 时间戳，单位秒。 |
| data[].chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| data[].chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| data[].chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| data[].chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| data[].chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| data[].chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| data[].attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取文件 [#读取文件]

`GET /openai/v1/vector_stores/{vector_store_id}/files/{file_id}`

使用添加附件或附件列表返回的 id 读取文件。可轮询此操作，直到 status 离开 in\_progress 后确认入库结果。

### 参数 [#参数-7]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求示例 [#请求示例-8]

```bash
curl -X GET "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-8]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 更新文件属性 [#更新文件属性]

`POST /openai/v1/vector_stores/{vector_store_id}/files/{file_id}`

替换已有附件的搜索筛选属性，不重新入库。使用附件 id。请求体示例：\{"attributes":\{"category":"refund"}}；null 清空属性。

### 参数 [#参数-8]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求体 [#请求体-4]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| attributes | object / null | 可选; 替换全部搜索筛选属性；null 清空属性。 |

### 请求示例 [#请求示例-9]

```bash
curl -X POST "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"attributes\":{\"category\":\"refund\"}}"
```

### 响应 [#响应-9]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 移除文件 [#移除文件]

`DELETE /openai/v1/vector_stores/{vector_store_id}/files/{file_id}`

返回后立即不再搜索到该文件；不会删除源文件。

### 参数 [#参数-9]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求示例 [#请求示例-10]

```bash
curl -X DELETE "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-10]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.file.deleted" | 必有; 对象标记；vector_store.file.deleted 表示此操作回执。 |
| deleted | true | 必有; 确认已从此知识库移出；源 File 未删除。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取抽取内容 [#读取抽取内容]

`GET /openai/v1/vector_stores/{vector_store_id}/files/{file_id}/content`

抽取文本按分段返回，可能重叠。图片内容可能是生成的描述，并非逐字 OCR。

### 参数 [#参数-10]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求示例 [#请求示例-11]

```bash
curl -X GET "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}/content" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-11]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "vector_store.file_content.page" | 必有; 对象标记；vector_store.file_content.page 表示提取的文件内容。 |
| data | object[] | 必有; 按分段序号排列的全部现存文本分段；相邻分段可能重叠。 |
| data[].type | "text" | 必有; text 表示提取出的文本分段。 |
| data[].text | string | 必有; 此分段的提取文本；可能与相邻分段重叠。 |
| has_more | false | 必有; 恒为 false；此响应返回全部现存分段。 |
| next_page | null | 必有; 恒为 null；提取内容不分页。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 创建文件批次 [#创建文件批次]

`POST /openai/v1/vector_stores/{vector_store_id}/file_batches`

批量添加已有 File 并异步入库。file\_ids 与 files 必须且只能提供一个；files 支持逐文件设置。已有附件直接复用。使用返回的批次 id 查询进度。

### 参数 [#参数-11]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求体 [#请求体-5]

file\_ids 与 files 必须且只能提供一个。已有文件直接复用，不修改属性或分段策略。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| (1).file_ids | string[] | 必填; 使用共同属性和分段设置的已有 File ID 列表。file_ids 与 files 二选一。; 最少条数: 1; 最多条数: 500 |
| (1).attributes | object / null | 可选; 用于每个新附件的搜索筛选属性；省略或 null 表示不设置。 |
| (1).chunking_strategy | object / object | 可选; auto 等同于每段 800 token、重叠 400 token。; 默认: &#123;"type":"auto"&#125; |
| (1).chunking_strategy (1).type | "auto" | 必填; auto 使用默认静态分段：800 个估算 token，重叠 400 个。 |
| (1).chunking_strategy (2).type | "static" | 必填; static 表示使用显式分段大小与重叠设置。 |
| (1).chunking_strategy (2).static | object | 必填; 以估算 token 数表示的分段大小与重叠限制。 |
| (1).chunking_strategy (2).static.max_chunk_size_tokens | integer | 必填; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| (1).chunking_strategy (2).static.chunk_overlap_tokens | integer | 必填; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| (2).files | object[] | 必填; 分别指定属性和分段设置的附件列表；忽略顶层 attributes 与 chunking_strategy。; 最少条数: 1; 最多条数: 500 |
| (2).files[].file_id | string | 必填; 上传文件返回的已有源 File ID；文件必须对调用方可见。; 最短字符数: 1 |
| (2).files[].attributes | object | 可选; 用于搜索筛选的文件属性。最多 16 个键，键最多 64 字符，字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string / number / boolean |
| (2).files[].chunking_strategy | object / object | 可选; auto 等同于每段 800 token、重叠 400 token。; 默认: &#123;"type":"auto"&#125; |
| (2).files[].chunking_strategy (1).type | "auto" | 必填; auto 使用默认静态分段：800 个估算 token，重叠 400 个。 |
| (2).files[].chunking_strategy (2).type | "static" | 必填; static 表示使用显式分段大小与重叠设置。 |
| (2).files[].chunking_strategy (2).static | object | 必填; 以估算 token 数表示的分段大小与重叠限制。 |
| (2).files[].chunking_strategy (2).static.max_chunk_size_tokens | integer | 必填; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| (2).files[].chunking_strategy (2).static.chunk_overlap_tokens | integer | 必填; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| (2).attributes | JSON | 可选; 不生效: 使用 files 时不生效。 |
| (2).chunking_strategy | JSON | 可选; 不生效: 使用 files 时不生效。 |

### 请求示例 [#请求示例-12]

```bash
curl -X POST "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/file_batches" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"file_ids\":[\"${FILE_ID}\"]}"
```

### 响应 [#响应-12]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.files_batch" | 必有; 对象标记；vector_store.files_batch 表示批量附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; cancelled 表示批次已取消；否则 in_progress 表示仍有成员入库中，failed 表示入库结束且有失败成员，completed 表示无入库中或失败成员。取消终态批次不会改变它。 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取文件批次 [#读取文件批次]

`GET /openai/v1/vector_stores/{vector_store_id}/file_batches/{batch_id}`

读取此知识库中创建的批次，包括当前状态和文件计数。使用创建批次返回的 id 监测入库结果。

### 参数 [#参数-12]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| batch\_id         | path: string | 必填；此知识库创建批次时返回的文件批次 ID。 最短字符数: 1     |

### 请求示例 [#请求示例-13]

```bash
curl -X GET "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/file_batches/${BATCH_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-13]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.files_batch" | 必有; 对象标记；vector_store.files_batch 表示批量附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; cancelled 表示批次已取消；否则 in_progress 表示仍有成员入库中，failed 表示入库结束且有失败成员，completed 表示无入库中或失败成员。取消终态批次不会改变它。 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 取消文件批次 [#取消文件批次]

`POST /openai/v1/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel`

只取消处理中的批次和文件。已完成、失败或已取消的批次原样返回（200，幂等），计数不变。

### 参数 [#参数-13]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| batch\_id         | path: string | 必填；此知识库创建批次时返回的文件批次 ID。 最短字符数: 1     |

### 请求示例 [#请求示例-14]

```bash
curl -X POST "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/file_batches/${BATCH_ID}/cancel" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-14]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.files_batch" | 必有; 对象标记；vector_store.files_batch 表示批量附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; cancelled 表示批次已取消；否则 in_progress 表示仍有成员入库中，failed 表示入库结束且有失败成员，completed 表示无入库中或失败成员。取消终态批次不会改变它。 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 列出批次文件 [#列出批次文件]

`GET /openai/v1/vector_stores/{vector_store_id}/file_batches/{batch_id}/files`

列出指定批次仍在库中的附件，默认最新附件在前。使用批次创建返回的 id；?filter=failed 查看失败文件，last\_id 可作为下一页 after。

### 参数 [#参数-14]

| 名称                | 位置与类型                                                        | 说明                                                                                    |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| vector\_store\_id | path: string                                                 | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1                                                  |
| batch\_id         | path: string                                                 | 必填；此知识库创建批次时返回的文件批次 ID。 最短字符数: 1                                                      |
| after             | query: string                                                | 上一页的 ID 游标。 最短字符数: 1                                                                  |
| before            | query: string                                                | 返回此 ID 之前的条目。 最短字符数: 1                                                                |
| limit             | query: integer                                               | 每页条数。 最小: 1; 最大: 100; 默认: 20                                                          |
| order             | query: "asc" / "desc"                                        | 知识库和文件默认按创建时间降序；分段默认按序号升序。 默认: "desc"                                                 |
| filter            | query: "in\_progress" / "completed" / "failed" / "cancelled" | in\_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。省略时包含全部状态。 |

### 请求示例 [#请求示例-15]

```bash
curl -X GET "https://api.deepraxis.ai/openai/v1/vector_stores/${VECTOR_STORE_ID}/file_batches/${BATCH_ID}/files" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-15]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| data[].id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| data[].object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| data[].vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| data[].last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| data[].last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| data[].last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| data[].usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| data[].created_at | integer | 必有; Unix 时间戳，单位秒。 |
| data[].chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| data[].chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| data[].chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| data[].chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| data[].chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| data[].chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| data[].attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

# Anthropic 兼容接口

## 基础地址 [#基础地址]

## 接入 [#接入]

## 端点 [#端点]

| 方法     | 路径                                                                           | 说明       | 支持     |
| ------ | ---------------------------------------------------------------------------- | -------- | ------ |
| POST   | [`/v1/messages`](/docs/api/compatible/anthropic/createMessage)               | 发送消息     | ● 支持   |
| POST   | [`/v1/messages/count_tokens`](/docs/api/compatible/anthropic/countTokens)    | 统计 token | ◐ 部分支持 |
| GET    | [`/v1/models`](/docs/api/compatible/anthropic/listModels)                    | 列出模型     | ● 支持   |
| POST   | [`/v1/files`](/docs/api/compatible/anthropic/createFile)                     | 上传文件     | ● 支持   |
| GET    | [`/v1/files`](/docs/api/compatible/anthropic/listFiles)                      | 列出文件     | ● 支持   |
| GET    | [`/v1/files/{file_id}`](/docs/api/compatible/anthropic/retrieveFile)         | 读取文件信息   | ● 支持   |
| DELETE | [`/v1/files/{file_id}`](/docs/api/compatible/anthropic/deleteFile)           | 删除文件     | ● 支持   |
| GET    | [`/v1/files/{file_id}/content`](/docs/api/compatible/anthropic/downloadFile) | 下载文件内容   | ● 支持   |

## 与官方的差异 [#与官方的差异]

* <a href="/docs/api/compatible/anthropic/createMessage">发送消息</a>：支持顶层 cache\_control、top\_k、metadata.user\_id、output\_config.format、thinking.display 与 anthropic-user-profile-id。仅原生 Anthropic 能表达的选项会限制路由；没有可保真供应时返回参数错误。anthropic-workspace-id 尚未支持，非空值返回 400。container、inference\_geo 与 service\_tier 接受并忽略；其他扩展见字段支持标注。 未知顶层字段原样转发给同协议上游，由上游决定是否接受；已声明字段的类型与取值范围仍会校验，不合法时返回 400 并点名字段。
* <a href="/docs/api/compatible/anthropic/countTokens">统计 token</a>：按模型族校准的估算值（包括中文和工具定义），响应头为 x-praxis-token-count: estimated；不能用作精确用量或计费依据。
* <a href="/docs/api/compatible/anthropic/listModels">列出模型</a>：始终返回 capabilities、max\_input\_tokens、max\_tokens；目录无法确定的值为 null，不将总上下文窗口冒充独立输入上限。非空 anthropic-workspace-id 返回 400；尚不按 anthropic-beta 选择目录版本。
* <a href="/docs/api/compatible/anthropic/createFile">上传文件</a>：SDK 0.128.0 上传参数为表单 file 和可选的表单 expires\_in\_seconds（3600–7776000 秒）。其他表单字段（包括 purpose）返回 400 invalid\_request\_error，消息形如 "purpose: Extra inputs are not permitted"；查询参数只接受 SDK 自带的 beta，其他查询参数返回 400，查询参数 expires\_in\_seconds 会提示改放表单。平台将上传文件记为 user\_data；不支持 anthropic-workspace-id，请求携带该头时返回 400。
* <a href="/docs/api/compatible/anthropic/listFiles">列出文件</a>：按创建时间从新到旧排列。用 after\_id / before\_id 与 limit 分页（两者同时给返回 400），也可以用 page 游标（next\_page）；三者只能选一个。响应包含 data、has\_more、first\_id、last\_id 与 next\_page。ids（最多 100 个去重 ID）与 page、after\_id、before\_id、limit 互斥。scope\_id 需要 anthropic-beta: managed-agents-2026-04-01 请求头；缺少该头返回 400，不存在的会话范围返回 404。anthropic-workspace-id 返回 400。
* <a href="/docs/api/compatible/anthropic/downloadFile">下载文件内容</a>：只有代码执行工具生成的文件可以下载；你自己上传的文件（用途为 user\_data）下载会返回 400 invalid\_request\_error，这与 Anthropic 官方的行为一致。

参数与字段的权威定义以 [Anthropic 官方文档](https://docs.anthropic.com/en/api)为准。

错误按 Anthropic 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 发送消息

## 响应 [#响应]

### HTTP 200 [#http-200]

Message created

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique object identifier.  The format and length of IDs may change over time. |
| container | null &#124; object | Information about the container used in the request (for the code execution tool) |
| container.id | string | Identifier for the container used in this request |
| container.expires_at | string | The time at which the container will expire. |
| container.skills | null &#124; array&lt;object&gt; | Skills loaded in the container |
| content | array&lt;object&gt; | Content generated by the model.  This is an array of content blocks, each of which has a &#96;type&#96; that determines its shape.  Example:  &#96;&#96;&#96;json [&#123; "type": "text", "text": "Hi, I'm Claude." &#125;] &#96;&#96;&#96;  If the request input &#96;messages&#96; ended with an &#96;assistant&#96; turn, then the response &#96;content&#96; will continue directly from that last turn. You can use this to constrain the model's output.  For example, if the input &#96;messages&#96; were:  &#96;&#96;&#96;json [   &#123;     "role": "user",     "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"   &#125;,   &#123; "role": "assistant", "content": "The best answer is (" &#125; ] &#96;&#96;&#96;  Then the response &#96;content&#96; might be:  &#96;&#96;&#96;json [&#123; "type": "text", "text": "B)" &#125;] &#96;&#96;&#96; |
| content[].citations | null &#124; array&lt;object&gt; | Citations supporting the text block.  The type of citation returned will depend on the type of document being cited. Citing a PDF results in &#96;page_location&#96;, plain text results in &#96;char_location&#96;, and content document results in &#96;content_block_location&#96;. |
| content[].text | string | The text generated by the model. |
| content[].type | string | Always &#96;text&#96;. Discriminator that marks this object as a TextBlock in a &#96;type&#96;-tagged union. / Always &#96;thinking&#96;. Discriminator that marks this object as a ThinkingBlock in a &#96;type&#96;-tagged union. / Always &#96;redacted_thinking&#96;. Discriminator that marks this object as a RedactedThinkingBlock in a &#96;type&#96;-tagged union. / Always &#96;tool_use&#96;. Discriminator that marks this object as a ToolUseBlock in a &#96;type&#96;-tagged union. / Always &#96;server_tool_use&#96;. Discriminator that marks this object as a ServerToolUseBlock in a &#96;type&#96;-tagged union. / Always &#96;web_search_tool_result&#96;. Discriminator that marks this object as a WebSearchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;web_fetch_tool_result&#96;. Discriminator that marks this object as a WebFetchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;code_execution_tool_result&#96;. Discriminator that marks this object as a CodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;bash_code_execution_tool_result&#96;. Discriminator that marks this object as a BashCodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;text_editor_code_execution_tool_result&#96;. Discriminator that marks this object as a TextEditorCodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;tool_search_tool_result&#96;. Discriminator that marks this object as a ToolSearchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;container_upload&#96;. Discriminator that marks this object as a ContainerUploadBlock in a &#96;type&#96;-tagged union. |
| content[].signature | string | A value used to verify that this thinking block was generated by Claude when it is passed back to the API.  This is an opaque field and should not be interpreted or parsed. When passing thinking blocks back to the API (required when using tools with extended thinking), pass them back exactly as received, with this field intact.  See [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) for details. |
| content[].thinking | string | The text of Claude's thinking process for this block. |
| content[].data | string | The contents of this redacted thinking block, returned when portions of the model's thinking were safety-redacted. This field is opaque and encrypted, with no readable content.  Pass &#96;redacted_thinking&#96; blocks back to the API unchanged when continuing a multi-turn conversation.  See [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#redacted-thinking-blocks) for details. |
| content[].id | string | Id of the tool call; send it back as tool_use_id in the tool_result block that answers it. / Id of the server tool call; the matching result block repeats it as tool_use_id. |
| content[].caller | object | Which party invoked the tool: the model directly or a code execution tool. / Which party invoked the server tool: the model directly or a code execution tool. / Which party invoked the search: the model directly or a code execution tool. / Which party invoked the fetch: the model directly or a code execution tool. |
| content[].input | any | Arguments the model chose, as a JSON object that follows the tool's input_schema. / Arguments the model passed to the server tool, as a JSON object. |
| content[].name | string | Name of the tool the model wants to call. / Name of the server tool the model called, such as web_search, web_fetch or code_execution. |
| content[].toolset_name | null &#124; string | For a toolset member tool_use, the toolset family. |
| content[].content | object &#124; array&lt;object&gt; &#124; object &#124; object &#124; object &#124; object &#124; object | Search results (array of web_search_result blocks) or an error object. / The fetched document or an error object. / Result of the code execution: a result block, an encrypted result block, or an error object. / Result of the bash command: a result block or an error object. / Result of the text editor command: a view, create or str_replace result block, or an error object. / Result of the tool search: a search result block that lists tool references, or an error object. |
| content[].tool_use_id | string | Id of the web_search server tool call this result belongs to. / Id of the web_fetch server tool call this result belongs to. / Id of the code_execution server tool call this result belongs to. / Id of the bash_code_execution server tool call this result belongs to. / Id of the text_editor_code_execution server tool call this result belongs to. / Id of the tool search server tool call this result belongs to. |
| content[].file_id | string | Id of the file that was uploaded into the code execution container. |
| model | string | The model that will complete your prompt.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| role | string | Conversational role of the generated message.  This will always be &#96;"assistant"&#96;. |
| stop_details | null &#124; object | Structured information about a refusal. |
| stop_details.category | null &#124; string | The policy category that triggered a refusal.  - &#96;cyber&#96; - The request could enable cyber harm, such as malware or exploit   development. Benign cybersecurity work can also trigger this category. - &#96;bio&#96; - The request could enable biological harm, such as dangerous lab   methods. Beneficial life sciences work can also trigger this category. - &#96;frontier_llm&#96; - The request could assist the development of competing AI   models, which is restricted under   [Anthropic's commercial terms](https://www.anthropic.com/legal/commercial-terms).   Benign machine learning work can also trigger this category. - &#96;reasoning_extraction&#96; - The request asks the model to reproduce its internal   reasoning in the response text. To get reasoning in a structured form instead,   use   [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking). - &#96;general_harms&#96; - The request could be related to an area that was determined   as harmful. Benign work might sometimes trigger this category. |
| stop_details.explanation | null &#124; string | Human-readable explanation of the refusal.  This text is not guaranteed to be stable. &#96;null&#96; when no explanation is available for the category. |
| stop_details.type | string | Always &#96;refusal&#96;. Discriminator that marks this object as a RefusalStopDetails in a &#96;type&#96;-tagged union. |
| stop_reason | null &#124; string | The reason that we stopped.  This may be one the following values:  - &#96;"end_turn"&#96;: the model reached a natural stopping point - &#96;"max_tokens"&#96;: we exceeded the requested &#96;max_tokens&#96; or the model's maximum - &#96;"stop_sequence"&#96;: one of your provided custom &#96;stop_sequences&#96; was generated - &#96;"tool_use"&#96;: the model invoked one or more tools - &#96;"pause_turn"&#96;: we paused a long-running turn. You may provide the response   back as-is in a subsequent request to let the model continue. - &#96;"refusal"&#96;: when streaming classifiers intervene to handle potential policy   violations - &#96;"model_context_window_exceeded"&#96;: we exceeded the model's context window  In non-streaming mode this value is always non-null. In streaming mode, it is null in the &#96;message_start&#96; event and non-null otherwise. |
| stop_sequence | null &#124; string | Which custom stop sequence was generated, if any.  This value will be a non-null string if one of your custom stop sequences was generated. |
| type | string | Object type.  For Messages, this is always &#96;"message"&#96;. |
| usage | object | Billing and rate-limit usage.  Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.  Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in &#96;usage&#96; will not match one-to-one with the exact visible content of an API request or response.  For example, &#96;output_tokens&#96; will be non-zero, even for an empty string response from Claude.  Total input tokens in a request is the summation of &#96;input_tokens&#96;, &#96;cache_creation_input_tokens&#96;, and &#96;cache_read_input_tokens&#96;. |
| usage.cache_creation | null &#124; object | Breakdown of cached tokens by TTL |
| usage.cache_creation_input_tokens | null &#124; number | The number of input tokens used to create the cache entry. |
| usage.cache_read_input_tokens | null &#124; number | The number of input tokens read from the cache. |
| usage.inference_geo | null &#124; string | The geographic region where inference was performed for this request. |
| usage.input_tokens | number | The number of input tokens which were used. |
| usage.output_tokens | number | The number of output tokens which were used. |
| usage.output_tokens_details | null &#124; object | Breakdown of output tokens by category.  &#96;output_tokens&#96; remains the inclusive, authoritative total used for billing. This object provides a read-only decomposition for observability — for example, how many of the billed output tokens were spent on internal reasoning that may have been summarized before being returned to you. |
| usage.server_tool_use | null &#124; object | The number of server tool requests. |
| usage.service_tier | null &#124; string | If the request used the priority, standard, or batch tier. |

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| delta | object | Final fields of the message sent with message_delta: why generation stopped and the container. / The incremental change to the content block at index. |
| delta.container | null &#124; object | Information about the container used in the request (for the code execution tool) |
| delta.stop_details | null &#124; object | Structured information about a refusal. |
| delta.stop_reason | null &#124; string | Why the model stopped; null while the message is still generating. |
| delta.stop_sequence | null &#124; string | The custom stop sequence that was matched; null unless stop_reason is stop_sequence. |
| delta.text | string | Text fragment to append to the text block. |
| delta.type | string | Always &#96;text_delta&#96;. Discriminator that marks this object as a TextDelta in a &#96;type&#96;-tagged union. / Always &#96;input_json_delta&#96;. Discriminator that marks this object as a InputJSONDelta in a &#96;type&#96;-tagged union. / Always &#96;citations_delta&#96;. Discriminator that marks this object as a CitationsDelta in a &#96;type&#96;-tagged union. / Always &#96;thinking_delta&#96;. Discriminator that marks this object as a ThinkingDelta in a &#96;type&#96;-tagged union. / Always &#96;signature_delta&#96;. Discriminator that marks this object as a SignatureDelta in a &#96;type&#96;-tagged union. |
| delta.partial_json | string | Fragment of the tool input JSON string; concatenate all fragments of a block and parse the result when the block stops. |
| delta.citation | object | The citation to attach to the text block being streamed. |
| delta.thinking | string | The incremental &#96;thinking&#96; text for this content block. Concatenate the &#96;thinking&#96; values of successive &#96;thinking_delta&#96; events to assemble the block's full &#96;thinking&#96; value. |
| delta.signature | string | The &#96;signature&#96; for this thinking block: an opaque value used to verify that the block was generated by Claude when it is passed back to the API. Delivered in a &#96;signature_delta&#96; event just before the block's &#96;content_block_stop&#96; event. |
| type | string | Always &#96;message_delta&#96;. Discriminator that marks this object as a RawMessageDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;content_block_delta&#96;. Discriminator that marks this object as a RawContentBlockDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;message_start&#96;. Discriminator that marks this object as a RawMessageStartEvent in a &#96;type&#96;-tagged union. / Always &#96;message_stop&#96;. Discriminator that marks this object as a RawMessageStopEvent in a &#96;type&#96;-tagged union. / Always &#96;content_block_start&#96;. Discriminator that marks this object as a RawContentBlockStartEvent in a &#96;type&#96;-tagged union. / Always &#96;content_block_stop&#96;. Discriminator that marks this object as a RawContentBlockStopEvent in a &#96;type&#96;-tagged union. |
| usage | object | Billing and rate-limit usage.  Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.  Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in &#96;usage&#96; will not match one-to-one with the exact visible content of an API request or response.  For example, &#96;output_tokens&#96; will be non-zero, even for an empty string response from Claude.  Total input tokens in a request is the summation of &#96;input_tokens&#96;, &#96;cache_creation_input_tokens&#96;, and &#96;cache_read_input_tokens&#96;. |
| usage.cache_creation_input_tokens | null &#124; number | The cumulative number of input tokens used to create the cache entry. |
| usage.cache_read_input_tokens | null &#124; number | The cumulative number of input tokens read from the cache. |
| usage.input_tokens | null &#124; number | The cumulative number of input tokens which were used. |
| usage.output_tokens | number | The cumulative number of output tokens which were used. |
| usage.output_tokens_details | null &#124; object | Breakdown of output tokens by category.  &#96;output_tokens&#96; remains the inclusive, authoritative total used for billing. This object provides a read-only decomposition for observability — for example, how many of the billed output tokens were spent on internal reasoning that may have been summarized before being returned to you. |
| usage.server_tool_use | null &#124; object | The number of server tool requests. |
| index | number | Zero-based index of the content block this delta applies to. / Zero-based index of the content block that starts. / Zero-based index of the content block that ends. |
| message | object | The complete Message object being started; its content is empty at message_start and filled by the following content_block events. |
| message.id | string | Unique object identifier.  The format and length of IDs may change over time. |
| message.container | null &#124; object | Information about the container used in the request (for the code execution tool) |
| message.content | array&lt;object&gt; | Content generated by the model.  This is an array of content blocks, each of which has a &#96;type&#96; that determines its shape.  Example:  &#96;&#96;&#96;json [&#123; "type": "text", "text": "Hi, I'm Claude." &#125;] &#96;&#96;&#96;  If the request input &#96;messages&#96; ended with an &#96;assistant&#96; turn, then the response &#96;content&#96; will continue directly from that last turn. You can use this to constrain the model's output.  For example, if the input &#96;messages&#96; were:  &#96;&#96;&#96;json [   &#123;     "role": "user",     "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"   &#125;,   &#123; "role": "assistant", "content": "The best answer is (" &#125; ] &#96;&#96;&#96;  Then the response &#96;content&#96; might be:  &#96;&#96;&#96;json [&#123; "type": "text", "text": "B)" &#125;] &#96;&#96;&#96; |
| message.model | string | The model that will complete your prompt.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| message.role | string | Conversational role of the generated message.  This will always be &#96;"assistant"&#96;. |
| message.stop_details | null &#124; object | Structured information about a refusal. |
| message.stop_reason | null &#124; string | The reason that we stopped.  This may be one the following values:  - &#96;"end_turn"&#96;: the model reached a natural stopping point - &#96;"max_tokens"&#96;: we exceeded the requested &#96;max_tokens&#96; or the model's maximum - &#96;"stop_sequence"&#96;: one of your provided custom &#96;stop_sequences&#96; was generated - &#96;"tool_use"&#96;: the model invoked one or more tools - &#96;"pause_turn"&#96;: we paused a long-running turn. You may provide the response   back as-is in a subsequent request to let the model continue. - &#96;"refusal"&#96;: when streaming classifiers intervene to handle potential policy   violations - &#96;"model_context_window_exceeded"&#96;: we exceeded the model's context window  In non-streaming mode this value is always non-null. In streaming mode, it is null in the &#96;message_start&#96; event and non-null otherwise. |
| message.stop_sequence | null &#124; string | Which custom stop sequence was generated, if any.  This value will be a non-null string if one of your custom stop sequences was generated. |
| message.type | string | Object type.  For Messages, this is always &#96;"message"&#96;. |
| message.usage | object | Billing and rate-limit usage.  Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.  Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in &#96;usage&#96; will not match one-to-one with the exact visible content of an API request or response.  For example, &#96;output_tokens&#96; will be non-zero, even for an empty string response from Claude.  Total input tokens in a request is the summation of &#96;input_tokens&#96;, &#96;cache_creation_input_tokens&#96;, and &#96;cache_read_input_tokens&#96;. |
| content_block | object | The content block as it starts, with empty text or input to be filled by deltas. |
| content_block.citations | null &#124; array&lt;object&gt; | Citations supporting the text block.  The type of citation returned will depend on the type of document being cited. Citing a PDF results in &#96;page_location&#96;, plain text results in &#96;char_location&#96;, and content document results in &#96;content_block_location&#96;. |
| content_block.text | string | The text generated by the model. |
| content_block.type | string | Always &#96;text&#96;. Discriminator that marks this object as a TextBlock in a &#96;type&#96;-tagged union. / Always &#96;thinking&#96;. Discriminator that marks this object as a ThinkingBlock in a &#96;type&#96;-tagged union. / Always &#96;redacted_thinking&#96;. Discriminator that marks this object as a RedactedThinkingBlock in a &#96;type&#96;-tagged union. / Always &#96;tool_use&#96;. Discriminator that marks this object as a ToolUseBlock in a &#96;type&#96;-tagged union. / Always &#96;server_tool_use&#96;. Discriminator that marks this object as a ServerToolUseBlock in a &#96;type&#96;-tagged union. / Always &#96;web_search_tool_result&#96;. Discriminator that marks this object as a WebSearchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;web_fetch_tool_result&#96;. Discriminator that marks this object as a WebFetchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;code_execution_tool_result&#96;. Discriminator that marks this object as a CodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;bash_code_execution_tool_result&#96;. Discriminator that marks this object as a BashCodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;text_editor_code_execution_tool_result&#96;. Discriminator that marks this object as a TextEditorCodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;tool_search_tool_result&#96;. Discriminator that marks this object as a ToolSearchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;container_upload&#96;. Discriminator that marks this object as a ContainerUploadBlock in a &#96;type&#96;-tagged union. |
| content_block.signature | string | A value used to verify that this thinking block was generated by Claude when it is passed back to the API.  This is an opaque field and should not be interpreted or parsed. When passing thinking blocks back to the API (required when using tools with extended thinking), pass them back exactly as received, with this field intact.  See [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) for details. |
| content_block.thinking | string | The text of Claude's thinking process for this block. |
| content_block.data | string | The contents of this redacted thinking block, returned when portions of the model's thinking were safety-redacted. This field is opaque and encrypted, with no readable content.  Pass &#96;redacted_thinking&#96; blocks back to the API unchanged when continuing a multi-turn conversation.  See [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#redacted-thinking-blocks) for details. |
| content_block.id | string | Id of the tool call; send it back as tool_use_id in the tool_result block that answers it. / Id of the server tool call; the matching result block repeats it as tool_use_id. |
| content_block.caller | object | Which party invoked the tool: the model directly or a code execution tool. / Which party invoked the server tool: the model directly or a code execution tool. / Which party invoked the search: the model directly or a code execution tool. / Which party invoked the fetch: the model directly or a code execution tool. |
| content_block.input | any | Arguments the model chose, as a JSON object that follows the tool's input_schema. / Arguments the model passed to the server tool, as a JSON object. |
| content_block.name | string | Name of the tool the model wants to call. / Name of the server tool the model called, such as web_search, web_fetch or code_execution. |
| content_block.toolset_name | null &#124; string | For a toolset member tool_use, the toolset family. |
| content_block.content | object &#124; array&lt;object&gt; &#124; object &#124; object &#124; object &#124; object &#124; object | Search results (array of web_search_result blocks) or an error object. / The fetched document or an error object. / Result of the code execution: a result block, an encrypted result block, or an error object. / Result of the bash command: a result block or an error object. / Result of the text editor command: a view, create or str_replace result block, or an error object. / Result of the tool search: a search result block that lists tool references, or an error object. |
| content_block.tool_use_id | string | Id of the web_search server tool call this result belongs to. / Id of the web_fetch server tool call this result belongs to. / Id of the code_execution server tool call this result belongs to. / Id of the bash_code_execution server tool call this result belongs to. / Id of the text_editor_code_execution server tool call this result belongs to. / Id of the tool search server tool call this result belongs to. |
| content_block.file_id | string | Id of the file that was uploaded into the code execution container. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Token count

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| input_tokens | number | The total number of tokens across the provided list of messages, system prompt, and tools. |

# 列出模型

## 响应 [#响应]

### HTTP 200 [#http-200]

Models listed

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique model identifier. |
| data[].capabilities | null &#124; object | Model capability information. |
| data[].created_at | string | RFC 3339 datetime string representing the time at which the model was released. May be set to an epoch value if the release date is unknown. |
| data[].display_name | string | A human-readable name for the model. |
| data[].max_input_tokens | null &#124; number | Maximum input context window size in tokens for this model. |
| data[].max_tokens | null &#124; number | Maximum value for the &#96;max_tokens&#96; parameter when using this model. |
| data[].type | string | Object type.  For Models, this is always &#96;"model"&#96;. |
| has_more | boolean |  |
| first_id | null &#124; string |  |
| last_id | null &#124; string |  |

# 上传文件

## 响应 [#响应]

### HTTP 200 [#http-200]

File uploaded

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique object identifier.  The format and length of IDs may change over time. |
| created_at | string | RFC 3339 datetime string representing when the file was created. |
| filename | string | Original filename of the uploaded file. |
| mime_type | string | MIME type of the file. |
| size_bytes | number | Size of the file in bytes. |
| type | string | Object type.  For files, this is always &#96;"file"&#96;. |
| downloadable | boolean | Whether the file can be downloaded. |
| expires_at | null &#124; string | RFC 3339 datetime string representing when the file will expire and become unavailable for download. Null if the file does not expire. For files uploaded with &#96;expires_in_seconds&#96;, this is the upload time plus that value. |
| scope | null &#124; object | The scope of this file, indicating the context in which it was created (e.g., a session). |
| scope.id | string | The ID of the scoping resource (e.g., the session ID). |
| scope.type | string | The type of scope (e.g., &#96;"session"&#96;). |

# 列出文件

## 响应 [#响应]

### HTTP 200 [#http-200]

Files listed

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique object identifier.  The format and length of IDs may change over time. |
| data[].created_at | string | RFC 3339 datetime string representing when the file was created. |
| data[].filename | string | Original filename of the uploaded file. |
| data[].mime_type | string | MIME type of the file. |
| data[].size_bytes | number | Size of the file in bytes. |
| data[].type | string | Object type.  For files, this is always &#96;"file"&#96;. |
| data[].downloadable | boolean | Whether the file can be downloaded. |
| data[].expires_at | null &#124; string | RFC 3339 datetime string representing when the file will expire and become unavailable for download. Null if the file does not expire. For files uploaded with &#96;expires_in_seconds&#96;, this is the upload time plus that value. |
| data[].scope | null &#124; object | The scope of this file, indicating the context in which it was created (e.g., a session). |
| next_page | null &#124; string |  |

# 读取文件信息

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Metadata

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique object identifier.  The format and length of IDs may change over time. |
| created_at | string | RFC 3339 datetime string representing when the file was created. |
| filename | string | Original filename of the uploaded file. |
| mime_type | string | MIME type of the file. |
| size_bytes | number | Size of the file in bytes. |
| type | string | Object type.  For files, this is always &#96;"file"&#96;. |
| downloadable | boolean | Whether the file can be downloaded. |
| expires_at | null &#124; string | RFC 3339 datetime string representing when the file will expire and become unavailable for download. Null if the file does not expire. For files uploaded with &#96;expires_in_seconds&#96;, this is the upload time plus that value. |
| scope | null &#124; object | The scope of this file, indicating the context in which it was created (e.g., a session). |
| scope.id | string | The ID of the scoping resource (e.g., the session ID). |
| scope.type | string | The type of scope (e.g., &#96;"session"&#96;). |

# 删除文件

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Deleted

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | ID of the deleted file. |
| type | string | Deleted object type.  For file deletion, this is always &#96;"file_deleted"&#96;. |

# 下载文件内容

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Binary content

未声明响应体。

# Claude 托管智能体 API

## 基础地址 [#基础地址]

## 接入 [#接入]

## 运行一次会话 [#运行一次会话]

1. [创建智能体](/docs/api/compatible/anthropic/managed-agents/createAgent)，保存返回的 `agent_…` ID。
2. [创建会话](/docs/api/compatible/anthropic/managed-agents/createSession)，将 `agent` 替换为该 ID，保存 `sesn_…` ID。
3. 先[订阅事件流](/docs/api/compatible/anthropic/managed-agents/streamEvents)，再[发送消息](/docs/api/compatible/anthropic/managed-agents/sendEvents)。将两个请求的会话 ID 替换为同一个真实 ID。
4. 收到 `agent.message` 后等待 `session.status_idle`；也可[查询历史事件](/docs/api/compatible/anthropic/managed-agents/listEvents)。

SDK 基础地址就是上面的基础地址。每个请求均需 API Key、`anthropic-version: 2023-06-01` 和 `anthropic-beta: managed-agents-2026-04-01`。在线试调会自动带上这些协议头，资源 ID 需自行替换。

官方 95 个操作已全部声明：其中 41 个已支持或部分支持（见端点清单徽标）；其余 54 个平台尚未实现，调用如实返回 501（not\_implemented\_error，响应带 x-should-retry: false），不产生任何副作用、不计费。各项能力与凭据库的具体限制见端点说明。

## 端点 [#端点]

### 智能体（6 个端点，6 个可用） [#智能体6-个端点6-个可用]

| 方法   | 路径                                                                                                  | 说明    | 支持     |
| ---- | --------------------------------------------------------------------------------------------------- | ----- | ------ |
| POST | [`/v1/agents`](/docs/api/compatible/anthropic/managed-agents/createAgent)                           | 创建智能体 | ◐ 部分支持 |
| GET  | [`/v1/agents`](/docs/api/compatible/anthropic/managed-agents/listAgents)                            | 列出智能体 | ● 支持   |
| GET  | [`/v1/agents/{agent_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveAgent)              | 读取智能体 | ● 支持   |
| POST | [`/v1/agents/{agent_id}`](/docs/api/compatible/anthropic/managed-agents/updateAgent)                | 更新智能体 | ◐ 部分支持 |
| GET  | [`/v1/agents/{agent_id}/versions`](/docs/api/compatible/anthropic/managed-agents/listAgentVersions) | 列出版本  | ● 支持   |
| POST | [`/v1/agents/{agent_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveAgent)       | 归档智能体 | ● 支持   |

### 会话与事件（9 个端点，8 个可用） [#会话与事件9-个端点8-个可用]

| 方法     | 路径                                                                                                      | 说明   | 支持     |
| ------ | ------------------------------------------------------------------------------------------------------- | ---- | ------ |
| POST   | [`/v1/sessions`](/docs/api/compatible/anthropic/managed-agents/createSession)                           | 创建会话 | ◐ 部分支持 |
| GET    | [`/v1/sessions`](/docs/api/compatible/anthropic/managed-agents/listSessions)                            | 列出会话 | ◐ 部分支持 |
| GET    | [`/v1/sessions/{session_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveSession)            | 读取会话 | ● 支持   |
| POST   | [`/v1/sessions/{session_id}/events`](/docs/api/compatible/anthropic/managed-agents/sendEvents)          | 发送事件 | ◐ 部分支持 |
| GET    | [`/v1/sessions/{session_id}/events`](/docs/api/compatible/anthropic/managed-agents/listEvents)          | 列出事件 | ● 支持   |
| GET    | [`/v1/sessions/{session_id}/events/stream`](/docs/api/compatible/anthropic/managed-agents/streamEvents) | 订阅事件 | ◐ 部分支持 |
| POST   | [`/v1/sessions/{session_id}`](/docs/api/compatible/anthropic/managed-agents/updateSession)              | 更新会话 | ◐ 部分支持 |
| DELETE | [`/v1/sessions/{session_id}`](/docs/api/compatible/anthropic/managed-agents/deleteSession)              | 删除会话 | ○ 未支持  |
| POST   | [`/v1/sessions/{session_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveSession)     | 归档会话 | ● 支持   |

### 定时部署（10 个端点，0 个可用） [#定时部署10-个端点0-个可用]

| 方法   | 路径                                                                                                               | 说明     | 支持    |
| ---- | ---------------------------------------------------------------------------------------------------------------- | ------ | ----- |
| GET  | [`/v1/deployment_runs`](/docs/api/compatible/anthropic/managed-agents/listDeploymentRuns)                        | 列出部署运行 | ○ 未支持 |
| GET  | [`/v1/deployment_runs/{deployment_run_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveDeploymentRun) | 读取部署运行 | ○ 未支持 |
| GET  | [`/v1/deployments`](/docs/api/compatible/anthropic/managed-agents/listDeployments)                               | 列出部署   | ○ 未支持 |
| POST | [`/v1/deployments`](/docs/api/compatible/anthropic/managed-agents/createDeployment)                              | 创建部署   | ○ 未支持 |
| GET  | [`/v1/deployments/{deployment_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveDeployment)            | 读取部署   | ○ 未支持 |
| POST | [`/v1/deployments/{deployment_id}`](/docs/api/compatible/anthropic/managed-agents/updateDeployment)              | 更新部署   | ○ 未支持 |
| POST | [`/v1/deployments/{deployment_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveDeployment)     | 归档部署   | ○ 未支持 |
| POST | [`/v1/deployments/{deployment_id}/pause`](/docs/api/compatible/anthropic/managed-agents/pauseDeployment)         | 暂停部署   | ○ 未支持 |
| POST | [`/v1/deployments/{deployment_id}/run`](/docs/api/compatible/anthropic/managed-agents/runDeployment)             | 运行部署   | ○ 未支持 |
| POST | [`/v1/deployments/{deployment_id}/unpause`](/docs/api/compatible/anthropic/managed-agents/unpauseDeployment)     | 恢复部署   | ○ 未支持 |

### 环境（6 个端点，5 个可用） [#环境6-个端点5-个可用]

| 方法     | 路径                                                                                                              | 说明   | 支持     |
| ------ | --------------------------------------------------------------------------------------------------------------- | ---- | ------ |
| GET    | [`/v1/environments`](/docs/api/compatible/anthropic/managed-agents/listEnvironments)                            | 列出环境 | ◐ 部分支持 |
| POST   | [`/v1/environments`](/docs/api/compatible/anthropic/managed-agents/createEnvironment)                           | 创建环境 | ◐ 部分支持 |
| DELETE | [`/v1/environments/{environment_id}`](/docs/api/compatible/anthropic/managed-agents/deleteEnvironment)          | 删除环境 | ○ 未支持  |
| GET    | [`/v1/environments/{environment_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveEnvironment)        | 读取环境 | ◐ 部分支持 |
| POST   | [`/v1/environments/{environment_id}`](/docs/api/compatible/anthropic/managed-agents/updateEnvironment)          | 更新环境 | ◐ 部分支持 |
| POST   | [`/v1/environments/{environment_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveEnvironment) | 归档环境 | ◐ 部分支持 |

### 环境任务（8 个端点，0 个可用） [#环境任务8-个端点0-个可用]

| 方法   | 路径                                                                                                                                     | 说明    | 支持    |
| ---- | -------------------------------------------------------------------------------------------------------------------------------------- | ----- | ----- |
| GET  | [`/v1/environments/{environment_id}/work`](/docs/api/compatible/anthropic/managed-agents/listEnvironmentWork)                          | 列出工作项 | ○ 未支持 |
| GET  | [`/v1/environments/{environment_id}/work/{work_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveEnvironmentWork)            | 读取工作项 | ○ 未支持 |
| POST | [`/v1/environments/{environment_id}/work/{work_id}`](/docs/api/compatible/anthropic/managed-agents/updateEnvironmentWork)              | 更新工作项 | ○ 未支持 |
| POST | [`/v1/environments/{environment_id}/work/{work_id}/ack`](/docs/api/compatible/anthropic/managed-agents/ackEnvironmentWork)             | 确认工作项 | ○ 未支持 |
| POST | [`/v1/environments/{environment_id}/work/{work_id}/heartbeat`](/docs/api/compatible/anthropic/managed-agents/heartbeatEnvironmentWork) | 工作项心跳 | ○ 未支持 |
| POST | [`/v1/environments/{environment_id}/work/{work_id}/stop`](/docs/api/compatible/anthropic/managed-agents/stopEnvironmentWork)           | 停止工作项 | ○ 未支持 |
| GET  | [`/v1/environments/{environment_id}/work/poll`](/docs/api/compatible/anthropic/managed-agents/pollEnvironmentWork)                     | 轮询工作项 | ○ 未支持 |
| GET  | [`/v1/environments/{environment_id}/work/stats`](/docs/api/compatible/anthropic/managed-agents/retrieveEnvironmentWorkStats)           | 工作项统计 | ○ 未支持 |

### 记忆库（14 个端点，0 个可用） [#记忆库14-个端点0-个可用]

| 方法     | 路径                                                                                                                                                               | 说明     | 支持    |
| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ----- |
| GET    | [`/v1/memory_stores`](/docs/api/compatible/anthropic/managed-agents/listMemoryStores)                                                                            | 列出记忆库  | ○ 未支持 |
| POST   | [`/v1/memory_stores`](/docs/api/compatible/anthropic/managed-agents/createMemoryStore)                                                                           | 创建记忆库  | ○ 未支持 |
| DELETE | [`/v1/memory_stores/{memory_store_id}`](/docs/api/compatible/anthropic/managed-agents/deleteMemoryStore)                                                         | 删除记忆库  | ○ 未支持 |
| GET    | [`/v1/memory_stores/{memory_store_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveMemoryStore)                                                       | 读取记忆库  | ○ 未支持 |
| POST   | [`/v1/memory_stores/{memory_store_id}`](/docs/api/compatible/anthropic/managed-agents/updateMemoryStore)                                                         | 更新记忆库  | ○ 未支持 |
| POST   | [`/v1/memory_stores/{memory_store_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveMemoryStore)                                                | 归档记忆库  | ○ 未支持 |
| GET    | [`/v1/memory_stores/{memory_store_id}/memories`](/docs/api/compatible/anthropic/managed-agents/listMemoryStoreMemories)                                          | 列出记忆   | ○ 未支持 |
| POST   | [`/v1/memory_stores/{memory_store_id}/memories`](/docs/api/compatible/anthropic/managed-agents/createMemoryStoreMemory)                                          | 创建记忆   | ○ 未支持 |
| DELETE | [`/v1/memory_stores/{memory_store_id}/memories/{memory_id}`](/docs/api/compatible/anthropic/managed-agents/deleteMemoryStoreMemory)                              | 删除记忆   | ○ 未支持 |
| GET    | [`/v1/memory_stores/{memory_store_id}/memories/{memory_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveMemoryStoreMemory)                            | 读取记忆   | ○ 未支持 |
| POST   | [`/v1/memory_stores/{memory_store_id}/memories/{memory_id}`](/docs/api/compatible/anthropic/managed-agents/updateMemoryStoreMemory)                              | 更新记忆   | ○ 未支持 |
| GET    | [`/v1/memory_stores/{memory_store_id}/memory_versions`](/docs/api/compatible/anthropic/managed-agents/listMemoryStoreMemoryVersions)                             | 列出记忆版本 | ○ 未支持 |
| GET    | [`/v1/memory_stores/{memory_store_id}/memory_versions/{memory_version_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveMemoryStoreMemoryVersion)      | 读取记忆版本 | ○ 未支持 |
| POST   | [`/v1/memory_stores/{memory_store_id}/memory_versions/{memory_version_id}/redact`](/docs/api/compatible/anthropic/managed-agents/redactMemoryStoreMemoryVersion) | 抹除记忆版本 | ○ 未支持 |

### 会话资源（5 个端点，4 个可用） [#会话资源5-个端点4-个可用]

| 方法     | 路径                                                                                                                           | 说明     | 支持     |
| ------ | ---------------------------------------------------------------------------------------------------------------------------- | ------ | ------ |
| GET    | [`/v1/sessions/{session_id}/resources`](/docs/api/compatible/anthropic/managed-agents/listSessionResources)                  | 列出会话资源 | ◐ 部分支持 |
| POST   | [`/v1/sessions/{session_id}/resources`](/docs/api/compatible/anthropic/managed-agents/addSessionResource)                    | 添加会话资源 | ◐ 部分支持 |
| DELETE | [`/v1/sessions/{session_id}/resources/{resource_id}`](/docs/api/compatible/anthropic/managed-agents/deleteSessionResource)   | 删除会话资源 | ◐ 部分支持 |
| GET    | [`/v1/sessions/{session_id}/resources/{resource_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveSessionResource) | 读取会话资源 | ◐ 部分支持 |
| POST   | [`/v1/sessions/{session_id}/resources/{resource_id}`](/docs/api/compatible/anthropic/managed-agents/updateSessionResource)   | 更新会话资源 | ○ 未支持  |

### 会话线程（5 个端点，5 个可用） [#会话线程5-个端点5-个可用]

| 方法   | 路径                                                                                                                                | 说明     | 支持     |
| ---- | --------------------------------------------------------------------------------------------------------------------------------- | ------ | ------ |
| GET  | [`/v1/sessions/{session_id}/threads`](/docs/api/compatible/anthropic/managed-agents/listSessionThreads)                           | 列出线程   | ◐ 部分支持 |
| GET  | [`/v1/sessions/{session_id}/threads/{thread_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveSessionThread)            | 读取线程   | ◐ 部分支持 |
| POST | [`/v1/sessions/{session_id}/threads/{thread_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveSessionThread)     | 归档线程   | ◐ 部分支持 |
| GET  | [`/v1/sessions/{session_id}/threads/{thread_id}/events`](/docs/api/compatible/anthropic/managed-agents/listSessionThreadEvents)   | 列出线程事件 | ◐ 部分支持 |
| GET  | [`/v1/sessions/{session_id}/threads/{thread_id}/stream`](/docs/api/compatible/anthropic/managed-agents/streamSessionThreadEvents) | 订阅线程事件 | ◐ 部分支持 |

### 技能（9 个端点，0 个可用） [#技能9-个端点0-个可用]

| 方法     | 路径                                                                                                                       | 说明       | 支持    |
| ------ | ------------------------------------------------------------------------------------------------------------------------ | -------- | ----- |
| GET    | [`/v1/skills`](/docs/api/compatible/anthropic/managed-agents/listSkills)                                                 | 列出技能     | ○ 未支持 |
| POST   | [`/v1/skills`](/docs/api/compatible/anthropic/managed-agents/createSkill)                                                | 创建技能     | ○ 未支持 |
| DELETE | [`/v1/skills/{skill_id}`](/docs/api/compatible/anthropic/managed-agents/deleteSkill)                                     | 删除技能     | ○ 未支持 |
| GET    | [`/v1/skills/{skill_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveSkill)                                   | 读取技能     | ○ 未支持 |
| GET    | [`/v1/skills/{skill_id}/versions`](/docs/api/compatible/anthropic/managed-agents/listSkillVersions)                      | 列出技能版本   | ○ 未支持 |
| POST   | [`/v1/skills/{skill_id}/versions`](/docs/api/compatible/anthropic/managed-agents/createSkillVersion)                     | 创建技能版本   | ○ 未支持 |
| DELETE | [`/v1/skills/{skill_id}/versions/{version}`](/docs/api/compatible/anthropic/managed-agents/deleteSkillVersion)           | 删除技能版本   | ○ 未支持 |
| GET    | [`/v1/skills/{skill_id}/versions/{version}`](/docs/api/compatible/anthropic/managed-agents/retrieveSkillVersion)         | 读取技能版本   | ○ 未支持 |
| GET    | [`/v1/skills/{skill_id}/versions/{version}/content`](/docs/api/compatible/anthropic/managed-agents/downloadSkillVersion) | 下载技能版本内容 | ○ 未支持 |

### 隧道（10 个端点，0 个可用） [#隧道10-个端点0-个可用]

| 方法   | 路径                                                                                                                                        | 说明     | 支持    |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------ | ----- |
| GET  | [`/v1/tunnels`](/docs/api/compatible/anthropic/managed-agents/listTunnels)                                                                | 列出隧道   | ○ 未支持 |
| POST | [`/v1/tunnels`](/docs/api/compatible/anthropic/managed-agents/createTunnel)                                                               | 创建隧道   | ○ 未支持 |
| GET  | [`/v1/tunnels/{tunnel_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveTunnel)                                                 | 读取隧道   | ○ 未支持 |
| POST | [`/v1/tunnels/{tunnel_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveTunnel)                                          | 归档隧道   | ○ 未支持 |
| GET  | [`/v1/tunnels/{tunnel_id}/certificates`](/docs/api/compatible/anthropic/managed-agents/listTunnelCertificates)                            | 列出隧道证书 | ○ 未支持 |
| POST | [`/v1/tunnels/{tunnel_id}/certificates`](/docs/api/compatible/anthropic/managed-agents/createTunnelCertificate)                           | 创建隧道证书 | ○ 未支持 |
| GET  | [`/v1/tunnels/{tunnel_id}/certificates/{certificate_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveTunnelCertificate)        | 读取隧道证书 | ○ 未支持 |
| POST | [`/v1/tunnels/{tunnel_id}/certificates/{certificate_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveTunnelCertificate) | 归档隧道证书 | ○ 未支持 |
| POST | [`/v1/tunnels/{tunnel_id}/reveal_token`](/docs/api/compatible/anthropic/managed-agents/revealTunnelToken)                                 | 显示隧道令牌 | ○ 未支持 |
| POST | [`/v1/tunnels/{tunnel_id}/rotate_token`](/docs/api/compatible/anthropic/managed-agents/rotateTunnelToken)                                 | 轮换隧道令牌 | ○ 未支持 |

### 凭据保险库（13 个端点，13 个可用） [#凭据保险库13-个端点13-个可用]

| 方法     | 路径                                                                                                                                                      | 说明             | 支持     |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | ------ |
| GET    | [`/v1/vaults`](/docs/api/compatible/anthropic/managed-agents/listVaults)                                                                                | 列出凭据库          | ● 支持   |
| POST   | [`/v1/vaults`](/docs/api/compatible/anthropic/managed-agents/createVault)                                                                               | 创建凭据库          | ● 支持   |
| DELETE | [`/v1/vaults/{vault_id}`](/docs/api/compatible/anthropic/managed-agents/deleteVault)                                                                    | 删除凭据库          | ● 支持   |
| GET    | [`/v1/vaults/{vault_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveVault)                                                                  | 读取凭据库          | ● 支持   |
| POST   | [`/v1/vaults/{vault_id}`](/docs/api/compatible/anthropic/managed-agents/updateVault)                                                                    | 更新凭据库          | ● 支持   |
| POST   | [`/v1/vaults/{vault_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveVault)                                                           | 归档凭据库          | ● 支持   |
| GET    | [`/v1/vaults/{vault_id}/credentials`](/docs/api/compatible/anthropic/managed-agents/listVaultCredentials)                                               | 列出凭据           | ◐ 部分支持 |
| POST   | [`/v1/vaults/{vault_id}/credentials`](/docs/api/compatible/anthropic/managed-agents/createVaultCredential)                                              | 创建凭据           | ◐ 部分支持 |
| DELETE | [`/v1/vaults/{vault_id}/credentials/{credential_id}`](/docs/api/compatible/anthropic/managed-agents/deleteVaultCredential)                              | 删除凭据           | ◐ 部分支持 |
| GET    | [`/v1/vaults/{vault_id}/credentials/{credential_id}`](/docs/api/compatible/anthropic/managed-agents/retrieveVaultCredential)                            | 读取凭据           | ◐ 部分支持 |
| POST   | [`/v1/vaults/{vault_id}/credentials/{credential_id}`](/docs/api/compatible/anthropic/managed-agents/updateVaultCredential)                              | 更新凭据           | ◐ 部分支持 |
| POST   | [`/v1/vaults/{vault_id}/credentials/{credential_id}/archive`](/docs/api/compatible/anthropic/managed-agents/archiveVaultCredential)                     | 归档凭据           | ◐ 部分支持 |
| POST   | [`/v1/vaults/{vault_id}/credentials/{credential_id}/mcp_oauth_validate`](/docs/api/compatible/anthropic/managed-agents/validateVaultCredentialMcpOAuth) | 校验凭据 MCP OAuth | ◐ 部分支持 |

## 与官方的差异 [#与官方的差异]

* <a href="/docs/api/compatible/anthropic/managed-agents/createAgent">创建智能体</a>：支持文本提示词、模型、元数据与内置工具。MCP、Skills 及额外模型控制尚不支持，传入会返回 400。 multiagent 接受 null 或 coordinator 名册，1–20 项：智能体 ID、\{type:"agent",id,version?} 或最多一个 \{type:"self"}。创建/更新时固定版本；成员去重且须存在、未归档、不能自身带 multiagent。兼容 API 只提供 bash、edit、glob、grep、read、write、web\_search、web\_fetch 这 8 个官方工具；configs 不接受其他工具名，经此入口创建的会话不提供后台任务、Monitor 或子智能体。完整原生工具请使用 /agent/v1。每个 coordinator 最多一个 advisor，模型须可用且不同于智能体模型；仅主会话可咨询，每次咨询为独立 advisor 线程，建议以 agent.thread\_message\_received 返回。
* <a href="/docs/api/compatible/anthropic/managed-agents/retrieveAgent">读取智能体</a>：将示例中的资源 ID 替换成你创建的资源 ID。
* <a href="/docs/api/compatible/anthropic/managed-agents/updateAgent">更新智能体</a>：version 可用于乐观并发控制，版本冲突返回 409；无变化的更新不增加版本。MCP、Skills 尚不支持。 multiagent 接受 null 或 coordinator 名册，1–20 项：智能体 ID、\{type:"agent",id,version?} 或最多一个 \{type:"self"}。创建/更新时固定版本；成员去重且须存在、未归档、不能自身带 multiagent。兼容 API 只提供 bash、edit、glob、grep、read、write、web\_search、web\_fetch 这 8 个官方工具；configs 不接受其他工具名，经此入口创建的会话不提供后台任务、Monitor 或子智能体。完整原生工具请使用 /agent/v1。每个 coordinator 最多一个 advisor，模型须可用且不同于智能体模型；仅主会话可咨询，每次咨询为独立 advisor 线程，建议以 agent.thread\_message\_received 返回。
* <a href="/docs/api/compatible/anthropic/managed-agents/listAgentVersions">列出版本</a>：将示例中的资源 ID 替换成你创建的资源 ID。
* <a href="/docs/api/compatible/anthropic/managed-agents/archiveAgent">归档智能体</a>：归档后保留查询与历史版本，不能继续更新。请只归档自己的测试智能体。
* <a href="/docs/api/compatible/anthropic/managed-agents/createSession">创建会话</a>：先创建智能体，将示例 agent\_123 换成返回的 id。Anthropic 兼容 API 的 environment\_id 必填，可用 node22 或租户自建 cloud 环境；/agent/v1 可省略 environment\_id 得到轻量机器。不支持内联智能体覆盖、预算与凭据库。 支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/compatible/anthropic/managed-agents/listSessions">列出会话</a>：支持 limit、page 与 agent\_id；agent\_version、时间范围、deployment\_id、memory\_store\_id、include\_archived、order、statuses 尚不支持，传入返回 400。
* <a href="/docs/api/compatible/anthropic/managed-agents/retrieveSession">读取会话</a>：将示例中的资源 ID 替换成你创建的资源 ID。
* <a href="/docs/api/compatible/anthropic/managed-agents/sendEvents">发送事件</a>：将 sesn\_123 换成创建会话返回的 id。每条 user.message 只接受一个非空文本块。支持文本 user.message、user.interrupt 和工具确认；其它事件变体尚不支持。返回的是已接纳事件；模型回复从事件历史或订阅读取。会话等待工具授权时发送的 user.message 会排队：返回的事件 processed\_at 为 null，授权处理完成后按发送顺序执行。
* <a href="/docs/api/compatible/anthropic/managed-agents/listEvents">列出事件</a>：先发送消息再读取历史；处理完成前可能只看到已接纳的输入。支持分页、事件类型和时间过滤。会话等待工具授权时停在 session.status\_idle，stop\_reason 为 requires\_action，event\_ids 列出待确认的 agent.tool\_use；运行失败时先出现 session.error，再出现 session.status\_terminated。agent.thinking 与官方一致，是不带内容的进度信号。
* <a href="/docs/api/compatible/anthropic/managed-agents/streamEvents">订阅事件</a>：保持 SSE 连接以接收事件；请求不会像普通 JSON 接口一样立刻结束。先创建会话并替换 sesn\_123，再从另一请求发送消息；停止按钮只断开订阅，不会停止智能体。SDK 0.124.0 会过滤 session.usage，完整用量请读历史。传 event\_deltas\[]=agent.message 可在最终事件到达前收到逐段文本预览；agent.thinking 与官方一致，只有 event\_start。
* <a href="/docs/api/compatible/anthropic/managed-agents/listEnvironments">列出环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/compatible/anthropic/managed-agents/createEnvironment">创建环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/compatible/anthropic/managed-agents/retrieveEnvironment">读取环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/compatible/anthropic/managed-agents/updateEnvironment">更新环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/compatible/anthropic/managed-agents/archiveEnvironment">归档环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/compatible/anthropic/managed-agents/updateSession">更新会话</a>：支持 title 与 metadata（官方补丁语义：字符串值写入、null 删除该键、整包 null 清空，未提及的键保留）。官方的 agent 覆盖（tools/mcp\_servers）、budget 与 vault\_ids 不支持，传入返回 400 并点名字段。归档后的会话更新返回 409。
* <a href="/docs/api/compatible/anthropic/managed-agents/archiveSession">归档会话</a>：归档后的会话拒绝新消息（400 invalid\_request\_error，写明会话已归档），读取与事件历史仍可用；重复归档幂等，archived\_at 保持首次归档时间。
* <a href="/docs/api/compatible/anthropic/managed-agents/listSessionResources">列出会话资源</a>：支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/compatible/anthropic/managed-agents/addSessionResource">添加会话资源</a>：支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/compatible/anthropic/managed-agents/deleteSessionResource">删除会话资源</a>：支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/compatible/anthropic/managed-agents/retrieveSessionResource">读取会话资源</a>：支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/compatible/anthropic/managed-agents/listSessionThreads">列出线程</a>：按 created\_at 升序返回主线程及全部子线程。线程 id 为 sthr\_ 加所属会话 id 的后缀；子线程的 parent\_thread\_id 指向主线程，session\_id 始终为父会话。agent 是实际运行的定义，内置类型的 name 为类型名，未注册的 id/version 为 null。归档子线程的 status 为 terminated，archived\_at 为归档时间；stats/usage 无线程级追踪时如实为 null。
* <a href="/docs/api/compatible/anthropic/managed-agents/retrieveSessionThread">读取线程</a>：返回本会话的主线程或子线程，与列表项逐字段一致。其他会话的线程、未知线程或非 sthr\_ id 一律返回 404，不泄露其存在性。
* <a href="/docs/api/compatible/anthropic/managed-agents/archiveSessionThread">归档线程</a>：主线程沿用会话归档动作；子线程仅归档对应子会话，不归档父会话或其他子线程。子线程归档后 status 为 terminated，带 archived\_at；历史事件仍可读。
* <a href="/docs/api/compatible/anthropic/managed-agents/listSessionThreadEvents">列出线程事件</a>：读取所选线程自己的事件记录：主线程读主会话，子线程读对应子会话。沿用会话事件接口的查询参数、公开事件类型和 data + next\_page 信封。使用网页工具时，两个接口均返回 search\_result 块；回答 citations 为 /agent/v1 扩展，/anthropic 将引用显示为正文 \[n]。
* <a href="/docs/api/compatible/anthropic/managed-agents/streamSessionThreadEvents">订阅线程事件</a>：订阅所选线程自己的实时事件流。复用会话 SSE 实现；/agent 接口支持同址只读 WebSocket。主会话流同时包含子线程创建、状态和消息事件，子线程审批带 session\_thread\_id 上浮；确认或中断携带该字段时路由到所属子线程。
* <a href="/docs/api/compatible/anthropic/managed-agents/listVaults">列出凭据库</a>：支持创建、列出、读取、更新、归档与删除。列表支持 limit、page 和 include\_archived。归档会同时归档库内全部凭据并清除凭据的值；删除会一并删除全部凭据，不可恢复。以 anthropic. 开头的 metadata 键由平台保留，不能写入。同一个库也可以通过原生接口 /vault/v1 管理。
* <a href="/docs/api/compatible/anthropic/managed-agents/createVault">创建凭据库</a>：支持创建、列出、读取、更新、归档与删除。列表支持 limit、page 和 include\_archived。归档会同时归档库内全部凭据并清除凭据的值；删除会一并删除全部凭据，不可恢复。以 anthropic. 开头的 metadata 键由平台保留，不能写入。同一个库也可以通过原生接口 /vault/v1 管理。
* <a href="/docs/api/compatible/anthropic/managed-agents/deleteVault">删除凭据库</a>：支持创建、列出、读取、更新、归档与删除。列表支持 limit、page 和 include\_archived。归档会同时归档库内全部凭据并清除凭据的值；删除会一并删除全部凭据，不可恢复。以 anthropic. 开头的 metadata 键由平台保留，不能写入。同一个库也可以通过原生接口 /vault/v1 管理。
* <a href="/docs/api/compatible/anthropic/managed-agents/retrieveVault">读取凭据库</a>：支持创建、列出、读取、更新、归档与删除。列表支持 limit、page 和 include\_archived。归档会同时归档库内全部凭据并清除凭据的值；删除会一并删除全部凭据，不可恢复。以 anthropic. 开头的 metadata 键由平台保留，不能写入。同一个库也可以通过原生接口 /vault/v1 管理。
* <a href="/docs/api/compatible/anthropic/managed-agents/updateVault">更新凭据库</a>：支持创建、列出、读取、更新、归档与删除。列表支持 limit、page 和 include\_archived。归档会同时归档库内全部凭据并清除凭据的值；删除会一并删除全部凭据，不可恢复。以 anthropic. 开头的 metadata 键由平台保留，不能写入。同一个库也可以通过原生接口 /vault/v1 管理。
* <a href="/docs/api/compatible/anthropic/managed-agents/archiveVault">归档凭据库</a>：支持创建、列出、读取、更新、归档与删除。列表支持 limit、page 和 include\_archived。归档会同时归档库内全部凭据并清除凭据的值；删除会一并删除全部凭据，不可恢复。以 anthropic. 开头的 metadata 键由平台保留，不能写入。同一个库也可以通过原生接口 /vault/v1 管理。
* <a href="/docs/api/compatible/anthropic/managed-agents/listVaultCredentials">列出凭据</a>：支持 environment\_variable 与 static\_bearer。environment\_variable 的 networking 只支持 limited，传 unrestricted 返回 400；secret\_name 只能使用大写字母、数字和下划线，且不能以数字开头；injection\_location 的默认值与官方一致。static\_bearer 的令牌只在 mcp\_server\_url 所在主机上可用。创建或更新 mcp\_oauth 返回 501（not\_implemented\_error），不产生副作用，官方 SDK 不会重试；需要 OAuth 令牌时请使用 /vault/v1/authorizations 一键授权。每个库最多 20 个有效凭据。以 anthropic. 开头的 metadata 键由平台保留，不能写入。
* <a href="/docs/api/compatible/anthropic/managed-agents/createVaultCredential">创建凭据</a>：支持 environment\_variable 与 static\_bearer。environment\_variable 的 networking 只支持 limited，传 unrestricted 返回 400；secret\_name 只能使用大写字母、数字和下划线，且不能以数字开头；injection\_location 的默认值与官方一致。static\_bearer 的令牌只在 mcp\_server\_url 所在主机上可用。创建或更新 mcp\_oauth 返回 501（not\_implemented\_error），不产生副作用，官方 SDK 不会重试；需要 OAuth 令牌时请使用 /vault/v1/authorizations 一键授权。每个库最多 20 个有效凭据。以 anthropic. 开头的 metadata 键由平台保留，不能写入。
* <a href="/docs/api/compatible/anthropic/managed-agents/deleteVaultCredential">删除凭据</a>：支持 environment\_variable 与 static\_bearer。environment\_variable 的 networking 只支持 limited，传 unrestricted 返回 400；secret\_name 只能使用大写字母、数字和下划线，且不能以数字开头；injection\_location 的默认值与官方一致。static\_bearer 的令牌只在 mcp\_server\_url 所在主机上可用。创建或更新 mcp\_oauth 返回 501（not\_implemented\_error），不产生副作用，官方 SDK 不会重试；需要 OAuth 令牌时请使用 /vault/v1/authorizations 一键授权。每个库最多 20 个有效凭据。以 anthropic. 开头的 metadata 键由平台保留，不能写入。
* <a href="/docs/api/compatible/anthropic/managed-agents/retrieveVaultCredential">读取凭据</a>：支持 environment\_variable 与 static\_bearer。environment\_variable 的 networking 只支持 limited，传 unrestricted 返回 400；secret\_name 只能使用大写字母、数字和下划线，且不能以数字开头；injection\_location 的默认值与官方一致。static\_bearer 的令牌只在 mcp\_server\_url 所在主机上可用。创建或更新 mcp\_oauth 返回 501（not\_implemented\_error），不产生副作用，官方 SDK 不会重试；需要 OAuth 令牌时请使用 /vault/v1/authorizations 一键授权。每个库最多 20 个有效凭据。以 anthropic. 开头的 metadata 键由平台保留，不能写入。
* <a href="/docs/api/compatible/anthropic/managed-agents/updateVaultCredential">更新凭据</a>：支持 environment\_variable 与 static\_bearer。environment\_variable 的 networking 只支持 limited，传 unrestricted 返回 400；secret\_name 只能使用大写字母、数字和下划线，且不能以数字开头；injection\_location 的默认值与官方一致。static\_bearer 的令牌只在 mcp\_server\_url 所在主机上可用。创建或更新 mcp\_oauth 返回 501（not\_implemented\_error），不产生副作用，官方 SDK 不会重试；需要 OAuth 令牌时请使用 /vault/v1/authorizations 一键授权。每个库最多 20 个有效凭据。以 anthropic. 开头的 metadata 键由平台保留，不能写入。
* <a href="/docs/api/compatible/anthropic/managed-agents/archiveVaultCredential">归档凭据</a>：支持 environment\_variable 与 static\_bearer。environment\_variable 的 networking 只支持 limited，传 unrestricted 返回 400；secret\_name 只能使用大写字母、数字和下划线，且不能以数字开头；injection\_location 的默认值与官方一致。static\_bearer 的令牌只在 mcp\_server\_url 所在主机上可用。创建或更新 mcp\_oauth 返回 501（not\_implemented\_error），不产生副作用，官方 SDK 不会重试；需要 OAuth 令牌时请使用 /vault/v1/authorizations 一键授权。每个库最多 20 个有效凭据。以 anthropic. 开头的 metadata 键由平台保留，不能写入。
* <a href="/docs/api/compatible/anthropic/managed-agents/validateVaultCredentialMcpOAuth">校验凭据 MCP OAuth</a>：只适用于 OAuth 凭据，对其他类型返回 400。结果总是 HTTP 200，status 为 valid、invalid 或 unknown；mcp\_probe 只在未通过时给出失败的一步，refresh 只在尝试了续期时给出。

参数与字段的权威定义以 [Claude Managed Agents 官方文档](https://platform.claude.com/docs/en/managed-agents/overview)为准。

错误按 Claude Managed Agents 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string |  |
| mcp_servers | array&lt;object&gt; |  |
| mcp_servers[].name | string |  |
| mcp_servers[].type | string |  |
| mcp_servers[].url | string |  |
| metadata | object |  |
| model | object | Model identifier and configuration. |
| model.id | string | The model that will power your agent.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| model.effort | object | How hard Claude works on each turn. Sets &#96;output_config.effort&#96; on every Messages call the session makes. |
| model.inference_geo | string | Geographic region for model inference. When unset, requests fall through to the workspace's default_inference_geo. |
| model.speed | string | Inference speed mode. &#96;fast&#96; provides significantly faster output token generation at premium pricing. Not all models support &#96;fast&#96;; invalid combinations are rejected at create time. |
| multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| multiagent.agents | array&lt;object&gt; | Agents the coordinator may spawn as session threads, each resolved to a specific version. |
| multiagent.type | string |  |
| name | string |  |
| skills | array&lt;object&gt; |  |
| skills[].skill_id | string |  |
| skills[].type | string |  |
| skills[].version | string |  |
| system | null &#124; string |  |
| tools | array&lt;object&gt; |  |
| tools[].configs | array&lt;object&gt; |  |
| tools[].default_config | object | Resolved default configuration for agent tools. / Resolved default configuration for all tools from an MCP server. |
| tools[].type | string |  |
| tools[].mcp_server_name | string |  |
| tools[].description | string |  |
| tools[].input_schema | object | JSON Schema for custom tool input parameters. |
| tools[].name | string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |

# 列出智能体

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string |  |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].description | null &#124; string |  |
| data[].mcp_servers | array&lt;object&gt; |  |
| data[].metadata | object |  |
| data[].model | object | Model identifier and configuration. |
| data[].multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| data[].name | string |  |
| data[].skills | array&lt;object&gt; |  |
| data[].system | null &#124; string |  |
| data[].tools | array&lt;object&gt; |  |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |
| next_page | string &#124; null |  |

# 读取智能体

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string |  |
| mcp_servers | array&lt;object&gt; |  |
| mcp_servers[].name | string |  |
| mcp_servers[].type | string |  |
| mcp_servers[].url | string |  |
| metadata | object |  |
| model | object | Model identifier and configuration. |
| model.id | string | The model that will power your agent.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| model.effort | object | How hard Claude works on each turn. Sets &#96;output_config.effort&#96; on every Messages call the session makes. |
| model.inference_geo | string | Geographic region for model inference. When unset, requests fall through to the workspace's default_inference_geo. |
| model.speed | string | Inference speed mode. &#96;fast&#96; provides significantly faster output token generation at premium pricing. Not all models support &#96;fast&#96;; invalid combinations are rejected at create time. |
| multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| multiagent.agents | array&lt;object&gt; | Agents the coordinator may spawn as session threads, each resolved to a specific version. |
| multiagent.type | string |  |
| name | string |  |
| skills | array&lt;object&gt; |  |
| skills[].skill_id | string |  |
| skills[].type | string |  |
| skills[].version | string |  |
| system | null &#124; string |  |
| tools | array&lt;object&gt; |  |
| tools[].configs | array&lt;object&gt; |  |
| tools[].default_config | object | Resolved default configuration for agent tools. / Resolved default configuration for all tools from an MCP server. |
| tools[].type | string |  |
| tools[].mcp_server_name | string |  |
| tools[].description | string |  |
| tools[].input_schema | object | JSON Schema for custom tool input parameters. |
| tools[].name | string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |

# 

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string |  |
| mcp_servers | array&lt;object&gt; |  |
| mcp_servers[].name | string |  |
| mcp_servers[].type | string |  |
| mcp_servers[].url | string |  |
| metadata | object |  |
| model | object | Model identifier and configuration. |
| model.id | string | The model that will power your agent.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| model.effort | object | How hard Claude works on each turn. Sets &#96;output_config.effort&#96; on every Messages call the session makes. |
| model.inference_geo | string | Geographic region for model inference. When unset, requests fall through to the workspace's default_inference_geo. |
| model.speed | string | Inference speed mode. &#96;fast&#96; provides significantly faster output token generation at premium pricing. Not all models support &#96;fast&#96;; invalid combinations are rejected at create time. |
| multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| multiagent.agents | array&lt;object&gt; | Agents the coordinator may spawn as session threads, each resolved to a specific version. |
| multiagent.type | string |  |
| name | string |  |
| skills | array&lt;object&gt; |  |
| skills[].skill_id | string |  |
| skills[].type | string |  |
| skills[].version | string |  |
| system | null &#124; string |  |
| tools | array&lt;object&gt; |  |
| tools[].configs | array&lt;object&gt; |  |
| tools[].default_config | object | Resolved default configuration for agent tools. / Resolved default configuration for all tools from an MCP server. |
| tools[].type | string |  |
| tools[].mcp_server_name | string |  |
| tools[].description | string |  |
| tools[].input_schema | object | JSON Schema for custom tool input parameters. |
| tools[].name | string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |

# 列出版本

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string |  |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].description | null &#124; string |  |
| data[].mcp_servers | array&lt;object&gt; |  |
| data[].metadata | object |  |
| data[].model | object | Model identifier and configuration. |
| data[].multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| data[].name | string |  |
| data[].skills | array&lt;object&gt; |  |
| data[].system | null &#124; string |  |
| data[].tools | array&lt;object&gt; |  |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |
| next_page | string &#124; null |  |

# 归档智能体

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string |  |
| mcp_servers | array&lt;object&gt; |  |
| mcp_servers[].name | string |  |
| mcp_servers[].type | string |  |
| mcp_servers[].url | string |  |
| metadata | object |  |
| model | object | Model identifier and configuration. |
| model.id | string | The model that will power your agent.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| model.effort | object | How hard Claude works on each turn. Sets &#96;output_config.effort&#96; on every Messages call the session makes. |
| model.inference_geo | string | Geographic region for model inference. When unset, requests fall through to the workspace's default_inference_geo. |
| model.speed | string | Inference speed mode. &#96;fast&#96; provides significantly faster output token generation at premium pricing. Not all models support &#96;fast&#96;; invalid combinations are rejected at create time. |
| multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| multiagent.agents | array&lt;object&gt; | Agents the coordinator may spawn as session threads, each resolved to a specific version. |
| multiagent.type | string |  |
| name | string |  |
| skills | array&lt;object&gt; |  |
| skills[].skill_id | string |  |
| skills[].type | string |  |
| skills[].version | string |  |
| system | null &#124; string |  |
| tools | array&lt;object&gt; |  |
| tools[].configs | array&lt;object&gt; |  |
| tools[].default_config | object | Resolved default configuration for agent tools. / Resolved default configuration for all tools from an MCP server. |
| tools[].type | string |  |
| tools[].mcp_server_name | string |  |
| tools[].description | string |  |
| tools[].input_schema | object | JSON Schema for custom tool input parameters. |
| tools[].name | string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |

# 

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string |  |
| agent.description | null &#124; string |  |
| agent.mcp_servers | array&lt;object&gt; |  |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string |  |
| agent.skills | array&lt;object&gt; |  |
| agent.system | null &#124; string |  |
| agent.tools | array&lt;object&gt; |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string |  |
| metadata | object |  |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string |  |
| resources | array&lt;object&gt; |  |
| resources[].id | string |  |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string |  |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string |  |
| resources[].checkout | null &#124; object |  |
| resources[].file_id | string |  |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string |  |
| data[].agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].environment_id | string |  |
| data[].metadata | object |  |
| data[].outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| data[].resources | array&lt;object&gt; |  |
| data[].stats | object | Timing statistics for a session. |
| data[].status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| data[].title | null &#124; string |  |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].usage | object | Cumulative token usage for a session across all turns. |
| data[].vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| data[].deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |
| next_page | string &#124; null |  |

# 读取会话

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string |  |
| agent.description | null &#124; string |  |
| agent.mcp_servers | array&lt;object&gt; |  |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string |  |
| agent.skills | array&lt;object&gt; |  |
| agent.system | null &#124; string |  |
| agent.tools | array&lt;object&gt; |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string |  |
| metadata | object |  |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string |  |
| resources | array&lt;object&gt; |  |
| resources[].id | string |  |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string |  |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string |  |
| resources[].checkout | null &#124; object |  |
| resources[].file_id | string |  |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Sent events |
| data[].id | string | Unique identifier for this event. |
| data[].content | array&lt;object&gt; | Array of content blocks comprising the user message. / The result content returned by the tool. / The result content returned by the tool. / System content blocks. Text-only. |
| data[].type | string |  |
| data[].processed_at | null &#124; string &#124; string &#124; null &#124; string &#124; null &#124; string | A timestamp in RFC 3339 format |
| data[].session_thread_id | null &#124; string | If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Set by the server to the subagent thread this confirmation was routed to. Omitted when it was routed to the primary thread. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. |
| data[].result | string | UserToolConfirmationResult enum |
| data[].tool_use_id | string | The id of the &#96;agent.tool_use&#96; or &#96;agent.mcp_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. / The id of the &#96;agent.tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].deny_message | null &#124; string | Optional message providing context for a 'deny' decision. Only allowed when result is 'deny'. |
| data[].custom_tool_use_id | string | The id of the &#96;agent.custom_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].is_error | null &#124; boolean | Whether the tool execution resulted in an error. |
| data[].description | string | What the agent should produce. Copied from the input event. |
| data[].max_iterations | null &#124; number | Evaluate-then-revise cycles before giving up. Default 3, max 20. |
| data[].outcome_id | string | Server-generated &#96;outc_&#96; ID for this outcome. Referenced by &#96;span.outcome_evaluation_*&#96; events and the session's &#96;outcome_evaluations&#96; list. |
| data[].rubric | object | Rubric for grading the quality of an outcome. |

# 列出事件

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for this event. |
| data[].content | array&lt;object&gt; | Array of content blocks comprising the user message. / The result content returned by the tool. / Array of text blocks comprising the agent response. / The result content returned by the tool. / The result content returned by the tool. / Message content blocks. / Message content blocks. / The result content returned by the tool. / System content blocks. Text-only. |
| data[].type | string |  |
| data[].processed_at | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string | A timestamp in RFC 3339 format |
| data[].session_thread_id | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string | If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Set by the server to the subagent thread this confirmation was routed to. Omitted when it was routed to the primary thread. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / When set, this event was cross-posted from a subagent's thread to surface its custom tool use on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.custom_tool_result&#96; by &#96;custom_tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; or &#96;user.tool_result&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / Public &#96;sthr_&#96; ID of the newly created thread. / Public sthr\_ ID of the thread that started running. / Public sthr\_ ID of the thread that went idle. / Public sthr\_ ID of the thread that terminated. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / Public sthr\_ ID of the thread that is retrying. |
| data[].result | string | UserToolConfirmationResult enum / Evaluation verdict. 'satisfied': criteria met, session goes idle. 'needs_revision': criteria not met, another revision cycle follows. 'max_iterations_reached': evaluation budget exhausted with criteria still unmet — one final acknowledgment turn follows before the session goes idle, but no further evaluation runs. 'failed': grader determined the rubric does not apply to the deliverables. 'interrupted': user sent an interrupt while evaluation was in progress. |
| data[].tool_use_id | string | The id of the &#96;agent.tool_use&#96; or &#96;agent.mcp_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. / The id of the &#96;agent.tool_use&#96; event this result corresponds to. / The id of the &#96;agent.tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].deny_message | null &#124; string | Optional message providing context for a 'deny' decision. Only allowed when result is 'deny'. |
| data[].custom_tool_use_id | string | The id of the &#96;agent.custom_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].is_error | null &#124; boolean | Whether the tool execution resulted in an error. / Whether the model request resulted in an error. / Whether the tool execution resulted in an error. |
| data[].input | object | Input parameters for the tool call. |
| data[].name | string | Name of the custom tool being called. / Name of the MCP tool being used. / Name of the agent tool being used. |
| data[].mcp_server_name | string | Name of the MCP server providing the tool. |
| data[].evaluated_permission | string | AgentEvaluatedPermission enum |
| data[].evaluation | object | Names the resolved permission_policy that produced evaluated_permission, and under auto carries the judgement. Open union: clients must tolerate unknown variants. |
| data[].mcp_tool_use_id | string | The id of the &#96;agent.mcp_tool_use&#96; event this result corresponds to. |
| data[].from_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread that sent the message. |
| data[].from_agent_name | null &#124; string | Name of the callable agent this message came from. Absent when received from the primary agent. |
| data[].to_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread the message was sent to. |
| data[].to_agent_name | null &#124; string | Name of the callable agent this message was sent to. Absent when sent to the primary agent. |
| data[].error | object |  |
| data[].stop_reason | object |  |
| data[].agent_name | string | Name of the callable agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. |
| data[].iteration | number | 0-indexed revision cycle. 0 is the first evaluation; 1 is the re-evaluation after the first revision; etc. / 0-indexed revision cycle, matching the corresponding &#96;span.outcome_evaluation_start&#96;. / 0-indexed revision cycle, matching the corresponding &#96;span.outcome_evaluation_start&#96;. |
| data[].outcome_id | string | The &#96;outc_&#96; ID of the outcome being evaluated. / Server-generated &#96;outc_&#96; ID for this outcome. Referenced by &#96;span.outcome_evaluation_*&#96; events and the session's &#96;outcome_evaluations&#96; list. |
| data[].explanation | string | Human-readable explanation of the verdict. For &#96;needs_revision&#96;, describes which criteria failed and why. |
| data[].outcome_evaluation_start_id | string | The id of the corresponding &#96;span.outcome_evaluation_start&#96; event. |
| data[].usage | object | Token usage for a single model request. / Point-in-time snapshot of a session's cumulative usage. |
| data[].model_request_start_id | string | The id of the corresponding &#96;span.model_request_start&#96; event. |
| data[].model_usage | object | Token usage for a single model request. |
| data[].description | string | What the agent should produce. Copied from the input event. |
| data[].max_iterations | null &#124; number | Evaluate-then-revise cycles before giving up. Default 3, max 20. |
| data[].rubric | object | Rubric for grading the quality of an outcome. |
| data[].agent | null &#124; object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| data[].budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| data[].metadata | object | The session's full metadata bag after the update. Present when the update set non-empty metadata; absent when metadata was unchanged or cleared to empty. |
| data[].title | null &#124; string | The session's new title. Present only when the update changed it. |
| next_page | string &#124; null |  |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Server-sent events

**text/event-stream — chunk / 事件对象**

未声明字段结构。

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for this run (&#96;drun_...&#96;). |
| data[].agent | object | A resolved agent reference with a concrete version. |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].deployment_id | string | ID of the deployment that produced this run. |
| data[].error | null &#124; object | Why the run failed to create a session. The type identifies the failure; message is human-readable detail. |
| data[].session_id | null &#124; string | Populated on success. Null on creation failure. Exactly one of &#96;session_id&#96; or &#96;error&#96; is non-null. |
| data[].trigger_context | object | Describes what triggered a deployment run, with trigger-specific metadata. |
| data[].type | string |  |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this run (&#96;drun_...&#96;). |
| agent | object | A resolved agent reference with a concrete version. |
| agent.id | string |  |
| agent.type | string |  |
| agent.version | number |  |
| created_at | string | A timestamp in RFC 3339 format |
| deployment_id | string | ID of the deployment that produced this run. |
| error | null &#124; object | Why the run failed to create a session. The type identifies the failure; message is human-readable detail. |
| error.message | string | Human-readable error description. |
| error.type | string |  |
| session_id | null &#124; string | Populated on success. Null on creation failure. Exactly one of &#96;session_id&#96; or &#96;error&#96; is non-null. |
| trigger_context | object | Describes what triggered a deployment run, with trigger-specific metadata. |
| trigger_context.scheduled_at | string | A timestamp in RFC 3339 format |
| trigger_context.type | string |  |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for this deployment. |
| data[].agent | object | A resolved agent reference with a concrete version. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].description | null &#124; string | Description of what the deployment does. |
| data[].environment_id | string | ID of the &#96;environment&#96; where sessions run. |
| data[].initial_events | array&lt;object&gt; | Events sent to each session immediately after creation. |
| data[].metadata | object | Arbitrary key-value metadata. Maximum 16 pairs. |
| data[].name | string | Human-readable name. |
| data[].paused_reason | null &#124; object | Why a deployment is paused. Non-null exactly when &#96;status&#96; is &#96;paused&#96;. |
| data[].resources | array&lt;object&gt; | Resources attached to sessions created from this deployment. Echoes the input minus write-only credentials. |
| data[].schedule | null &#124; object | 5-field POSIX cron schedule with computed runtime timestamps. |
| data[].status | string | Lifecycle status of a deployment. |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].vault_ids | array&lt;string&gt; | Vault IDs supplying stored credentials for sessions created from this deployment. |
| data[].budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this deployment. |
| agent | object | A resolved agent reference with a concrete version. |
| agent.id | string |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Description of what the deployment does. |
| environment_id | string | ID of the &#96;environment&#96; where sessions run. |
| initial_events | array&lt;object&gt; | Events sent to each session immediately after creation. |
| initial_events[].content | array&lt;object&gt; | Array of content blocks for the user message. / System content blocks to append. Text-only. |
| initial_events[].type | string |  |
| initial_events[].description | string | What the agent should produce. This is the task specification. |
| initial_events[].rubric | object | Rubric for grading the quality of an outcome. |
| initial_events[].max_iterations | null &#124; number | Eval→revision cycles before giving up. Default 3, max 20. |
| metadata | object | Arbitrary key-value metadata. Maximum 16 pairs. |
| name | string | Human-readable name. |
| paused_reason | null &#124; object | Why a deployment is paused. Non-null exactly when &#96;status&#96; is &#96;paused&#96;. |
| paused_reason.type | string |  |
| paused_reason.error | object | The error that triggered an auto-pause. Matches the failed run's &#96;error.type&#96;. |
| resources | array&lt;object&gt; | Resources attached to sessions created from this deployment. Echoes the input minus write-only credentials. |
| resources[].type | string |  |
| resources[].url | string | Github URL of the repository |
| resources[].checkout | null &#124; object | Branch or commit to check out. Defaults to the repository's default branch. |
| resources[].mount_path | null &#124; string | Mount path in the container. Defaults to &#96;/workspace/&lt;repo-name&gt;&#96;. / Mount path in the container. Defaults to &#96;/mnt/session/uploads/&lt;file_id&gt;&#96;. |
| resources[].file_id | string | ID of a previously uploaded file. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| schedule | null &#124; object | 5-field POSIX cron schedule with computed runtime timestamps. |
| schedule.expression | string | 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g., "0 9 \* \* 1-5" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean Sunday. Extended cron syntax - seconds or year fields, and the special characters L, W, #, and ? - is not supported, nor are predefined shortcuts (@daily). |
| schedule.timezone | string | IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). |
| schedule.type | string |  |
| schedule.last_run_at | null &#124; string | A timestamp in RFC 3339 format |
| schedule.upcoming_runs_at | array&lt;string&gt; | Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused deployments (reflects what the schedule would do if unpaused); empty once the deployment is archived (&#96;archived_at&#96; set). Each fire is offset by a small per-schedule jitter, so a run will actually start at or shortly after its listed time. |
| status | string | Lifecycle status of a deployment. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_ids | array&lt;string&gt; | Vault IDs supplying stored credentials for sessions created from this deployment. |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this deployment. |
| agent | object | A resolved agent reference with a concrete version. |
| agent.id | string |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Description of what the deployment does. |
| environment_id | string | ID of the &#96;environment&#96; where sessions run. |
| initial_events | array&lt;object&gt; | Events sent to each session immediately after creation. |
| initial_events[].content | array&lt;object&gt; | Array of content blocks for the user message. / System content blocks to append. Text-only. |
| initial_events[].type | string |  |
| initial_events[].description | string | What the agent should produce. This is the task specification. |
| initial_events[].rubric | object | Rubric for grading the quality of an outcome. |
| initial_events[].max_iterations | null &#124; number | Eval→revision cycles before giving up. Default 3, max 20. |
| metadata | object | Arbitrary key-value metadata. Maximum 16 pairs. |
| name | string | Human-readable name. |
| paused_reason | null &#124; object | Why a deployment is paused. Non-null exactly when &#96;status&#96; is &#96;paused&#96;. |
| paused_reason.type | string |  |
| paused_reason.error | object | The error that triggered an auto-pause. Matches the failed run's &#96;error.type&#96;. |
| resources | array&lt;object&gt; | Resources attached to sessions created from this deployment. Echoes the input minus write-only credentials. |
| resources[].type | string |  |
| resources[].url | string | Github URL of the repository |
| resources[].checkout | null &#124; object | Branch or commit to check out. Defaults to the repository's default branch. |
| resources[].mount_path | null &#124; string | Mount path in the container. Defaults to &#96;/workspace/&lt;repo-name&gt;&#96;. / Mount path in the container. Defaults to &#96;/mnt/session/uploads/&lt;file_id&gt;&#96;. |
| resources[].file_id | string | ID of a previously uploaded file. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| schedule | null &#124; object | 5-field POSIX cron schedule with computed runtime timestamps. |
| schedule.expression | string | 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g., "0 9 \* \* 1-5" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean Sunday. Extended cron syntax - seconds or year fields, and the special characters L, W, #, and ? - is not supported, nor are predefined shortcuts (@daily). |
| schedule.timezone | string | IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). |
| schedule.type | string |  |
| schedule.last_run_at | null &#124; string | A timestamp in RFC 3339 format |
| schedule.upcoming_runs_at | array&lt;string&gt; | Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused deployments (reflects what the schedule would do if unpaused); empty once the deployment is archived (&#96;archived_at&#96; set). Each fire is offset by a small per-schedule jitter, so a run will actually start at or shortly after its listed time. |
| status | string | Lifecycle status of a deployment. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_ids | array&lt;string&gt; | Vault IDs supplying stored credentials for sessions created from this deployment. |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this deployment. |
| agent | object | A resolved agent reference with a concrete version. |
| agent.id | string |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Description of what the deployment does. |
| environment_id | string | ID of the &#96;environment&#96; where sessions run. |
| initial_events | array&lt;object&gt; | Events sent to each session immediately after creation. |
| initial_events[].content | array&lt;object&gt; | Array of content blocks for the user message. / System content blocks to append. Text-only. |
| initial_events[].type | string |  |
| initial_events[].description | string | What the agent should produce. This is the task specification. |
| initial_events[].rubric | object | Rubric for grading the quality of an outcome. |
| initial_events[].max_iterations | null &#124; number | Eval→revision cycles before giving up. Default 3, max 20. |
| metadata | object | Arbitrary key-value metadata. Maximum 16 pairs. |
| name | string | Human-readable name. |
| paused_reason | null &#124; object | Why a deployment is paused. Non-null exactly when &#96;status&#96; is &#96;paused&#96;. |
| paused_reason.type | string |  |
| paused_reason.error | object | The error that triggered an auto-pause. Matches the failed run's &#96;error.type&#96;. |
| resources | array&lt;object&gt; | Resources attached to sessions created from this deployment. Echoes the input minus write-only credentials. |
| resources[].type | string |  |
| resources[].url | string | Github URL of the repository |
| resources[].checkout | null &#124; object | Branch or commit to check out. Defaults to the repository's default branch. |
| resources[].mount_path | null &#124; string | Mount path in the container. Defaults to &#96;/workspace/&lt;repo-name&gt;&#96;. / Mount path in the container. Defaults to &#96;/mnt/session/uploads/&lt;file_id&gt;&#96;. |
| resources[].file_id | string | ID of a previously uploaded file. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| schedule | null &#124; object | 5-field POSIX cron schedule with computed runtime timestamps. |
| schedule.expression | string | 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g., "0 9 \* \* 1-5" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean Sunday. Extended cron syntax - seconds or year fields, and the special characters L, W, #, and ? - is not supported, nor are predefined shortcuts (@daily). |
| schedule.timezone | string | IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). |
| schedule.type | string |  |
| schedule.last_run_at | null &#124; string | A timestamp in RFC 3339 format |
| schedule.upcoming_runs_at | array&lt;string&gt; | Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused deployments (reflects what the schedule would do if unpaused); empty once the deployment is archived (&#96;archived_at&#96; set). Each fire is offset by a small per-schedule jitter, so a run will actually start at or shortly after its listed time. |
| status | string | Lifecycle status of a deployment. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_ids | array&lt;string&gt; | Vault IDs supplying stored credentials for sessions created from this deployment. |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this deployment. |
| agent | object | A resolved agent reference with a concrete version. |
| agent.id | string |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Description of what the deployment does. |
| environment_id | string | ID of the &#96;environment&#96; where sessions run. |
| initial_events | array&lt;object&gt; | Events sent to each session immediately after creation. |
| initial_events[].content | array&lt;object&gt; | Array of content blocks for the user message. / System content blocks to append. Text-only. |
| initial_events[].type | string |  |
| initial_events[].description | string | What the agent should produce. This is the task specification. |
| initial_events[].rubric | object | Rubric for grading the quality of an outcome. |
| initial_events[].max_iterations | null &#124; number | Eval→revision cycles before giving up. Default 3, max 20. |
| metadata | object | Arbitrary key-value metadata. Maximum 16 pairs. |
| name | string | Human-readable name. |
| paused_reason | null &#124; object | Why a deployment is paused. Non-null exactly when &#96;status&#96; is &#96;paused&#96;. |
| paused_reason.type | string |  |
| paused_reason.error | object | The error that triggered an auto-pause. Matches the failed run's &#96;error.type&#96;. |
| resources | array&lt;object&gt; | Resources attached to sessions created from this deployment. Echoes the input minus write-only credentials. |
| resources[].type | string |  |
| resources[].url | string | Github URL of the repository |
| resources[].checkout | null &#124; object | Branch or commit to check out. Defaults to the repository's default branch. |
| resources[].mount_path | null &#124; string | Mount path in the container. Defaults to &#96;/workspace/&lt;repo-name&gt;&#96;. / Mount path in the container. Defaults to &#96;/mnt/session/uploads/&lt;file_id&gt;&#96;. |
| resources[].file_id | string | ID of a previously uploaded file. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| schedule | null &#124; object | 5-field POSIX cron schedule with computed runtime timestamps. |
| schedule.expression | string | 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g., "0 9 \* \* 1-5" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean Sunday. Extended cron syntax - seconds or year fields, and the special characters L, W, #, and ? - is not supported, nor are predefined shortcuts (@daily). |
| schedule.timezone | string | IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). |
| schedule.type | string |  |
| schedule.last_run_at | null &#124; string | A timestamp in RFC 3339 format |
| schedule.upcoming_runs_at | array&lt;string&gt; | Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused deployments (reflects what the schedule would do if unpaused); empty once the deployment is archived (&#96;archived_at&#96; set). Each fire is offset by a small per-schedule jitter, so a run will actually start at or shortly after its listed time. |
| status | string | Lifecycle status of a deployment. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_ids | array&lt;string&gt; | Vault IDs supplying stored credentials for sessions created from this deployment. |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this deployment. |
| agent | object | A resolved agent reference with a concrete version. |
| agent.id | string |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Description of what the deployment does. |
| environment_id | string | ID of the &#96;environment&#96; where sessions run. |
| initial_events | array&lt;object&gt; | Events sent to each session immediately after creation. |
| initial_events[].content | array&lt;object&gt; | Array of content blocks for the user message. / System content blocks to append. Text-only. |
| initial_events[].type | string |  |
| initial_events[].description | string | What the agent should produce. This is the task specification. |
| initial_events[].rubric | object | Rubric for grading the quality of an outcome. |
| initial_events[].max_iterations | null &#124; number | Eval→revision cycles before giving up. Default 3, max 20. |
| metadata | object | Arbitrary key-value metadata. Maximum 16 pairs. |
| name | string | Human-readable name. |
| paused_reason | null &#124; object | Why a deployment is paused. Non-null exactly when &#96;status&#96; is &#96;paused&#96;. |
| paused_reason.type | string |  |
| paused_reason.error | object | The error that triggered an auto-pause. Matches the failed run's &#96;error.type&#96;. |
| resources | array&lt;object&gt; | Resources attached to sessions created from this deployment. Echoes the input minus write-only credentials. |
| resources[].type | string |  |
| resources[].url | string | Github URL of the repository |
| resources[].checkout | null &#124; object | Branch or commit to check out. Defaults to the repository's default branch. |
| resources[].mount_path | null &#124; string | Mount path in the container. Defaults to &#96;/workspace/&lt;repo-name&gt;&#96;. / Mount path in the container. Defaults to &#96;/mnt/session/uploads/&lt;file_id&gt;&#96;. |
| resources[].file_id | string | ID of a previously uploaded file. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| schedule | null &#124; object | 5-field POSIX cron schedule with computed runtime timestamps. |
| schedule.expression | string | 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g., "0 9 \* \* 1-5" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean Sunday. Extended cron syntax - seconds or year fields, and the special characters L, W, #, and ? - is not supported, nor are predefined shortcuts (@daily). |
| schedule.timezone | string | IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). |
| schedule.type | string |  |
| schedule.last_run_at | null &#124; string | A timestamp in RFC 3339 format |
| schedule.upcoming_runs_at | array&lt;string&gt; | Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused deployments (reflects what the schedule would do if unpaused); empty once the deployment is archived (&#96;archived_at&#96; set). Each fire is offset by a small per-schedule jitter, so a run will actually start at or shortly after its listed time. |
| status | string | Lifecycle status of a deployment. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_ids | array&lt;string&gt; | Vault IDs supplying stored credentials for sessions created from this deployment. |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this run (&#96;drun_...&#96;). |
| agent | object | A resolved agent reference with a concrete version. |
| agent.id | string |  |
| agent.type | string |  |
| agent.version | number |  |
| created_at | string | A timestamp in RFC 3339 format |
| deployment_id | string | ID of the deployment that produced this run. |
| error | null &#124; object | Why the run failed to create a session. The type identifies the failure; message is human-readable detail. |
| error.message | string | Human-readable error description. |
| error.type | string |  |
| session_id | null &#124; string | Populated on success. Null on creation failure. Exactly one of &#96;session_id&#96; or &#96;error&#96; is non-null. |
| trigger_context | object | Describes what triggered a deployment run, with trigger-specific metadata. |
| trigger_context.scheduled_at | string | A timestamp in RFC 3339 format |
| trigger_context.type | string |  |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this deployment. |
| agent | object | A resolved agent reference with a concrete version. |
| agent.id | string |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Description of what the deployment does. |
| environment_id | string | ID of the &#96;environment&#96; where sessions run. |
| initial_events | array&lt;object&gt; | Events sent to each session immediately after creation. |
| initial_events[].content | array&lt;object&gt; | Array of content blocks for the user message. / System content blocks to append. Text-only. |
| initial_events[].type | string |  |
| initial_events[].description | string | What the agent should produce. This is the task specification. |
| initial_events[].rubric | object | Rubric for grading the quality of an outcome. |
| initial_events[].max_iterations | null &#124; number | Eval→revision cycles before giving up. Default 3, max 20. |
| metadata | object | Arbitrary key-value metadata. Maximum 16 pairs. |
| name | string | Human-readable name. |
| paused_reason | null &#124; object | Why a deployment is paused. Non-null exactly when &#96;status&#96; is &#96;paused&#96;. |
| paused_reason.type | string |  |
| paused_reason.error | object | The error that triggered an auto-pause. Matches the failed run's &#96;error.type&#96;. |
| resources | array&lt;object&gt; | Resources attached to sessions created from this deployment. Echoes the input minus write-only credentials. |
| resources[].type | string |  |
| resources[].url | string | Github URL of the repository |
| resources[].checkout | null &#124; object | Branch or commit to check out. Defaults to the repository's default branch. |
| resources[].mount_path | null &#124; string | Mount path in the container. Defaults to &#96;/workspace/&lt;repo-name&gt;&#96;. / Mount path in the container. Defaults to &#96;/mnt/session/uploads/&lt;file_id&gt;&#96;. |
| resources[].file_id | string | ID of a previously uploaded file. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| schedule | null &#124; object | 5-field POSIX cron schedule with computed runtime timestamps. |
| schedule.expression | string | 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g., "0 9 \* \* 1-5" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean Sunday. Extended cron syntax - seconds or year fields, and the special characters L, W, #, and ? - is not supported, nor are predefined shortcuts (@daily). |
| schedule.timezone | string | IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). |
| schedule.type | string |  |
| schedule.last_run_at | null &#124; string | A timestamp in RFC 3339 format |
| schedule.upcoming_runs_at | array&lt;string&gt; | Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused deployments (reflects what the schedule would do if unpaused); empty once the deployment is archived (&#96;archived_at&#96; set). Each fire is offset by a small per-schedule jitter, so a run will actually start at or shortly after its listed time. |
| status | string | Lifecycle status of a deployment. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_ids | array&lt;string&gt; | Vault IDs supplying stored credentials for sessions created from this deployment. |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Environment identifier (e.g., 'env\_...') |
| data[].archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| data[].config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| data[].created_at | string | RFC 3339 timestamp when environment was created |
| data[].description | null &#124; string | User-provided description for the environment; null when unset |
| data[].metadata | object | User-provided metadata key-value pairs |
| data[].name | string | Human-readable name for the environment |
| data[].type | string | The type of object (always 'environment') |
| data[].updated_at | string | RFC 3339 timestamp when environment was last updated |
| data[].scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier (e.g., 'env\_...') |
| archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| config.networking | object | Network configuration policy. |
| config.packages | object | Package manager configuration. |
| config.type | string | Environment type |
| created_at | string | RFC 3339 timestamp when environment was created |
| description | null &#124; string | User-provided description for the environment; null when unset |
| metadata | object | User-provided metadata key-value pairs |
| name | string | Human-readable name for the environment |
| type | string | The type of object (always 'environment') |
| updated_at | string | RFC 3339 timestamp when environment was last updated |
| scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier |
| type | string | The type of response |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier (e.g., 'env\_...') |
| archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| config.networking | object | Network configuration policy. |
| config.packages | object | Package manager configuration. |
| config.type | string | Environment type |
| created_at | string | RFC 3339 timestamp when environment was created |
| description | null &#124; string | User-provided description for the environment; null when unset |
| metadata | object | User-provided metadata key-value pairs |
| name | string | Human-readable name for the environment |
| type | string | The type of object (always 'environment') |
| updated_at | string | RFC 3339 timestamp when environment was last updated |
| scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier (e.g., 'env\_...') |
| archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| config.networking | object | Network configuration policy. |
| config.packages | object | Package manager configuration. |
| config.type | string | Environment type |
| created_at | string | RFC 3339 timestamp when environment was created |
| description | null &#124; string | User-provided description for the environment; null when unset |
| metadata | object | User-provided metadata key-value pairs |
| name | string | Human-readable name for the environment |
| type | string | The type of object (always 'environment') |
| updated_at | string | RFC 3339 timestamp when environment was last updated |
| scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier (e.g., 'env\_...') |
| archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| config.networking | object | Network configuration policy. |
| config.packages | object | Package manager configuration. |
| config.type | string | Environment type |
| created_at | string | RFC 3339 timestamp when environment was created |
| description | null &#124; string | User-provided description for the environment; null when unset |
| metadata | object | User-provided metadata key-value pairs |
| name | string | Human-readable name for the environment |
| type | string | The type of object (always 'environment') |
| updated_at | string | RFC 3339 timestamp when environment was last updated |
| scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Work identifier (e.g., 'work\_...') |
| data[].acknowledged_at | null &#124; string | RFC 3339 timestamp when work was acknowledged by Environment Manager |
| data[].created_at | string | RFC 3339 timestamp when work was created |
| data[].data | object | The actual work to be performed (session or health check) |
| data[].environment_id | string | Environment identifier this work belongs to (e.g., &#96;env_...&#96;) |
| data[].latest_heartbeat_at | null &#124; string | RFC 3339 timestamp of the most recent heartbeat |
| data[].metadata | object | User-provided metadata key-value pairs associated with this work item |
| data[].secret | null &#124; string | Credential payload used by the environment worker to execute this work item. May be populated when polling for work; null on all other retrieval paths. |
| data[].started_at | null &#124; string | RFC 3339 timestamp when work execution started |
| data[].state | string | Current state of the work item |
| data[].stop_requested_at | null &#124; string | RFC 3339 timestamp when stop was requested |
| data[].stopped_at | null &#124; string | RFC 3339 timestamp when work execution stopped |
| data[].type | string | The type of object (always 'work') |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Work identifier (e.g., 'work\_...') |
| acknowledged_at | null &#124; string | RFC 3339 timestamp when work was acknowledged by Environment Manager |
| created_at | string | RFC 3339 timestamp when work was created |
| data | object | The actual work to be performed (session or health check) |
| data.id | string | Session identifier (e.g., 'session\_...') / Health check identifier |
| data.type | string | Type of work data |
| environment_id | string | Environment identifier this work belongs to (e.g., &#96;env_...&#96;) |
| latest_heartbeat_at | null &#124; string | RFC 3339 timestamp of the most recent heartbeat |
| metadata | object | User-provided metadata key-value pairs associated with this work item |
| secret | null &#124; string | Credential payload used by the environment worker to execute this work item. May be populated when polling for work; null on all other retrieval paths. |
| started_at | null &#124; string | RFC 3339 timestamp when work execution started |
| state | string | Current state of the work item |
| stop_requested_at | null &#124; string | RFC 3339 timestamp when stop was requested |
| stopped_at | null &#124; string | RFC 3339 timestamp when work execution stopped |
| type | string | The type of object (always 'work') |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Work identifier (e.g., 'work\_...') |
| acknowledged_at | null &#124; string | RFC 3339 timestamp when work was acknowledged by Environment Manager |
| created_at | string | RFC 3339 timestamp when work was created |
| data | object | The actual work to be performed (session or health check) |
| data.id | string | Session identifier (e.g., 'session\_...') / Health check identifier |
| data.type | string | Type of work data |
| environment_id | string | Environment identifier this work belongs to (e.g., &#96;env_...&#96;) |
| latest_heartbeat_at | null &#124; string | RFC 3339 timestamp of the most recent heartbeat |
| metadata | object | User-provided metadata key-value pairs associated with this work item |
| secret | null &#124; string | Credential payload used by the environment worker to execute this work item. May be populated when polling for work; null on all other retrieval paths. |
| started_at | null &#124; string | RFC 3339 timestamp when work execution started |
| state | string | Current state of the work item |
| stop_requested_at | null &#124; string | RFC 3339 timestamp when stop was requested |
| stopped_at | null &#124; string | RFC 3339 timestamp when work execution stopped |
| type | string | The type of object (always 'work') |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Work identifier (e.g., 'work\_...') |
| acknowledged_at | null &#124; string | RFC 3339 timestamp when work was acknowledged by Environment Manager |
| created_at | string | RFC 3339 timestamp when work was created |
| data | object | The actual work to be performed (session or health check) |
| data.id | string | Session identifier (e.g., 'session\_...') / Health check identifier |
| data.type | string | Type of work data |
| environment_id | string | Environment identifier this work belongs to (e.g., &#96;env_...&#96;) |
| latest_heartbeat_at | null &#124; string | RFC 3339 timestamp of the most recent heartbeat |
| metadata | object | User-provided metadata key-value pairs associated with this work item |
| secret | null &#124; string | Credential payload used by the environment worker to execute this work item. May be populated when polling for work; null on all other retrieval paths. |
| started_at | null &#124; string | RFC 3339 timestamp when work execution started |
| state | string | Current state of the work item |
| stop_requested_at | null &#124; string | RFC 3339 timestamp when stop was requested |
| stopped_at | null &#124; string | RFC 3339 timestamp when work execution stopped |
| type | string | The type of object (always 'work') |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| last_heartbeat | string | RFC 3339 timestamp of the actual heartbeat from DB |
| lease_extended | boolean | Whether the heartbeat succeeded in extending the lease |
| state | string | Current state of the work item (active/stopping/stopped) |
| ttl_seconds | number | Effective TTL applied to the lease |
| type | string | The type of response |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Work identifier (e.g., 'work\_...') |
| acknowledged_at | null &#124; string | RFC 3339 timestamp when work was acknowledged by Environment Manager |
| created_at | string | RFC 3339 timestamp when work was created |
| data | object | The actual work to be performed (session or health check) |
| data.id | string | Session identifier (e.g., 'session\_...') / Health check identifier |
| data.type | string | Type of work data |
| environment_id | string | Environment identifier this work belongs to (e.g., &#96;env_...&#96;) |
| latest_heartbeat_at | null &#124; string | RFC 3339 timestamp of the most recent heartbeat |
| metadata | object | User-provided metadata key-value pairs associated with this work item |
| secret | null &#124; string | Credential payload used by the environment worker to execute this work item. May be populated when polling for work; null on all other retrieval paths. |
| started_at | null &#124; string | RFC 3339 timestamp when work execution started |
| state | string | Current state of the work item |
| stop_requested_at | null &#124; string | RFC 3339 timestamp when stop was requested |
| stopped_at | null &#124; string | RFC 3339 timestamp when work execution stopped |
| type | string | The type of object (always 'work') |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Work identifier (e.g., 'work\_...') |
| acknowledged_at | null &#124; string | RFC 3339 timestamp when work was acknowledged by Environment Manager |
| created_at | string | RFC 3339 timestamp when work was created |
| data | object | The actual work to be performed (session or health check) |
| data.id | string | Session identifier (e.g., 'session\_...') / Health check identifier |
| data.type | string | Type of work data |
| environment_id | string | Environment identifier this work belongs to (e.g., &#96;env_...&#96;) |
| latest_heartbeat_at | null &#124; string | RFC 3339 timestamp of the most recent heartbeat |
| metadata | object | User-provided metadata key-value pairs associated with this work item |
| secret | null &#124; string | Credential payload used by the environment worker to execute this work item. May be populated when polling for work; null on all other retrieval paths. |
| started_at | null &#124; string | RFC 3339 timestamp when work execution started |
| state | string | Current state of the work item |
| stop_requested_at | null &#124; string | RFC 3339 timestamp when stop was requested |
| stopped_at | null &#124; string | RFC 3339 timestamp when work execution stopped |
| type | string | The type of object (always 'work') |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| depth | number | Number of work items waiting to be picked up (lag from consumer group) |
| oldest_queued_at | null &#124; string | RFC 3339 timestamp of oldest item in the work stream (includes both queued and pending items), null if stream empty |
| pending | number | Number of work items being processed (polled but not acknowledged) |
| type | string | The type of object |
| workers_polling | null &#124; number | Number of workers that have polled for work in the last 30 seconds. Requires worker_id to be sent with poll requests. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for the memory store (a &#96;memstore_...&#96; tagged ID). Use this when attaching the store to a session, or in the &#96;&#123;memory_store_id&#125;&#96; path parameter of subsequent calls. |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].name | string | Human-readable name for the store. 1–255 characters. The store's mount-path slug under &#96;/mnt/memory/&#96; is derived from this name. |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].description | string | Free-text description of what the store contains, up to 1024 characters. Included in the agent's system prompt when the store is attached, so word it to be useful to the agent. Empty string when unset. |
| data[].metadata | object | Arbitrary key-value tags for your own bookkeeping (such as the end user a store belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters. Returned on retrieve/list but not filterable. |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the memory store (a &#96;memstore_...&#96; tagged ID). Use this when attaching the store to a session, or in the &#96;&#123;memory_store_id&#125;&#96; path parameter of subsequent calls. |
| created_at | string | A timestamp in RFC 3339 format |
| name | string | Human-readable name for the store. 1–255 characters. The store's mount-path slug under &#96;/mnt/memory/&#96; is derived from this name. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| description | string | Free-text description of what the store contains, up to 1024 characters. Included in the agent's system prompt when the store is attached, so word it to be useful to the agent. Empty string when unset. |
| metadata | object | Arbitrary key-value tags for your own bookkeeping (such as the end user a store belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters. Returned on retrieve/list but not filterable. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | ID of the deleted memory store (a &#96;memstore_...&#96; identifier). The store and all its memories and versions are no longer retrievable. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the memory store (a &#96;memstore_...&#96; tagged ID). Use this when attaching the store to a session, or in the &#96;&#123;memory_store_id&#125;&#96; path parameter of subsequent calls. |
| created_at | string | A timestamp in RFC 3339 format |
| name | string | Human-readable name for the store. 1–255 characters. The store's mount-path slug under &#96;/mnt/memory/&#96; is derived from this name. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| description | string | Free-text description of what the store contains, up to 1024 characters. Included in the agent's system prompt when the store is attached, so word it to be useful to the agent. Empty string when unset. |
| metadata | object | Arbitrary key-value tags for your own bookkeeping (such as the end user a store belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters. Returned on retrieve/list but not filterable. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the memory store (a &#96;memstore_...&#96; tagged ID). Use this when attaching the store to a session, or in the &#96;&#123;memory_store_id&#125;&#96; path parameter of subsequent calls. |
| created_at | string | A timestamp in RFC 3339 format |
| name | string | Human-readable name for the store. 1–255 characters. The store's mount-path slug under &#96;/mnt/memory/&#96; is derived from this name. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| description | string | Free-text description of what the store contains, up to 1024 characters. Included in the agent's system prompt when the store is attached, so word it to be useful to the agent. Empty string when unset. |
| metadata | object | Arbitrary key-value tags for your own bookkeeping (such as the end user a store belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters. Returned on retrieve/list but not filterable. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the memory store (a &#96;memstore_...&#96; tagged ID). Use this when attaching the store to a session, or in the &#96;&#123;memory_store_id&#125;&#96; path parameter of subsequent calls. |
| created_at | string | A timestamp in RFC 3339 format |
| name | string | Human-readable name for the store. 1–255 characters. The store's mount-path slug under &#96;/mnt/memory/&#96; is derived from this name. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| description | string | Free-text description of what the store contains, up to 1024 characters. Included in the agent's system prompt when the store is attached, so word it to be useful to the agent. Empty string when unset. |
| metadata | object | Arbitrary key-value tags for your own bookkeeping (such as the end user a store belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters. Returned on retrieve/list but not filterable. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for this memory (a &#96;mem_...&#96; value). Stable across renames; use this ID, not the path, to read, update, or delete the memory. |
| data[].content_sha256 | string | Lowercase hex SHA-256 digest of the UTF-8 &#96;content&#96; bytes (64 characters). The server applies no normalization, so clients can compute the same hash locally for staleness checks and as the value for a &#96;content_sha256&#96; precondition on update. Always populated, regardless of &#96;view&#96;. |
| data[].content_size_bytes | number | Size of &#96;content&#96; in bytes (the UTF-8 plaintext length). Always populated, regardless of &#96;view&#96;. |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].memory_store_id | string | ID of the memory store this memory belongs to (a &#96;memstore_...&#96; value). |
| data[].memory_version_id | string | ID of the &#96;memory_version&#96; representing this memory's current content (a &#96;memver_...&#96; value). This is the authoritative head pointer; &#96;memory_version&#96; objects do not carry an &#96;is_latest&#96; flag, so compare against this field instead. Enumerate the history via [List memory versions](/en/api/beta/memory_stores/memory_versions/list). |
| data[].path | string | Hierarchical path of the memory within the store, e.g. &#96;/projects/foo/notes.md&#96;. Always starts with &#96;/&#96;. Paths are case-sensitive and unique within a store. Maximum 1,024 bytes. / The rolled-up path prefix, including a trailing &#96;/&#96; (e.g. &#96;/projects/foo/&#96;). Pass this value as &#96;path_prefix&#96; on a subsequent list call to drill into the directory. |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].content | null &#124; string | The memory's UTF-8 text content. Populated when &#96;view=full&#96;; &#96;null&#96; when &#96;view=basic&#96;. Maximum 100 kB (102,400 bytes). |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this memory (a &#96;mem_...&#96; value). Stable across renames; use this ID, not the path, to read, update, or delete the memory. |
| content_sha256 | string | Lowercase hex SHA-256 digest of the UTF-8 &#96;content&#96; bytes (64 characters). The server applies no normalization, so clients can compute the same hash locally for staleness checks and as the value for a &#96;content_sha256&#96; precondition on update. Always populated, regardless of &#96;view&#96;. |
| content_size_bytes | number | Size of &#96;content&#96; in bytes (the UTF-8 plaintext length). Always populated, regardless of &#96;view&#96;. |
| created_at | string | A timestamp in RFC 3339 format |
| memory_store_id | string | ID of the memory store this memory belongs to (a &#96;memstore_...&#96; value). |
| memory_version_id | string | ID of the &#96;memory_version&#96; representing this memory's current content (a &#96;memver_...&#96; value). This is the authoritative head pointer; &#96;memory_version&#96; objects do not carry an &#96;is_latest&#96; flag, so compare against this field instead. Enumerate the history via [List memory versions](/en/api/beta/memory_stores/memory_versions/list). |
| path | string | Hierarchical path of the memory within the store, e.g. &#96;/projects/foo/notes.md&#96;. Always starts with &#96;/&#96;. Paths are case-sensitive and unique within a store. Maximum 1,024 bytes. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| content | null &#124; string | The memory's UTF-8 text content. Populated when &#96;view=full&#96;; &#96;null&#96; when &#96;view=basic&#96;. Maximum 100 kB (102,400 bytes). |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | ID of the deleted memory (a &#96;mem_...&#96; value). |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this memory (a &#96;mem_...&#96; value). Stable across renames; use this ID, not the path, to read, update, or delete the memory. |
| content_sha256 | string | Lowercase hex SHA-256 digest of the UTF-8 &#96;content&#96; bytes (64 characters). The server applies no normalization, so clients can compute the same hash locally for staleness checks and as the value for a &#96;content_sha256&#96; precondition on update. Always populated, regardless of &#96;view&#96;. |
| content_size_bytes | number | Size of &#96;content&#96; in bytes (the UTF-8 plaintext length). Always populated, regardless of &#96;view&#96;. |
| created_at | string | A timestamp in RFC 3339 format |
| memory_store_id | string | ID of the memory store this memory belongs to (a &#96;memstore_...&#96; value). |
| memory_version_id | string | ID of the &#96;memory_version&#96; representing this memory's current content (a &#96;memver_...&#96; value). This is the authoritative head pointer; &#96;memory_version&#96; objects do not carry an &#96;is_latest&#96; flag, so compare against this field instead. Enumerate the history via [List memory versions](/en/api/beta/memory_stores/memory_versions/list). |
| path | string | Hierarchical path of the memory within the store, e.g. &#96;/projects/foo/notes.md&#96;. Always starts with &#96;/&#96;. Paths are case-sensitive and unique within a store. Maximum 1,024 bytes. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| content | null &#124; string | The memory's UTF-8 text content. Populated when &#96;view=full&#96;; &#96;null&#96; when &#96;view=basic&#96;. Maximum 100 kB (102,400 bytes). |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this memory (a &#96;mem_...&#96; value). Stable across renames; use this ID, not the path, to read, update, or delete the memory. |
| content_sha256 | string | Lowercase hex SHA-256 digest of the UTF-8 &#96;content&#96; bytes (64 characters). The server applies no normalization, so clients can compute the same hash locally for staleness checks and as the value for a &#96;content_sha256&#96; precondition on update. Always populated, regardless of &#96;view&#96;. |
| content_size_bytes | number | Size of &#96;content&#96; in bytes (the UTF-8 plaintext length). Always populated, regardless of &#96;view&#96;. |
| created_at | string | A timestamp in RFC 3339 format |
| memory_store_id | string | ID of the memory store this memory belongs to (a &#96;memstore_...&#96; value). |
| memory_version_id | string | ID of the &#96;memory_version&#96; representing this memory's current content (a &#96;memver_...&#96; value). This is the authoritative head pointer; &#96;memory_version&#96; objects do not carry an &#96;is_latest&#96; flag, so compare against this field instead. Enumerate the history via [List memory versions](/en/api/beta/memory_stores/memory_versions/list). |
| path | string | Hierarchical path of the memory within the store, e.g. &#96;/projects/foo/notes.md&#96;. Always starts with &#96;/&#96;. Paths are case-sensitive and unique within a store. Maximum 1,024 bytes. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| content | null &#124; string | The memory's UTF-8 text content. Populated when &#96;view=full&#96;; &#96;null&#96; when &#96;view=basic&#96;. Maximum 100 kB (102,400 bytes). |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for this version (a &#96;memver_...&#96; value). |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].memory_id | string | ID of the memory this version snapshots (a &#96;mem_...&#96; value). Remains valid after the memory is deleted; pass it as &#96;memory_id&#96; to [List memory versions](/en/api/beta/memory_stores/memory_versions/list) to retrieve the memory's retained versions, including the &#96;deleted&#96; row while the lineage is retained. |
| data[].memory_store_id | string | ID of the memory store this version belongs to (a &#96;memstore_...&#96; value). |
| data[].operation | string | The kind of mutation a &#96;memory_version&#96; records. Every non-no-op mutation to a memory appends exactly one version row with one of these values. |
| data[].type | string |  |
| data[].content | null &#124; string | The memory's UTF-8 text content as of this version. &#96;null&#96; when &#96;view=basic&#96;, when &#96;operation&#96; is &#96;deleted&#96;, or when &#96;redacted_at&#96; is set. |
| data[].content_sha256 | null &#124; string | Lowercase hex SHA-256 digest of &#96;content&#96; as of this version (64 characters). &#96;null&#96; when &#96;redacted_at&#96; is set or &#96;operation&#96; is &#96;deleted&#96;. Populated regardless of &#96;view&#96; otherwise. |
| data[].content_size_bytes | null &#124; number | Size of &#96;content&#96; in bytes as of this version. &#96;null&#96; when &#96;redacted_at&#96; is set or &#96;operation&#96; is &#96;deleted&#96;. Populated regardless of &#96;view&#96; otherwise. |
| data[].created_by | object | Identifies who performed a write or redact operation. Captured at write time on the &#96;memory_version&#96; row. The API key that created a session is not recorded on agent writes; attribution answers who made the write, not who is ultimately responsible. Look up session provenance separately via the [Sessions API](/en/api/beta/sessions/retrieve). |
| data[].path | null &#124; string | The memory's path at the time of this write. &#96;null&#96; if and only if &#96;redacted_at&#96; is set. |
| data[].redacted_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].redacted_by | object | Identifies who performed a write or redact operation. Captured at write time on the &#96;memory_version&#96; row. The API key that created a session is not recorded on agent writes; attribution answers who made the write, not who is ultimately responsible. Look up session provenance separately via the [Sessions API](/en/api/beta/sessions/retrieve). |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this version (a &#96;memver_...&#96; value). |
| created_at | string | A timestamp in RFC 3339 format |
| memory_id | string | ID of the memory this version snapshots (a &#96;mem_...&#96; value). Remains valid after the memory is deleted; pass it as &#96;memory_id&#96; to [List memory versions](/en/api/beta/memory_stores/memory_versions/list) to retrieve the memory's retained versions, including the &#96;deleted&#96; row while the lineage is retained. |
| memory_store_id | string | ID of the memory store this version belongs to (a &#96;memstore_...&#96; value). |
| operation | string | The kind of mutation a &#96;memory_version&#96; records. Every non-no-op mutation to a memory appends exactly one version row with one of these values. |
| type | string |  |
| content | null &#124; string | The memory's UTF-8 text content as of this version. &#96;null&#96; when &#96;view=basic&#96;, when &#96;operation&#96; is &#96;deleted&#96;, or when &#96;redacted_at&#96; is set. |
| content_sha256 | null &#124; string | Lowercase hex SHA-256 digest of &#96;content&#96; as of this version (64 characters). &#96;null&#96; when &#96;redacted_at&#96; is set or &#96;operation&#96; is &#96;deleted&#96;. Populated regardless of &#96;view&#96; otherwise. |
| content_size_bytes | null &#124; number | Size of &#96;content&#96; in bytes as of this version. &#96;null&#96; when &#96;redacted_at&#96; is set or &#96;operation&#96; is &#96;deleted&#96;. Populated regardless of &#96;view&#96; otherwise. |
| created_by | object | Identifies who performed a write or redact operation. Captured at write time on the &#96;memory_version&#96; row. The API key that created a session is not recorded on agent writes; attribution answers who made the write, not who is ultimately responsible. Look up session provenance separately via the [Sessions API](/en/api/beta/sessions/retrieve). |
| created_by.session_id | string | ID of the session that performed the write (a &#96;sesn_...&#96; value). Look up the session via [Retrieve a session](/en/api/beta/sessions/retrieve) for further provenance. |
| created_by.type | string |  |
| created_by.api_key_id | string | ID of the API key that performed the write. This identifies the key, not the secret. |
| created_by.user_id | string | ID of the user who performed the write (a &#96;user_...&#96; value). |
| created_by.service_account_id | string | ID of the service account that performed the write (a &#96;svac_...&#96; value). |
| path | null &#124; string | The memory's path at the time of this write. &#96;null&#96; if and only if &#96;redacted_at&#96; is set. |
| redacted_at | null &#124; string | A timestamp in RFC 3339 format |
| redacted_by | object | Identifies who performed a write or redact operation. Captured at write time on the &#96;memory_version&#96; row. The API key that created a session is not recorded on agent writes; attribution answers who made the write, not who is ultimately responsible. Look up session provenance separately via the [Sessions API](/en/api/beta/sessions/retrieve). |
| redacted_by.session_id | string | ID of the session that performed the write (a &#96;sesn_...&#96; value). Look up the session via [Retrieve a session](/en/api/beta/sessions/retrieve) for further provenance. |
| redacted_by.type | string |  |
| redacted_by.api_key_id | string | ID of the API key that performed the write. This identifies the key, not the secret. |
| redacted_by.user_id | string | ID of the user who performed the write (a &#96;user_...&#96; value). |
| redacted_by.service_account_id | string | ID of the service account that performed the write (a &#96;svac_...&#96; value). |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this version (a &#96;memver_...&#96; value). |
| created_at | string | A timestamp in RFC 3339 format |
| memory_id | string | ID of the memory this version snapshots (a &#96;mem_...&#96; value). Remains valid after the memory is deleted; pass it as &#96;memory_id&#96; to [List memory versions](/en/api/beta/memory_stores/memory_versions/list) to retrieve the memory's retained versions, including the &#96;deleted&#96; row while the lineage is retained. |
| memory_store_id | string | ID of the memory store this version belongs to (a &#96;memstore_...&#96; value). |
| operation | string | The kind of mutation a &#96;memory_version&#96; records. Every non-no-op mutation to a memory appends exactly one version row with one of these values. |
| type | string |  |
| content | null &#124; string | The memory's UTF-8 text content as of this version. &#96;null&#96; when &#96;view=basic&#96;, when &#96;operation&#96; is &#96;deleted&#96;, or when &#96;redacted_at&#96; is set. |
| content_sha256 | null &#124; string | Lowercase hex SHA-256 digest of &#96;content&#96; as of this version (64 characters). &#96;null&#96; when &#96;redacted_at&#96; is set or &#96;operation&#96; is &#96;deleted&#96;. Populated regardless of &#96;view&#96; otherwise. |
| content_size_bytes | null &#124; number | Size of &#96;content&#96; in bytes as of this version. &#96;null&#96; when &#96;redacted_at&#96; is set or &#96;operation&#96; is &#96;deleted&#96;. Populated regardless of &#96;view&#96; otherwise. |
| created_by | object | Identifies who performed a write or redact operation. Captured at write time on the &#96;memory_version&#96; row. The API key that created a session is not recorded on agent writes; attribution answers who made the write, not who is ultimately responsible. Look up session provenance separately via the [Sessions API](/en/api/beta/sessions/retrieve). |
| created_by.session_id | string | ID of the session that performed the write (a &#96;sesn_...&#96; value). Look up the session via [Retrieve a session](/en/api/beta/sessions/retrieve) for further provenance. |
| created_by.type | string |  |
| created_by.api_key_id | string | ID of the API key that performed the write. This identifies the key, not the secret. |
| created_by.user_id | string | ID of the user who performed the write (a &#96;user_...&#96; value). |
| created_by.service_account_id | string | ID of the service account that performed the write (a &#96;svac_...&#96; value). |
| path | null &#124; string | The memory's path at the time of this write. &#96;null&#96; if and only if &#96;redacted_at&#96; is set. |
| redacted_at | null &#124; string | A timestamp in RFC 3339 format |
| redacted_by | object | Identifies who performed a write or redact operation. Captured at write time on the &#96;memory_version&#96; row. The API key that created a session is not recorded on agent writes; attribution answers who made the write, not who is ultimately responsible. Look up session provenance separately via the [Sessions API](/en/api/beta/sessions/retrieve). |
| redacted_by.session_id | string | ID of the session that performed the write (a &#96;sesn_...&#96; value). Look up the session via [Retrieve a session](/en/api/beta/sessions/retrieve) for further provenance. |
| redacted_by.type | string |  |
| redacted_by.api_key_id | string | ID of the API key that performed the write. This identifies the key, not the secret. |
| redacted_by.user_id | string | ID of the user who performed the write (a &#96;user_...&#96; value). |
| redacted_by.service_account_id | string | ID of the service account that performed the write (a &#96;svac_...&#96; value). |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| type | string |  |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string |  |
| agent.description | null &#124; string |  |
| agent.mcp_servers | array&lt;object&gt; |  |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string |  |
| agent.skills | array&lt;object&gt; |  |
| agent.system | null &#124; string |  |
| agent.tools | array&lt;object&gt; |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string |  |
| metadata | object |  |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string |  |
| resources | array&lt;object&gt; |  |
| resources[].id | string |  |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string |  |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string |  |
| resources[].checkout | null &#124; object |  |
| resources[].file_id | string |  |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |

# 归档会话

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string |  |
| agent.description | null &#124; string |  |
| agent.mcp_servers | array&lt;object&gt; |  |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string |  |
| agent.skills | array&lt;object&gt; |  |
| agent.system | null &#124; string |  |
| agent.tools | array&lt;object&gt; |  |
| agent.type | string |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string |  |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string |  |
| metadata | object |  |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string |  |
| resources | array&lt;object&gt; |  |
| resources[].id | string |  |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string |  |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string |  |
| resources[].checkout | null &#124; object |  |
| resources[].file_id | string |  |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string |  |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].mount_path | string &#124; null &#124; string | Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].url | string |  |
| data[].checkout | null &#124; object |  |
| data[].file_id | string |  |
| data[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| data[].access | null &#124; string | Access mode for an attached memory store. |
| data[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| data[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| data[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| created_at | string | A timestamp in RFC 3339 format |
| file_id | string |  |
| mount_path | string |  |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| created_at | string | A timestamp in RFC 3339 format |
| mount_path | string &#124; null &#124; string | Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| url | string |  |
| checkout | null &#124; object |  |
| checkout.name | string | Branch name to check out. |
| checkout.type | string |  |
| checkout.sha | string | Full commit SHA to check out. |
| file_id | string |  |
| memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| access | null &#124; string | Access mode for an attached memory store. |
| description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| created_at | string | A timestamp in RFC 3339 format |
| mount_path | string &#124; null &#124; string | Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| url | string |  |
| checkout | null &#124; object |  |
| checkout.name | string | Branch name to check out. |
| checkout.type | string |  |
| checkout.sha | string | Full commit SHA to check out. |
| file_id | string |  |
| memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| access | null &#124; string | Access mode for an attached memory store. |
| description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for this thread. |
| data[].agent | object | The resolved agent a &#96;session_thread&#96; runs. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].parent_thread_id | null &#124; string | Parent thread that spawned this thread. Null for the primary thread. |
| data[].session_id | string | The session this thread belongs to. |
| data[].stats | null &#124; object | Timing statistics for a session thread. |
| data[].status | string | SessionThreadStatus enum |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].usage | null &#124; object | Cumulative token usage for a session thread across all turns. |
| next_page | string &#124; null |  |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this thread. |
| agent | object | The resolved agent a &#96;session_thread&#96; runs. |
| agent.model | string &#124; object | The advisor model id. / Model identifier and configuration. |
| agent.type | string |  |
| agent.id | string |  |
| agent.description | null &#124; string |  |
| agent.mcp_servers | array&lt;object&gt; |  |
| agent.name | string |  |
| agent.skills | array&lt;object&gt; |  |
| agent.system | null &#124; string |  |
| agent.tools | array&lt;object&gt; |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| parent_thread_id | null &#124; string | Parent thread that spawned this thread. Null for the primary thread. |
| session_id | string | The session this thread belongs to. |
| stats | null &#124; object | Timing statistics for a session thread. |
| stats.active_seconds | number | Cumulative time in seconds the thread spent actively running. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since thread creation in seconds. For archived threads, frozen at the final update. |
| stats.startup_seconds | number | Time in seconds for the thread to begin running. Zero for child threads, which start immediately. |
| status | string | SessionThreadStatus enum |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | null &#124; object | Cumulative token usage for a session thread across all turns. |
| usage.active_seconds | number | Cumulative time in seconds this thread spent in running status. Equal to &#96;stats.active_seconds&#96;; surfaced here so a thread's usage carries every quantity its cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this thread. |
| agent | object | The resolved agent a &#96;session_thread&#96; runs. |
| agent.model | string &#124; object | The advisor model id. / Model identifier and configuration. |
| agent.type | string |  |
| agent.id | string |  |
| agent.description | null &#124; string |  |
| agent.mcp_servers | array&lt;object&gt; |  |
| agent.name | string |  |
| agent.skills | array&lt;object&gt; |  |
| agent.system | null &#124; string |  |
| agent.tools | array&lt;object&gt; |  |
| agent.version | number |  |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| parent_thread_id | null &#124; string | Parent thread that spawned this thread. Null for the primary thread. |
| session_id | string | The session this thread belongs to. |
| stats | null &#124; object | Timing statistics for a session thread. |
| stats.active_seconds | number | Cumulative time in seconds the thread spent actively running. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since thread creation in seconds. For archived threads, frozen at the final update. |
| stats.startup_seconds | number | Time in seconds for the thread to begin running. Zero for child threads, which start immediately. |
| status | string | SessionThreadStatus enum |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | null &#124; object | Cumulative token usage for a session thread across all turns. |
| usage.active_seconds | number | Cumulative time in seconds this thread spent in running status. Equal to &#96;stats.active_seconds&#96;; surfaced here so a thread's usage carries every quantity its cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for this event. |
| data[].content | array&lt;object&gt; | Array of content blocks comprising the user message. / The result content returned by the tool. / Array of text blocks comprising the agent response. / The result content returned by the tool. / The result content returned by the tool. / Message content blocks. / Message content blocks. / The result content returned by the tool. / System content blocks. Text-only. |
| data[].type | string |  |
| data[].processed_at | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string | A timestamp in RFC 3339 format |
| data[].session_thread_id | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string | If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Set by the server to the subagent thread this confirmation was routed to. Omitted when it was routed to the primary thread. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / When set, this event was cross-posted from a subagent's thread to surface its custom tool use on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.custom_tool_result&#96; by &#96;custom_tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; or &#96;user.tool_result&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / Public &#96;sthr_&#96; ID of the newly created thread. / Public sthr\_ ID of the thread that started running. / Public sthr\_ ID of the thread that went idle. / Public sthr\_ ID of the thread that terminated. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / Public sthr\_ ID of the thread that is retrying. |
| data[].result | string | UserToolConfirmationResult enum / Evaluation verdict. 'satisfied': criteria met, session goes idle. 'needs_revision': criteria not met, another revision cycle follows. 'max_iterations_reached': evaluation budget exhausted with criteria still unmet — one final acknowledgment turn follows before the session goes idle, but no further evaluation runs. 'failed': grader determined the rubric does not apply to the deliverables. 'interrupted': user sent an interrupt while evaluation was in progress. |
| data[].tool_use_id | string | The id of the &#96;agent.tool_use&#96; or &#96;agent.mcp_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. / The id of the &#96;agent.tool_use&#96; event this result corresponds to. / The id of the &#96;agent.tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].deny_message | null &#124; string | Optional message providing context for a 'deny' decision. Only allowed when result is 'deny'. |
| data[].custom_tool_use_id | string | The id of the &#96;agent.custom_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].is_error | null &#124; boolean | Whether the tool execution resulted in an error. / Whether the model request resulted in an error. / Whether the tool execution resulted in an error. |
| data[].input | object | Input parameters for the tool call. |
| data[].name | string | Name of the custom tool being called. / Name of the MCP tool being used. / Name of the agent tool being used. |
| data[].mcp_server_name | string | Name of the MCP server providing the tool. |
| data[].evaluated_permission | string | AgentEvaluatedPermission enum |
| data[].evaluation | object | Names the resolved permission_policy that produced evaluated_permission, and under auto carries the judgement. Open union: clients must tolerate unknown variants. |
| data[].mcp_tool_use_id | string | The id of the &#96;agent.mcp_tool_use&#96; event this result corresponds to. |
| data[].from_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread that sent the message. |
| data[].from_agent_name | null &#124; string | Name of the callable agent this message came from. Absent when received from the primary agent. |
| data[].to_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread the message was sent to. |
| data[].to_agent_name | null &#124; string | Name of the callable agent this message was sent to. Absent when sent to the primary agent. |
| data[].error | object |  |
| data[].stop_reason | object |  |
| data[].agent_name | string | Name of the callable agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. |
| data[].iteration | number | 0-indexed revision cycle. 0 is the first evaluation; 1 is the re-evaluation after the first revision; etc. / 0-indexed revision cycle, matching the corresponding &#96;span.outcome_evaluation_start&#96;. / 0-indexed revision cycle, matching the corresponding &#96;span.outcome_evaluation_start&#96;. |
| data[].outcome_id | string | The &#96;outc_&#96; ID of the outcome being evaluated. / Server-generated &#96;outc_&#96; ID for this outcome. Referenced by &#96;span.outcome_evaluation_*&#96; events and the session's &#96;outcome_evaluations&#96; list. |
| data[].explanation | string | Human-readable explanation of the verdict. For &#96;needs_revision&#96;, describes which criteria failed and why. |
| data[].outcome_evaluation_start_id | string | The id of the corresponding &#96;span.outcome_evaluation_start&#96; event. |
| data[].usage | object | Token usage for a single model request. / Point-in-time snapshot of a session's cumulative usage. |
| data[].model_request_start_id | string | The id of the corresponding &#96;span.model_request_start&#96; event. |
| data[].model_usage | object | Token usage for a single model request. |
| data[].description | string | What the agent should produce. Copied from the input event. |
| data[].max_iterations | null &#124; number | Evaluate-then-revise cycles before giving up. Default 3, max 20. |
| data[].rubric | object | Rubric for grading the quality of an outcome. |
| data[].agent | null &#124; object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| data[].budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| data[].metadata | object | The session's full metadata bag after the update. Present when the update set non-empty metadata; absent when metadata was unchanged or cleared to empty. |
| data[].title | null &#124; string | The session's new title. Present only when the update changed it. |
| next_page | string &#124; null |  |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Server-sent events

**text/event-stream — chunk / 事件对象**

未声明字段结构。

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for the skill.  The format and length of IDs may change over time. |
| data[].created_at | string | ISO 8601 timestamp of when the skill was created. |
| data[].display_name | string | Human-readable, single-line label for the Skill. Maximum 255 characters. Always set: derived from the SKILL.md frontmatter &#96;name&#96; when omitted at creation. Not unique. |
| data[].latest_version_id | string | ID of the newest Skill Version — what &#96;latest&#96; references resolve to. Always set: a Skill holds at least one version. |
| data[].source | object | Where the Skill comes from.  Possible values:  - &#96;"custom"&#96;: authored by the platform user; private to their workspace - &#96;"anthropic"&#96;: published by Anthropic; shared and read-only - &#96;"anthropic_example"&#96;: Anthropic-published sample Skill - &#96;"plugin"&#96;: resolved from an installed plugin |
| data[].type | string | Object type.  For Skills, this is always &#96;"skill"&#96;. |
| data[].updated_at | string | ISO 8601 timestamp of when the skill was last updated. |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**multipart/form-data**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the skill.  The format and length of IDs may change over time. |
| created_at | string | ISO 8601 timestamp of when the skill was created. |
| display_name | string | Human-readable, single-line label for the Skill. Maximum 255 characters. Always set: derived from the SKILL.md frontmatter &#96;name&#96; when omitted at creation. Not unique. |
| latest_version_id | string | ID of the newest Skill Version — what &#96;latest&#96; references resolve to. Always set: a Skill holds at least one version. |
| source | object | Where the Skill comes from.  Possible values:  - &#96;"custom"&#96;: authored by the platform user; private to their workspace - &#96;"anthropic"&#96;: published by Anthropic; shared and read-only - &#96;"anthropic_example"&#96;: Anthropic-published sample Skill - &#96;"plugin"&#96;: resolved from an installed plugin |
| source.type | string | Where the Skill comes from.  Possible values:  - &#96;"custom"&#96;: authored by the platform user; private to their workspace - &#96;"anthropic"&#96;: published by Anthropic; shared and read-only - &#96;"anthropic_example"&#96;: Anthropic-published sample Skill - &#96;"plugin"&#96;: resolved from an installed plugin |
| type | string | Object type.  For Skills, this is always &#96;"skill"&#96;. |
| updated_at | string | ISO 8601 timestamp of when the skill was last updated. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the skill.  The format and length of IDs may change over time. |
| type | string | Deleted object type.  For Skills, this is always &#96;"skill_deleted"&#96;. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the skill.  The format and length of IDs may change over time. |
| created_at | string | ISO 8601 timestamp of when the skill was created. |
| display_name | string | Human-readable, single-line label for the Skill. Maximum 255 characters. Always set: derived from the SKILL.md frontmatter &#96;name&#96; when omitted at creation. Not unique. |
| latest_version_id | string | ID of the newest Skill Version — what &#96;latest&#96; references resolve to. Always set: a Skill holds at least one version. |
| source | object | Where the Skill comes from.  Possible values:  - &#96;"custom"&#96;: authored by the platform user; private to their workspace - &#96;"anthropic"&#96;: published by Anthropic; shared and read-only - &#96;"anthropic_example"&#96;: Anthropic-published sample Skill - &#96;"plugin"&#96;: resolved from an installed plugin |
| source.type | string | Where the Skill comes from.  Possible values:  - &#96;"custom"&#96;: authored by the platform user; private to their workspace - &#96;"anthropic"&#96;: published by Anthropic; shared and read-only - &#96;"anthropic_example"&#96;: Anthropic-published sample Skill - &#96;"plugin"&#96;: resolved from an installed plugin |
| type | string | Object type.  For Skills, this is always &#96;"skill"&#96;. |
| updated_at | string | ISO 8601 timestamp of when the skill was last updated. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for this Skill Version. The id addresses the version in paths and pins it in references. |
| data[].created_at | string | ISO 8601 timestamp of when the skill was created. |
| data[].description | string | Description of the skill version.  This is extracted from the SKILL.md file in the skill upload. |
| data[].name | string | The Skill's immutable kebab-case slug, set at creation from the first upload's SKILL.md frontmatter &#96;name&#96; (or its enclosing directory). Every later upload must resolve to the same value. Also the top-level directory of the Skill's mounted files and the base name of a downloaded archive. |
| data[].skill_id | string | Unique identifier for the skill.  The format and length of IDs may change over time. |
| data[].type | string | Object type.  For Skill Versions, this is always &#96;"skill_version"&#96;. |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**multipart/form-data**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this Skill Version. The id addresses the version in paths and pins it in references. |
| created_at | string | ISO 8601 timestamp of when the skill was created. |
| description | string | Description of the skill version.  This is extracted from the SKILL.md file in the skill upload. |
| name | string | The Skill's immutable kebab-case slug, set at creation from the first upload's SKILL.md frontmatter &#96;name&#96; (or its enclosing directory). Every later upload must resolve to the same value. Also the top-level directory of the Skill's mounted files and the base name of a downloaded archive. |
| skill_id | string | Unique identifier for the skill.  The format and length of IDs may change over time. |
| type | string | Object type.  For Skill Versions, this is always &#96;"skill_version"&#96;. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this Skill Version. The id addresses the version in paths and pins it in references. |
| type | string | Deleted object type.  For Skill Versions, this is always &#96;"skill_version_deleted"&#96;. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this Skill Version. The id addresses the version in paths and pins it in references. |
| created_at | string | ISO 8601 timestamp of when the skill was created. |
| description | string | Description of the skill version.  This is extracted from the SKILL.md file in the skill upload. |
| name | string | The Skill's immutable kebab-case slug, set at creation from the first upload's SKILL.md frontmatter &#96;name&#96; (or its enclosing directory). Every later upload must resolve to the same value. Also the top-level directory of the Skill's mounted files and the base name of a downloaded archive. |
| skill_id | string | Unique identifier for the skill.  The format and length of IDs may change over time. |
| type | string | Object type.  For Skill Versions, this is always &#96;"skill_version"&#96;. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Binary response body

**application/octet-stream**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for the tunnel, prefixed with &#96;tnl_&#96;. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].display_name | null &#124; string | Human-readable name for the tunnel (1-255 characters). Null if unset. |
| data[].domain | string | Anthropic-assigned hostname for the tunnel. MCP server URLs whose host is a subdomain of this value are routed through the tunnel. Globally unique and never reused, even after the tunnel is archived. |
| data[].type | string |  |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the tunnel, prefixed with &#96;tnl_&#96;. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| display_name | null &#124; string | Human-readable name for the tunnel (1-255 characters). Null if unset. |
| domain | string | Anthropic-assigned hostname for the tunnel. MCP server URLs whose host is a subdomain of this value are routed through the tunnel. Globally unique and never reused, even after the tunnel is archived. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the tunnel, prefixed with &#96;tnl_&#96;. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| display_name | null &#124; string | Human-readable name for the tunnel (1-255 characters). Null if unset. |
| domain | string | Anthropic-assigned hostname for the tunnel. MCP server URLs whose host is a subdomain of this value are routed through the tunnel. Globally unique and never reused, even after the tunnel is archived. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the tunnel, prefixed with &#96;tnl_&#96;. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| display_name | null &#124; string | Human-readable name for the tunnel (1-255 characters). Null if unset. |
| domain | string | Anthropic-assigned hostname for the tunnel. MCP server URLs whose host is a subdomain of this value are routed through the tunnel. Globally unique and never reused, even after the tunnel is archived. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for the certificate, prefixed with &#96;tcrt_&#96;. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].expires_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].fingerprint | string | Lowercase hex SHA-256 fingerprint of the certificate's DER encoding. |
| data[].tunnel_id | string | ID of the tunnel the certificate is registered against. |
| data[].type | string |  |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the certificate, prefixed with &#96;tcrt_&#96;. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| expires_at | null &#124; string | A timestamp in RFC 3339 format |
| fingerprint | string | Lowercase hex SHA-256 fingerprint of the certificate's DER encoding. |
| tunnel_id | string | ID of the tunnel the certificate is registered against. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the certificate, prefixed with &#96;tcrt_&#96;. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| expires_at | null &#124; string | A timestamp in RFC 3339 format |
| fingerprint | string | Lowercase hex SHA-256 fingerprint of the certificate's DER encoding. |
| tunnel_id | string | ID of the tunnel the certificate is registered against. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the certificate, prefixed with &#96;tcrt_&#96;. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| expires_at | null &#124; string | A timestamp in RFC 3339 format |
| fingerprint | string | Lowercase hex SHA-256 fingerprint of the certificate's DER encoding. |
| tunnel_id | string | ID of the tunnel the certificate is registered against. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Stable identifier for the current token value. Changes when the token is rotated. |
| tunnel_token | string | The connector token used to run the tunnel. Treat as a credential. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Stable identifier for the current token value. Changes when the token is rotated. |
| tunnel_token | string | The connector token used to run the tunnel. Treat as a credential. |
| type | string |  |

# 列出凭据库

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for the vault. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].display_name | string | Human-readable name for the vault. |
| data[].metadata | object | Arbitrary key-value metadata attached to the vault. |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| next_page | string &#124; null |  |

# 创建凭据库

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the vault. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| display_name | string | Human-readable name for the vault. |
| metadata | object | Arbitrary key-value metadata attached to the vault. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |

# 删除凭据库

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier of the deleted vault. |
| type | string |  |

# 读取凭据库

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the vault. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| display_name | string | Human-readable name for the vault. |
| metadata | object | Arbitrary key-value metadata attached to the vault. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |

# 更新凭据库

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the vault. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| display_name | string | Human-readable name for the vault. |
| metadata | object | Arbitrary key-value metadata attached to the vault. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |

# 归档凭据库

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the vault. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| display_name | string | Human-readable name for the vault. |
| metadata | object | Arbitrary key-value metadata attached to the vault. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; |  |
| data[].id | string | Unique identifier for the credential. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].auth | object | Authentication details for a credential. |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].metadata | object | Arbitrary key-value metadata attached to the credential. |
| data[].type | string |  |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].vault_id | string | Identifier of the vault this credential belongs to. |
| data[].display_name | null &#124; string | Human-readable name for the credential. |
| next_page | string &#124; null |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the credential. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| auth | object | Authentication details for a credential. |
| auth.mcp_server_url | string | URL of the MCP server this credential authenticates against. |
| auth.type | string |  |
| auth.expires_at | null &#124; string | A timestamp in RFC 3339 format |
| auth.refresh | null &#124; object | OAuth refresh token configuration returned in credential responses. |
| auth.injection_location | object | Where in the outbound request the secret value is substituted. |
| auth.networking | object | Outbound hosts the secret value is substituted on. |
| auth.secret_name | string | Name of the environment variable. |
| created_at | string | A timestamp in RFC 3339 format |
| metadata | object | Arbitrary key-value metadata attached to the credential. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_id | string | Identifier of the vault this credential belongs to. |
| display_name | null &#124; string | Human-readable name for the credential. |

## MCP OAuth 创建限制 [#mcp-oauth-创建限制]

上面的示例创建 environment\_variable 凭据。创建 mcp\_oauth 仍返回 501，不会创建凭据；更新已有 mcp\_oauth 凭据也不支持。以下为创建请求的实测错误响应。

```json
{
  "type": "error",
  "error": {
    "type": "not_implemented_error",
    "message": "Not implemented: creating mcp_oauth credentials is not available on this platform yet; use static_bearer or environment_variable."
  },
  "request_id": "4c1dcdba-97bb-46ce-aad0-0a7d8753357c"
}
```

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier of the deleted credential. |
| type | string |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the credential. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| auth | object | Authentication details for a credential. |
| auth.mcp_server_url | string | URL of the MCP server this credential authenticates against. |
| auth.type | string |  |
| auth.expires_at | null &#124; string | A timestamp in RFC 3339 format |
| auth.refresh | null &#124; object | OAuth refresh token configuration returned in credential responses. |
| auth.injection_location | object | Where in the outbound request the secret value is substituted. |
| auth.networking | object | Outbound hosts the secret value is substituted on. |
| auth.secret_name | string | Name of the environment variable. |
| created_at | string | A timestamp in RFC 3339 format |
| metadata | object | Arbitrary key-value metadata attached to the credential. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_id | string | Identifier of the vault this credential belongs to. |
| display_name | null &#124; string | Human-readable name for the credential. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the credential. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| auth | object | Authentication details for a credential. |
| auth.mcp_server_url | string | URL of the MCP server this credential authenticates against. |
| auth.type | string |  |
| auth.expires_at | null &#124; string | A timestamp in RFC 3339 format |
| auth.refresh | null &#124; object | OAuth refresh token configuration returned in credential responses. |
| auth.injection_location | object | Where in the outbound request the secret value is substituted. |
| auth.networking | object | Outbound hosts the secret value is substituted on. |
| auth.secret_name | string | Name of the environment variable. |
| created_at | string | A timestamp in RFC 3339 format |
| metadata | object | Arbitrary key-value metadata attached to the credential. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_id | string | Identifier of the vault this credential belongs to. |
| display_name | null &#124; string | Human-readable name for the credential. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for the credential. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| auth | object | Authentication details for a credential. |
| auth.mcp_server_url | string | URL of the MCP server this credential authenticates against. |
| auth.type | string |  |
| auth.expires_at | null &#124; string | A timestamp in RFC 3339 format |
| auth.refresh | null &#124; object | OAuth refresh token configuration returned in credential responses. |
| auth.injection_location | object | Where in the outbound request the secret value is substituted. |
| auth.networking | object | Outbound hosts the secret value is substituted on. |
| auth.secret_name | string | Name of the environment variable. |
| created_at | string | A timestamp in RFC 3339 format |
| metadata | object | Arbitrary key-value metadata attached to the credential. |
| type | string |  |
| updated_at | string | A timestamp in RFC 3339 format |
| vault_id | string | Identifier of the vault this credential belongs to. |
| display_name | null &#124; string | Human-readable name for the credential. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| credential_id | string | Unique identifier of the credential that was validated. |
| has_refresh_token | boolean | Whether the credential has a refresh token configured. |
| mcp_probe | null &#124; object | The failing step of an MCP validation probe. |
| mcp_probe.http_response | null &#124; object | An HTTP response captured during a credential validation probe. |
| mcp_probe.method | string | The MCP method that failed (for example &#96;initialize&#96; or &#96;tools/list&#96;). |
| refresh | null &#124; object | Outcome of a refresh-token exchange attempted during credential validation. |
| refresh.http_response | null &#124; object | An HTTP response captured during a credential validation probe. |
| refresh.status | string | Outcome of a refresh-token exchange attempted during credential validation.  - &#96;succeeded&#96; - The token endpoint returned a new access token. - &#96;failed&#96; - The token endpoint returned an error response. See &#96;http_response&#96;   for detail. - &#96;connect_error&#96; - The token endpoint could not be reached (DNS, TLS, or   connection error). - &#96;no_refresh_token&#96; - No refresh token is stored for the credential, so no   exchange was attempted. |
| status | string | Overall verdict of a credential validation probe. |
| type | string |  |
| validated_at | string | A timestamp in RFC 3339 format |
| vault_id | string | Identifier of the vault containing the credential. |

## 示例前提 [#示例前提]

此示例针对前面创建的 static 凭据，因此实测返回 400 invalid\_request\_error。要获得校验结果，请先通过[一键授权](/docs/api/native/vault/authorizations)完成用户授权，再将 credential\_id 换成产生的 OAuth Secret ID。校验 OAuth 凭据返回 HTTP 200，状态为 valid、invalid 或 unknown。

# Google Gemini 兼容接口

## 基础地址 [#基础地址]

## 接入 [#接入]

## 可用模型 [#可用模型]

* 路径里的模型名就是平台模型名（如 `gemini-2.5-flash`），可用模型见[列出模型](/docs/api/compatible/google/listModels)。只有声明了 Google 协议的模型可以在这里调用，其他模型返回 404。
* 需要图片输出时，在 `generationConfig.responseModalities` 里带上 `IMAGE`，请求会交给平台的图像模型处理。
* 在思考模型上强制调用工具（`toolConfig` 的 `ANY` 模式）与 Gemini 原生 API 一致，会原样转发给模型：模型接受即执行，不接受时返回 Google 格式的 400 错误。

## 端点 [#端点]

| 方法   | 路径                                                                                                     | 说明       | 支持     |
| ---- | ------------------------------------------------------------------------------------------------------ | -------- | ------ |
| POST | [`/v1beta/models/{modelsId}:generateContent`](/docs/api/compatible/google/generateContent)             | 生成内容     | ● 支持   |
| POST | [`/v1beta/models/{modelsId}:streamGenerateContent`](/docs/api/compatible/google/streamGenerateContent) | 流式生成内容   | ● 支持   |
| POST | [`/v1beta/models/{modelsId}:countTokens`](/docs/api/compatible/google/countTokens)                     | 统计 token | ◐ 部分支持 |
| POST | [`/v1beta/models/{modelsId}:embedContent`](/docs/api/compatible/google/embedContent)                   | 生成向量嵌入   | ● 支持   |
| POST | [`/v1beta/models/{modelsId}:batchEmbedContents`](/docs/api/compatible/google/batchEmbedContents)       | 批量生成向量嵌入 | ● 支持   |
| GET  | [`/v1beta/models`](/docs/api/compatible/google/listModels)                                             | 列出模型     | ● 支持   |
| GET  | [`/v1beta/models/{modelsId}`](/docs/api/compatible/google/getModel)                                    | 读取模型     | ● 支持   |

## 与官方的差异 [#与官方的差异]

* <a href="/docs/api/compatible/google/generateContent">生成内容</a>：toolConfig 的强制工具（functionCallingConfig mode ANY，含 allowedFunctionNames） 在思考模型上同样忠实转发给上游——与 Gemini 原生 API 一致，是否接受由上游模型 决定：如果上游返回 400，错误保持 Google 格式并携带上游的代码与状态。
* <a href="/docs/api/compatible/google/countTokens">统计 token</a>：按模型族校准的估算值（包括中文和工具定义），响应头为 x-praxis-token-count: estimated；不能用作精确用量或计费依据。
* <a href="/docs/api/compatible/google/embedContent">生成向量嵌入</a>：只接受文本部件；图像等多模态部件会被拒绝。taskType、title 以及 autoTruncate / documentOcr / audioTrackExtraction 等检索配置在平台上没有等价语义， 请求携带时会收到 400（INVALID\_ARGUMENT），不会静默忽略——因为不同 taskType 生成的向量行为不同，静默丢弃会悄悄改变检索质量。outputDimensionality 映射为 返回向量的维度。
* <a href="/docs/api/compatible/google/batchEmbedContents">批量生成向量嵌入</a>：requests 中每一项的约束与 embedContent 相同（文本部件、同上拒绝规则）；批量内 所有条目的 outputDimensionality 必须一致。当前官方 JS 与 Python SDK 的 embedContent 调用实际走的就是这个批量端点。
* <a href="/docs/api/compatible/google/listModels">列出模型</a>：向量嵌入模型会以 embedContent 作为其唯一受支持的方法列出。当模型目录 暂时不可用时，generateContent 的行为保持不变：显式要求图像输出 （responseModalities 含 IMAGE）的请求仍走图像通道；未显式声明的旧式图像请求 在该窗口内会按文本对话处理——降级期间每个响应都带 X-Praxis-Route-Degraded: model-catalog-unavailable 头以示区别。

参数与字段的权威定义以 [Gemini API 官方文档](https://ai.google.dev/api)为准。

错误按 Gemini API 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 生成内容

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| candidates | array&lt;object&gt; | Candidate responses from the model. |
| candidates[].avgLogprobs | number | Output only. Average log probability score of the candidate. |
| candidates[].citationMetadata | object | Output only. Citation information for model-generated candidate. This field may be populated with recitation information for any text included in the &#96;content&#96;. These are passages that are "recited" from copyrighted material in the foundational LLM's training data. |
| candidates[].content | object | Output only. Generated content returned from the model. |
| candidates[].finishMessage | string | Optional. Output only. Details the reason why the model stopped generating tokens. This is populated only when &#96;finish_reason&#96; is set. |
| candidates[].finishReason | string | Optional. Output only. The reason why the model stopped generating tokens. If empty, the model has not stopped generating tokens. |
| candidates[].groundingAttributions | array&lt;object&gt; | Output only. Attribution information for sources that contributed to a grounded answer. This field is populated for &#96;GenerateAnswer&#96; calls. |
| candidates[].groundingMetadata | object | Output only. Grounding metadata for the candidate. This field is populated for &#96;GenerateContent&#96; calls. |
| candidates[].index | integer | Output only. Index of the candidate in the list of response candidates. |
| candidates[].logprobsResult | object | Output only. Log-likelihood scores for the response tokens and top tokens |
| candidates[].safetyRatings | array&lt;object&gt; | List of ratings for the safety of a response candidate. There is at most one rating per category. |
| candidates[].tokenCount | integer | Output only. Token count for this candidate. |
| candidates[].urlContextMetadata | object | Output only. Metadata related to url context retrieval tool. |
| modelStatus | object | Output only. The current model status of this model. |
| modelStatus.message | string | A message explaining the model status. |
| modelStatus.modelStage | string | The stage of the underlying model. |
| modelStatus.retirementTime | string | The time at which the model will be retired. |
| modelVersion | string | Output only. The model version used to generate the response. |
| promptFeedback | object | Returns the prompt's feedback related to the content filters. |
| promptFeedback.blockReason | string | Optional. If set, the prompt was blocked and no candidates are returned. Rephrase the prompt. |
| promptFeedback.safetyRatings | array&lt;object&gt; | Ratings for safety of the prompt. There is at most one rating per category. |
| responseId | string | Output only. response_id is used to identify each response. |
| usageMetadata | object | Output only. Metadata on the generation requests' token usage. |
| usageMetadata.cacheTokensDetails | array&lt;object&gt; | Output only. List of modalities of the cached content in the request input. |
| usageMetadata.cachedContentTokenCount | integer | Number of tokens in the cached part of the prompt (the cached content) |
| usageMetadata.candidatesTokenCount | integer | Total number of tokens across all the generated response candidates. |
| usageMetadata.candidatesTokensDetails | array&lt;object&gt; | Output only. List of modalities that were returned in the response. |
| usageMetadata.promptTokenCount | integer | Number of tokens in the prompt. When &#96;cached_content&#96; is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. |
| usageMetadata.promptTokensDetails | array&lt;object&gt; | Output only. List of modalities that were processed in the request input. |
| usageMetadata.serviceTier | string | Output only. Service tier of the request. |
| usageMetadata.thoughtsTokenCount | integer | Output only. Number of tokens of thoughts for thinking models. |
| usageMetadata.toolUsePromptTokenCount | integer | Output only. Number of tokens present in tool-use prompt(s). |
| usageMetadata.toolUsePromptTokensDetails | array&lt;object&gt; | Output only. List of modalities that were processed for tool-use request inputs. |
| usageMetadata.totalTokenCount | integer | Total token count for the generation request (prompt + thoughts + response candidates). |

# 流式生成内容

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| candidates | array&lt;object&gt; | Candidate responses from the model. |
| candidates[].avgLogprobs | number | Output only. Average log probability score of the candidate. |
| candidates[].citationMetadata | object | Output only. Citation information for model-generated candidate. This field may be populated with recitation information for any text included in the &#96;content&#96;. These are passages that are "recited" from copyrighted material in the foundational LLM's training data. |
| candidates[].content | object | Output only. Generated content returned from the model. |
| candidates[].finishMessage | string | Optional. Output only. Details the reason why the model stopped generating tokens. This is populated only when &#96;finish_reason&#96; is set. |
| candidates[].finishReason | string | Optional. Output only. The reason why the model stopped generating tokens. If empty, the model has not stopped generating tokens. |
| candidates[].groundingAttributions | array&lt;object&gt; | Output only. Attribution information for sources that contributed to a grounded answer. This field is populated for &#96;GenerateAnswer&#96; calls. |
| candidates[].groundingMetadata | object | Output only. Grounding metadata for the candidate. This field is populated for &#96;GenerateContent&#96; calls. |
| candidates[].index | integer | Output only. Index of the candidate in the list of response candidates. |
| candidates[].logprobsResult | object | Output only. Log-likelihood scores for the response tokens and top tokens |
| candidates[].safetyRatings | array&lt;object&gt; | List of ratings for the safety of a response candidate. There is at most one rating per category. |
| candidates[].tokenCount | integer | Output only. Token count for this candidate. |
| candidates[].urlContextMetadata | object | Output only. Metadata related to url context retrieval tool. |
| modelStatus | object | Output only. The current model status of this model. |
| modelStatus.message | string | A message explaining the model status. |
| modelStatus.modelStage | string | The stage of the underlying model. |
| modelStatus.retirementTime | string | The time at which the model will be retired. |
| modelVersion | string | Output only. The model version used to generate the response. |
| promptFeedback | object | Returns the prompt's feedback related to the content filters. |
| promptFeedback.blockReason | string | Optional. If set, the prompt was blocked and no candidates are returned. Rephrase the prompt. |
| promptFeedback.safetyRatings | array&lt;object&gt; | Ratings for safety of the prompt. There is at most one rating per category. |
| responseId | string | Output only. response_id is used to identify each response. |
| usageMetadata | object | Output only. Metadata on the generation requests' token usage. |
| usageMetadata.cacheTokensDetails | array&lt;object&gt; | Output only. List of modalities of the cached content in the request input. |
| usageMetadata.cachedContentTokenCount | integer | Number of tokens in the cached part of the prompt (the cached content) |
| usageMetadata.candidatesTokenCount | integer | Total number of tokens across all the generated response candidates. |
| usageMetadata.candidatesTokensDetails | array&lt;object&gt; | Output only. List of modalities that were returned in the response. |
| usageMetadata.promptTokenCount | integer | Number of tokens in the prompt. When &#96;cached_content&#96; is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. |
| usageMetadata.promptTokensDetails | array&lt;object&gt; | Output only. List of modalities that were processed in the request input. |
| usageMetadata.serviceTier | string | Output only. Service tier of the request. |
| usageMetadata.thoughtsTokenCount | integer | Output only. Number of tokens of thoughts for thinking models. |
| usageMetadata.toolUsePromptTokenCount | integer | Output only. Number of tokens present in tool-use prompt(s). |
| usageMetadata.toolUsePromptTokensDetails | array&lt;object&gt; | Output only. List of modalities that were processed for tool-use request inputs. |
| usageMetadata.totalTokenCount | integer | Total token count for the generation request (prompt + thoughts + response candidates). |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| cacheTokensDetails | array&lt;object&gt; | Output only. List of modalities that were processed in the cached content. |
| cacheTokensDetails[].modality | string | The modality associated with this token count. |
| cacheTokensDetails[].tokenCount | integer | Number of tokens. |
| cachedContentTokenCount | integer | Number of tokens in the cached part of the prompt (the cached content). |
| promptTokensDetails | array&lt;object&gt; | Output only. List of modalities that were processed in the request input. |
| promptTokensDetails[].modality | string | The modality associated with this token count. |
| promptTokensDetails[].tokenCount | integer | Number of tokens. |
| totalTokens | integer | The number of tokens that the &#96;Model&#96; tokenizes the &#96;prompt&#96; into. Always non-negative. |

# 生成向量嵌入

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| embedding | object | Output only. The embedding generated from the input content. |
| embedding.shape | array&lt;integer&gt; | This field stores the soft tokens tensor frame shape (e.g. [1, 1, 256, 2048]). |
| embedding.values | array&lt;number&gt; | The embedding values. This is for 3P users only and will not be populated for 1P calls. |
| usageMetadata | object | Output only. The usage metadata for the request. |
| usageMetadata.promptTokenCount | integer | Output only. Number of tokens in the prompt. |
| usageMetadata.promptTokenDetails | array&lt;object&gt; | Output only. List of modalities that were processed in the request input. |

# 批量生成向量嵌入

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| embeddings | array&lt;object&gt; | Output only. The embeddings for each request, in the same order as provided in the batch request. |
| embeddings[].shape | array&lt;integer&gt; | This field stores the soft tokens tensor frame shape (e.g. [1, 1, 256, 2048]). |
| embeddings[].values | array&lt;number&gt; | The embedding values. This is for 3P users only and will not be populated for 1P calls. |
| usageMetadata | object | Output only. The usage metadata for the request. |
| usageMetadata.promptTokenCount | integer | Output only. Number of tokens in the prompt. |
| usageMetadata.promptTokenDetails | array&lt;object&gt; | Output only. List of modalities that were processed in the request input. |

# 列出模型

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| models | array&lt;object&gt; | The returned Models. |
| models[].baseModelId | string | Required. The name of the base model, pass this to the generation request. Examples: * &#96;gemini-1.5-flash&#96; |
| models[].description | string | A short description of the model. |
| models[].displayName | string | The human-readable name of the model. E.g. "Gemini 1.5 Flash". The name can be up to 128 characters long and can consist of any UTF-8 characters. |
| models[].inputTokenLimit | integer | Maximum number of input tokens allowed for this model. |
| models[].maxTemperature | number | The maximum temperature this model can use. |
| models[].name | string | Required. The resource name of the &#96;Model&#96;. Refer to [Model variants](https://ai.google.dev/gemini-api/docs/models/gemini#model-variations) for all allowed values. Format: &#96;models/&#123;model&#125;&#96; with a &#96;&#123;model&#125;&#96; naming convention of: * "&#123;base_model_id&#125;-&#123;version&#125;" Examples: * &#96;models/gemini-1.5-flash-001&#96; |
| models[].outputTokenLimit | integer | Maximum number of output tokens available for this model. |
| models[].supportedGenerationMethods | array&lt;string&gt; | The model's supported generation methods. The corresponding API method names are defined as Pascal case strings, such as &#96;generateMessage&#96; and &#96;generateContent&#96;. |
| models[].temperature | number | Controls the randomness of the output. Values can range over &#96;[0.0,max_temperature]&#96;, inclusive. A higher value will produce responses that are more varied, while a value closer to &#96;0.0&#96; will typically result in less surprising responses from the model. This value specifies default to be used by the backend while making the call to the model. |
| models[].thinking | boolean | Whether the model supports thinking. |
| models[].topK | integer | For Top-k sampling. Top-k sampling considers the set of &#96;top_k&#96; most probable tokens. This value specifies default to be used by the backend while making the call to the model. If empty, indicates the model doesn't use top-k sampling, and &#96;top_k&#96; isn't allowed as a generation parameter. |
| models[].topP | number | For [Nucleus sampling](https://ai.google.dev/gemini-api/docs/prompting-strategies#top-p). Nucleus sampling considers the smallest set of tokens whose probability sum is at least &#96;top_p&#96;. This value specifies default to be used by the backend while making the call to the model. |
| models[].version | string | Required. The version number of the model. This represents the major version (&#96;1.0&#96; or &#96;1.5&#96;) |
| nextPageToken | string | A token, which can be sent as &#96;page_token&#96; to retrieve the next page. If this field is omitted, there are no more pages. |

# 读取模型

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| baseModelId | string | Required. The name of the base model, pass this to the generation request. Examples: * &#96;gemini-1.5-flash&#96; |
| description | string | A short description of the model. |
| displayName | string | The human-readable name of the model. E.g. "Gemini 1.5 Flash". The name can be up to 128 characters long and can consist of any UTF-8 characters. |
| inputTokenLimit | integer | Maximum number of input tokens allowed for this model. |
| maxTemperature | number | The maximum temperature this model can use. |
| name | string | Required. The resource name of the &#96;Model&#96;. Refer to [Model variants](https://ai.google.dev/gemini-api/docs/models/gemini#model-variations) for all allowed values. Format: &#96;models/&#123;model&#125;&#96; with a &#96;&#123;model&#125;&#96; naming convention of: * "&#123;base_model_id&#125;-&#123;version&#125;" Examples: * &#96;models/gemini-1.5-flash-001&#96; |
| outputTokenLimit | integer | Maximum number of output tokens available for this model. |
| supportedGenerationMethods | array&lt;string&gt; | The model's supported generation methods. The corresponding API method names are defined as Pascal case strings, such as &#96;generateMessage&#96; and &#96;generateContent&#96;. |
| temperature | number | Controls the randomness of the output. Values can range over &#96;[0.0,max_temperature]&#96;, inclusive. A higher value will produce responses that are more varied, while a value closer to &#96;0.0&#96; will typically result in less surprising responses from the model. This value specifies default to be used by the backend while making the call to the model. |
| thinking | boolean | Whether the model supports thinking. |
| topK | integer | For Top-k sampling. Top-k sampling considers the set of &#96;top_k&#96; most probable tokens. This value specifies default to be used by the backend while making the call to the model. If empty, indicates the model doesn't use top-k sampling, and &#96;top_k&#96; isn't allowed as a generation parameter. |
| topP | number | For [Nucleus sampling](https://ai.google.dev/gemini-api/docs/prompting-strategies#top-p). Nucleus sampling considers the smallest set of tokens whose probability sum is at least &#96;top_p&#96;. This value specifies default to be used by the backend while making the call to the model. |
| version | string | Required. The version number of the model. This represents the major version (&#96;1.0&#96; or &#96;1.5&#96;) |

# E2B 兼容接口

## 基础地址 [#基础地址]

## 接入 [#接入]

## 控制面与数据面 [#控制面与数据面]

* **控制面**：创建、列出、暂停、连接、终止沙箱等本页列出的端点，地址是上面的基础地址，用你的 API Key 认证（`X-API-Key` 头，官方 SDK 自动带上）。
* **数据面**：在沙箱里运行命令、读写文件，由 SDK 直连 `<端口>-<沙箱 ID>.praxisusercontent.com`，用创建沙箱时返回的访问凭证认证。所以 SDK 除了 `api_url` 还要把 `domain` 设为 `praxisusercontent.com`。

也可以不改代码，只设环境变量：

## 端点 [#端点]

| 方法     | 路径                                                                                | 说明       | 支持   |
| ------ | --------------------------------------------------------------------------------- | -------- | ---- |
| POST   | [`/sandboxes`](/docs/api/compatible/e2b/createSandbox)                            | 创建沙箱     | ● 支持 |
| GET    | [`/sandboxes`](/docs/api/compatible/e2b/listSandboxes)                            | 列出沙箱     | ● 支持 |
| GET    | [`/sandboxes/{sandboxID}`](/docs/api/compatible/e2b/getSandbox)                   | 读取沙箱     | ● 支持 |
| GET    | [`/sandboxes/{sandboxID}/metrics`](/docs/api/compatible/e2b/getSandboxMetrics)    | 沙箱指标     | ● 支持 |
| POST   | [`/sandboxes/{sandboxID}/timeout`](/docs/api/compatible/e2b/setSandboxTimeout)    | 设置超时     | ● 支持 |
| POST   | [`/sandboxes/{sandboxID}/pause`](/docs/api/compatible/e2b/pauseSandbox)           | 暂停沙箱     | ● 支持 |
| POST   | [`/sandboxes/{sandboxID}/connect`](/docs/api/compatible/e2b/connectSandbox)       | 连接沙箱     | ● 支持 |
| DELETE | [`/sandboxes/{sandboxID}`](/docs/api/compatible/e2b/killSandbox)                  | 终止沙箱     | ● 支持 |
| POST   | [`/v2/sandboxes`](/docs/api/compatible/e2b/createSandboxV2)                       | 创建沙箱（v2） | ● 支持 |
| GET    | [`/v2/sandboxes`](/docs/api/compatible/e2b/listSandboxesV2)                       | 列出沙箱（v2） | ● 支持 |
| POST   | [`/v2/sandboxes/{sandboxID}/connect`](/docs/api/compatible/e2b/connectSandboxV2)  | 连接沙箱（v2） | ● 支持 |
| GET    | [`/templates`](/docs/api/compatible/e2b/listTemplates)                            | 列出模板     | ● 支持 |
| GET    | [`/v2/templates`](/docs/api/compatible/e2b/listTemplatesV2)                       | 列出模板（v2） | ● 支持 |
| POST   | [`/volumes`](/docs/api/compatible/e2b/createVolume)                               | 创建卷      | ● 支持 |
| GET    | [`/volumes`](/docs/api/compatible/e2b/listVolumes)                                | 列出卷      | ● 支持 |
| GET    | [`/volumes/{volumeID}`](/docs/api/compatible/e2b/getVolume)                       | 读取卷      | ● 支持 |
| DELETE | [`/volumes/{volumeID}`](/docs/api/compatible/e2b/deleteVolume)                    | 删除卷      | ● 支持 |
| POST   | [`/sandboxes/{sandboxID}/fork`](/docs/api/compatible/e2b/forkSandbox)             | 复制沙箱     | ● 支持 |
| POST   | [`/sandboxes/{sandboxID}/snapshots`](/docs/api/compatible/e2b/createSnapshot)     | 创建快照     | ● 支持 |
| GET    | [`/snapshots`](/docs/api/compatible/e2b/listSnapshots)                            | 列出快照     | ● 支持 |
| DELETE | [`/templates/{templateID}`](/docs/api/compatible/e2b/deleteSnapshot)              | 删除快照     | ● 支持 |
| PUT    | [`/sandboxes/{sandboxID}/network`](/docs/api/compatible/e2b/updateSandboxNetwork) | 更新网络策略   | ● 支持 |
| GET    | [`/v2/sandboxes/{sandboxID}/logs`](/docs/api/compatible/e2b/getSandboxLogs)       | 读取沙箱日志   | ● 支持 |

## 与官方的差异 [#与官方的差异]

* <a href="/docs/api/compatible/e2b/createSandbox">创建沙箱</a>：已弃用：最新官方 SDK 走 v2。平台暂未提供 E2B 默认的 base 模板：不带模板参数的 Sandbox.create() 会返回 404，请显式指定模板（可用模板见「列出模板」）。
* <a href="/docs/api/compatible/e2b/listSandboxes">列出沙箱</a>：已弃用：最新官方 SDK 走 v2。
* <a href="/docs/api/compatible/e2b/connectSandbox">连接沙箱</a>：已弃用：最新官方 SDK 走 v2。
* <a href="/docs/api/compatible/e2b/listTemplates">列出模板</a>：已弃用：最新官方 SDK 走 v2。

参数与字段的权威定义以 [E2B 官方文档](https://docs.e2b.dev/api-reference)为准。

错误按 E2B 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 创建沙箱

## 响应 [#响应]

### HTTP 201 [#http-201]

The sandbox was created successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

# 列出沙箱

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned all running sandboxes

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].templateID | string | Identifier of the template from which is the sandbox created |
| [].alias | string | Alias of the template |
| [].sandboxID | string | Identifier of the sandbox |
| [].clientID | string | Identifier of the client |
| [].startedAt | string | Time when the sandbox was started |
| [].endAt | string | Time when the sandbox will expire |
| [].cpuCount | integer | CPU cores for the sandbox |
| [].memoryMB | integer | Memory for the sandbox in MiB |
| [].diskSizeMB | integer | Disk size for the sandbox in MiB |
| [].metadata | any |  |
| [].state | string | State of the sandbox |
| [].envdVersion | string | Version of the envd running in the sandbox |
| [].volumeMounts | array&lt;object&gt; |  |
| [].volumeMounts[].name | string | Name of the volume |
| [].volumeMounts[].path | string | Path of the volume |

# 读取沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned the sandbox

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| alias | string | Alias of the template |
| sandboxID | string | Identifier of the sandbox |
| clientID | string | Identifier of the client |
| startedAt | string | Time when the sandbox was started |
| endAt | string | Time when the sandbox will expire |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| allowInternetAccess | boolean | Whether internet access was explicitly enabled or disabled for the sandbox. Null means it was not explicitly set. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |
| cpuCount | integer | CPU cores for the sandbox |
| memoryMB | integer | Memory for the sandbox in MiB |
| diskSizeMB | integer | Disk size for the sandbox in MiB |
| metadata | any |  |
| state | string | State of the sandbox |
| network | object |  |
| network.allowPublicTraffic | boolean | Specify if the sandbox URLs should be accessible only with authentication. |
| network.allowOut | array&lt;string&gt; | List of allowed destinations for egress traffic. Each entry can be a CIDR block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com", "*.example.com"). Allowed entries always take precedence over denied entries. |
| network.denyOut | array&lt;string&gt; | List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules. |
| network.egressProxy | object | SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through the proxy after allow/deny filtering; the sandbox is unaware. Domain-matched flows use remote DNS (ATYP=domain). |
| network.maskRequestHost | string | Specify host mask which will be used for all sandbox requests |
| network.httpsPorts | array&lt;integer&gt; | Unlike E2B, network.httpsPorts is rejected; omit it and serve plaintext HTTP inside the sandbox. The public port URL still uses HTTPS. The upstream field denotes HTTPS-speaking internal ports, permits self-signed certificates and excludes envd port 49983. |
| network.rules | object | Per-domain transform rules applied to matching outbound HTTPS requests. Keys may be exact DNS names (for example, "api.example.com") or a leading wildcard (for example, "*.example.com"), and are normalized to lowercase on write. Wildcards match subdomains at any depth but not the apex domain; a bare "*" is invalid. Exact rules take precedence, followed by the longest matching wildcard suffix, and matching rule sets are not merged. Broad wildcards such as "*.com" are allowed and may expose transformed credentials to every matching destination the sandbox contacts. Rules do not grant network access; configure allowOut separately to permit the destination.  |
| lifecycle | object | Sandbox lifecycle policy returned by sandbox info. |
| lifecycle.autoResume | boolean | Whether the sandbox can auto-resume. |
| lifecycle.onTimeout | string | Action taken when the sandbox times out. |
| volumeMounts | array&lt;object&gt; |  |
| volumeMounts[].name | string | Name of the volume |
| volumeMounts[].path | string | Path of the volume |

# 沙箱指标

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned the sandbox metrics

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].timestamp | string | Timestamp of the metric entry |
| [].timestampUnix | integer | Timestamp of the metric entry in Unix time (seconds since epoch) |
| [].cpuCount | integer | Number of CPU cores |
| [].cpuUsedPct | number | CPU usage percentage |
| [].memUsed | integer | Memory used in bytes |
| [].memTotal | integer | Total memory in bytes |
| [].memCache | integer | Cached memory (page cache) in bytes |
| [].diskUsed | integer | Disk used in bytes |
| [].diskTotal | integer | Total disk space in bytes |

# 设置超时

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 204 [#http-204]

Successfully set the sandbox timeout

未声明响应体。

# 暂停沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 204 [#http-204]

The sandbox was paused successfully and can be resumed

未声明响应体。

# 连接沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The sandbox was already running

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

### HTTP 201 [#http-201]

The sandbox was resumed successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

# 终止沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 204 [#http-204]

The sandbox was killed successfully

未声明响应体。

# 创建沙箱（v2）

## 响应 [#响应]

### HTTP 201 [#http-201]

The sandbox was created successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

# 列出沙箱（v2）

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned all running sandboxes

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].templateID | string | Identifier of the template from which is the sandbox created |
| [].alias | string | Alias of the template |
| [].sandboxID | string | Identifier of the sandbox |
| [].clientID | string | Identifier of the client |
| [].startedAt | string | Time when the sandbox was started |
| [].endAt | string | Time when the sandbox will expire |
| [].cpuCount | integer | CPU cores for the sandbox |
| [].memoryMB | integer | Memory for the sandbox in MiB |
| [].diskSizeMB | integer | Disk size for the sandbox in MiB |
| [].metadata | any |  |
| [].state | string | State of the sandbox |
| [].envdVersion | string | Version of the envd running in the sandbox |
| [].volumeMounts | array&lt;object&gt; |  |
| [].volumeMounts[].name | string | Name of the volume |
| [].volumeMounts[].path | string | Path of the volume |

# 连接沙箱（v2）

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The sandbox was already running

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

### HTTP 201 [#http-201]

The sandbox was resumed successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

# 列出模板

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned all templates

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].templateID | string | Identifier of the template |
| [].buildID | string | Identifier of the last successful build for given template |
| [].cpuCount | integer | CPU cores for the sandbox |
| [].memoryMB | integer | Memory for the sandbox in MiB |
| [].diskSizeMB | integer | Disk size for the sandbox in MiB |
| [].public | boolean | Whether the template is public or only accessible by the team |
| [].aliases | array&lt;string&gt; | Aliases of the template |
| [].names | array&lt;string&gt; | Names of the template (namespace/alias format when namespaced) |
| [].createdAt | string | Time when the template was created |
| [].updatedAt | string | Time when the template was last updated |
| [].createdBy | object |  |
| [].createdBy.id | string | Identifier of the user |
| [].createdBy.email | string | Email of the user |
| [].lastSpawnedAt | string | Time when the template was last used |
| [].spawnCount | integer | Number of times the template was used |
| [].buildCount | integer | Number of times the template was built |
| [].envdVersion | string | Version of the envd running in the sandbox |
| [].buildStatus | string | Status of the template build |

# 列出模板（v2）

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned all templates

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].templateID | string | Identifier of the template |
| [].buildID | string | Identifier of the last successful build for given template |
| [].cpuCount | integer | CPU cores for the sandbox |
| [].memoryMB | integer | Memory for the sandbox in MiB |
| [].diskSizeMB | integer | Disk size for the sandbox in MiB |
| [].public | boolean | Whether the template is public or only accessible by the team |
| [].aliases | array&lt;string&gt; | Aliases of the template |
| [].names | array&lt;string&gt; | Names of the template (namespace/alias format when namespaced) |
| [].createdAt | string | Time when the template was created |
| [].updatedAt | string | Time when the template was last updated |
| [].createdBy | object |  |
| [].createdBy.id | string | Identifier of the user |
| [].createdBy.email | string | Email of the user |
| [].lastSpawnedAt | string | Time when the template was last used |
| [].spawnCount | integer | Number of times the template was used |
| [].buildCount | integer | Number of times the template was built |
| [].envdVersion | string | Version of the envd running in the sandbox |
| [].buildStatus | string | Status of the template build |

# 创建卷

## 响应 [#响应]

### HTTP 201 [#http-201]

Successfully created a new team volume

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| volumeID | string | ID of the volume |
| name | string | Name of the volume |
| token | string | Auth token to use for interacting with volume content |
| domain | string | Domain to use as the destination for volume content requests, replacing the default &#96;api.&lt;E2B_DOMAIN&gt;&#96;. Only returned when the team is connected to a custom (BYOC) cluster; absent otherwise, in which case the default domain is used.  |

# 列出卷

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully listed all team volumes

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].volumeID | string | ID of the volume |
| [].name | string | Name of the volume |

# 读取卷

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully retrieved a team volume

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| volumeID | string | ID of the volume |
| name | string | Name of the volume |
| token | string | Auth token to use for interacting with volume content |
| domain | string | Domain to use as the destination for volume content requests, replacing the default &#96;api.&lt;E2B_DOMAIN&gt;&#96;. Only returned when the team is connected to a custom (BYOC) cluster; absent otherwise, in which case the default domain is used.  |

# 删除卷

## 响应 [#响应]

### HTTP 204 [#http-204]

Successfully deleted a team volume

未声明响应体。

# 复制沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 201 [#http-201]

The sandbox was snapshotted and the forks were attempted; each entry reports one fork's outcome

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].sandbox | object |  |
| [].sandbox.templateID | string | Identifier of the template from which is the sandbox created |
| [].sandbox.sandboxID | string | Identifier of the sandbox |
| [].sandbox.alias | string | Alias of the template |
| [].sandbox.clientID | string | Identifier of the client |
| [].sandbox.envdVersion | string | Version of the envd running in the sandbox |
| [].sandbox.envdAccessToken | string | Access token used for envd communication |
| [].sandbox.trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| [].sandbox.domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |
| [].error | object |  |
| [].error.code | integer | Error code |
| [].error.error_code | string | Machine-readable semantic error code. Not a closed set; initial values: sandbox_capacity_unavailable, sandbox_placement_timeout, sandbox_no_compatible_node, sandbox_create_failed, internal_server_error. |
| [].error.message | string | Error |

# 创建快照

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 201 [#http-201]

Snapshot created successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| snapshotID | string | Identifier of the snapshot template including the tag. Uses namespace/alias when a name was provided (e.g. team-slug/my-snapshot:default), otherwise falls back to the raw template ID (e.g. abc123:default). |
| names | array&lt;string&gt; | Full names of the snapshot template including team namespace and tag (e.g. team-slug/my-snapshot:v2) |

# 列出快照

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned snapshots

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].snapshotID | string | Identifier of the snapshot template including the tag. Uses namespace/alias when a name was provided (e.g. team-slug/my-snapshot:default), otherwise falls back to the raw template ID (e.g. abc123:default). |
| [].names | array&lt;string&gt; | Full names of the snapshot template including team namespace and tag (e.g. team-slug/my-snapshot:v2) |

# 删除快照

## 响应 [#响应]

### HTTP 204 [#http-204]

The template was deleted successfully

未声明响应体。

# 更新网络策略

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 204 [#http-204]

Successfully updated the sandbox network configuration

未声明响应体。

# 读取沙箱日志

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned the sandbox logs

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| logs | array&lt;object&gt; | Sandbox logs structured |
| logs[].timestamp | string | Timestamp of the log entry |
| logs[].message | string | Log message content |
| logs[].level | string | State of the sandbox |
| logs[].fields | object |  |

# Tavily 兼容接口

## 基础地址 [#基础地址]

## 接入 [#接入]

## 端点 [#端点]

| 方法   | 路径                                                  | 说明     | 支持   |
| ---- | --------------------------------------------------- | ------ | ---- |
| POST | [`/search`](/docs/api/compatible/tavily/search)     | 搜索     | ● 支持 |
| POST | [`/extract`](/docs/api/compatible/tavily/extract)   | 提取网页内容 | ● 支持 |
| POST | [`/crawl`](/docs/api/compatible/tavily/crawl)       | 站内爬取   | ● 支持 |
| POST | [`/map`](/docs/api/compatible/tavily/map)           | 站点地图   | ● 支持 |
| POST | [`/feedback`](/docs/api/compatible/tavily/feedback) | 提交反馈   | ● 支持 |

## 与官方的差异 [#与官方的差异]

* <a href="/docs/api/compatible/tavily/crawl">站内爬取</a>：调用前要求账户余额大于 0；按 Tavily 返回的 usage.credits 计费，每 credit $0.01；Tavily 未返回用量时，按本次请求可能消耗的上限计费。
* <a href="/docs/api/compatible/tavily/map">站点地图</a>：调用前要求账户余额大于 0；按 Tavily 返回的 usage.credits 计费，每 credit $0.01；Tavily 未返回用量时，按本次请求可能消耗的上限计费。
* <a href="/docs/api/compatible/tavily/feedback">提交反馈</a>：原样转发给 Tavily，不计费（Tavily 官方定价未对反馈单独计费）。

参数与字段的权威定义以 [Tavily 官方文档](https://docs.tavily.com/documentation/api-reference)为准。

错误按 Tavily 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 搜索

## 响应 [#响应]

### HTTP 200 [#http-200]

Search results returned successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| query | string | The search query that was executed. |
| answer | string | A short answer to the user's query, generated by an LLM. Included in the response only if &#96;include_answer&#96; is requested (i.e., set to &#96;true&#96;, &#96;basic&#96;, or &#96;advanced&#96;) |
| images | array&lt;object&gt; | A list of query-related images from image search. If &#96;include_image_descriptions&#96; is true, each item will have &#96;url&#96; and &#96;description&#96;. Note: per-result images are also returned inside each result object's &#96;images&#96; field. |
| images[].url | string |  |
| images[].description | string |  |
| results | array&lt;object&gt; | A list of sorted search results, ranked by relevancy. |
| results[].title | string | The title of the search result. |
| results[].url | string | The URL of the search result. |
| results[].content | string | A short description of the search result. |
| results[].score | number | The relevance score of the search result. |
| results[].raw_content | string | The cleaned and parsed HTML content of the search result. Only if &#96;include_raw_content&#96; is true. |
| results[].published_date | string | Tavily's best estimate of when the source was published or last updated. Can be later than the original publish date. &#96;null&#96; if no date could be detected. Only returned when &#96;include_published_date&#96; is &#96;true&#96; (automatically enabled when &#96;topic&#96; is &#96;news&#96;). |
| results[].favicon | string | The favicon URL for the result. |
| results[].images | array&lt;object&gt; | A list of images extracted from this search result. Only included when &#96;include_images&#96; is &#96;true&#96;. If &#96;include_image_descriptions&#96; is &#96;true&#96;, each item will have &#96;url&#96; and &#96;description&#96;. |
| results[].id | string | Unique identifier for this result |
| auto_parameters | object | A dictionary of the selected auto_parameters, only shown when &#96;auto_parameters&#96; is true. |
| response_time | number | Time in seconds it took to complete the request. |
| usage | object | Credit usage details for the request. |
| request_id | string | A unique request identifier you can share with customer support to help resolve issues with specific requests. |

# 提取网页内容

## 响应 [#响应]

### HTTP 200 [#http-200]

Extraction completed. Check results and failed\_results for each URL. HTTP 200 can have an empty results array when all valid URLs fail during extraction; output order is not guaranteed.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| results | array&lt;object&gt; | A list of extracted content from the provided URLs. |
| results[].url | string | The URL from which the content was extracted. |
| results[].raw_content | string | The full content extracted from the page. When &#96;query&#96; is provided, contains the top-ranked chunks joined by &#96;[...]&#96; separator. |
| results[].images | array&lt;string&gt; | This is only available if &#96;include_images&#96; is set to &#96;true&#96;. A list of image URLs extracted from the page. |
| results[].favicon | string | The favicon URL for the result. |
| failed_results | array&lt;object&gt; | A list of URLs that could not be processed. |
| failed_results[].url | string | The URL that failed to be processed. |
| failed_results[].error | string | An error message describing why the URL couldn't be processed. |
| response_time | number | Time in seconds it took to complete the request. |
| usage | object | Credit usage details for the request. |
| request_id | string | A unique request identifier you can share with customer support to help resolve issues with specific requests. |

# 站内爬取

## 响应 [#响应]

### HTTP 200 [#http-200]

Crawl results returned successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| base_url | string | The base URL that was crawled. |
| results | array&lt;object&gt; | A list of extracted content from the crawled URLs. |
| results[].url | string | The URL that was crawled. |
| results[].raw_content | string | The full content extracted from the page. When &#96;query&#96; is provided, contains the top-ranked chunks joined by &#96;[...]&#96; separator. |
| results[].favicon | string | The favicon URL for the result. |
| response_time | number | Time in seconds it took to complete the request. |
| usage | object | Credit usage details for the request. |
| request_id | string | A unique request identifier you can share with customer support to help resolve issues with specific requests. |

# 站点地图

## 响应 [#响应]

### HTTP 200 [#http-200]

Map results returned successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| base_url | string | The base URL that was mapped. |
| results | array&lt;string&gt; | A list of URLs that were discovered during the mapping. |
| response_time | number | Time in seconds it took to complete the request. |
| usage | object | Credit usage details for the request. |
| request_id | string | A unique request identifier you can share with customer support to help resolve issues with specific requests. |

# 提交反馈

## 响应 [#响应]

### HTTP 200 [#http-200]

Feedback accepted

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Whether the feedback was accepted. |
| feedback_id | string | Unique identifier of this feedback submission. |
| response_time | number | Response time of this feedback request in seconds. |

# Supabase 兼容接口

（待译）

Database exposes its row API through Supabase client paths. Use a base URL ending in /supabase/\<database\_id>/, including the trailing slash, and a Praxis credential. Unlike Supabase, storage uses SQLite; define tables and fields through /database/v1, not SQL migrations, and do not expect Supabase Auth, RLS policies or realtime subscriptions. Auth, storage, realtime, functions and graphql service paths return 501 with x-should-retry=false. See the Database domain for supported concepts and differences.

使用官方 supabase-js 读写一个库中的表。

[指南 →](/docs/cloud/services/database/quickstart)

## 基础地址 [#基础地址]

`https://api.deepraxis.ai/supabase/{database_id}/`

| 部分 | 含义 |
| --- | --- |
| &#123;database_id&#125; | 建库返回的 ID；每个库使用自己的地址。 |
| / | 保留末尾斜杠，supabase-js 才会保留库 ID 并追加 rest/v1。 |

API Key 用作 Authorization: Bearer 凭据；supabase-js 的第二个参数传同一 Key。以下示例在服务端运行。

```typescript
import { createClient } from "@supabase/supabase-js";

const supabase = createClient(
  `https://api.deepraxis.ai/supabase/${process.env.DATABASE_ID}/`,
  process.env.PRAXIS_API_KEY,
  { auth: { persistSession: false, autoRefreshToken: false } },
);
```

## 表端点 [#表端点]

[GET / HEAD / POST / PATCH / DELETE](/docs/api/compatible/supabase/tables)

`/supabase/{database_id}/rest/v1/{table}`

仅提供下列 PostgREST 子集。不支持的语法返回 HTTP 400，code 为 PGRST127；无效或未知参数可能返回 PGRST100。

## 过滤运算符 [#过滤运算符]

| 值 | 支持情况 |
| --- | --- |
| `eq` | 支持 |
| `neq` | 支持 |
| `gt` | 支持 |
| `gte` | 支持 |
| `lt` | 支持 |
| `lte` | 支持 |
| `like` | 支持 |
| `ilike` | 支持 |
| `in` | 支持 |
| `is` | 支持 |
| `cs` | 支持 |
| `cd` | 支持 |
| `ov` | 支持 |
| `fts` | 不支持 |
| `plfts` | 不支持 |
| `phfts` | 不支持 |
| `wfts` | 不支持 |
| `match` | 不支持 |
| `imatch` | 不支持 |
| `isdistinct` | 不支持 |
| `sl` | 不支持 |
| `sr` | 不支持 |
| `nxl` | 不支持 |
| `nxr` | 不支持 |
| `adj` | 不支持 |

## Prefer [#prefer]

| 值 | 支持情况 |
| --- | --- |
| `return=minimal` | 支持 |
| `return=headers-only` | 支持 |
| `return=representation` | 支持 |
| `count=exact` | 支持 |
| `count=planned` | 部分支持 |
| `count=estimated` | 部分支持 |
| `resolution=merge-duplicates` | 支持 |
| `resolution=ignore-duplicates` | 支持 |
| `missing=default` | 部分支持 |
| `handling=strict` | 支持 |
| `handling=lenient` | 支持 |

## Accept [#accept]

| 值 | 支持情况 |
| --- | --- |
| `application/json` | 支持 |
| `*/*` | 支持 |
| `application/vnd.pgrst.object+json` | 支持 |
| `text/csv` | 不支持 |
| `application/geo+json` | 不支持 |
| `application/vnd.pgrst.plan*` | 不支持 |

## 查询语法 [#查询语法]

| 值 | 支持情况 |
| --- | --- |
| `not` | 支持 |
| `and/or/not.and/not.or` | 支持 |
| `JSON paths (->, ->>)` | 支持 |
| `aliases` | 支持 |
| `link embedding` | 支持 |
| `!field hint` | 支持 |
| `embedded filters/order/pagination` | 不支持 |
| `casts (::)` | 不支持 |
| `aggregates` | 不支持 |
| `spread (...)` | 不支持 |
| `!inner/!left` | 不支持 |
| `operator(any)/operator(all)` | 不支持 |

planned/estimated 当前返回精确计数；字段可以配置 default：批量插入中有的行提供、有的行缺失的列，带 missing=default 时缺失处取字段 default，否则按 PostgREST 写 null；所有行都未提供的列始终取 default（没有 default 时为 null）。cs/cd/ov 接收数组（`{a,b}` 或 `["a"]`）；json 字段上的 cs/cd 还接受 JSON 对象，按 jsonb 包含判断，例如 `meta=cs.{"color":"red"}`（键值逐层包含）；cs 还接受 JSON 标量，数组顶层含该元素即匹配，例如 `meta=cs."a"`。`cs.{}`/`cd.{}` 在 json 字段上是空对象，在数组字段上是空数组。一次 DELETE 删除的行之间互相引用不阻断删除，只要有引用者不在本次删除中就返回 409 23503。like/ilike 只适用于 string 字段与 `->>` 文本路径，用在其他类型返回 400 42883。字符串按二进制序（区分大小写，大写在小写前）比较与排序，不支持按 lower() 排序；需要不区分大小写排序时，另存一个小写字段并按它排序。GET/HEAD 带 If-None-Match 且与当前 ETag 匹配时返回 304、无正文。不支持的 Accept 返回 406 PGRST107。upsert 仅接受 id 或单个 unique 字段。

Prefer 中的未知值默认忽略；handling=strict 时返回 400 PGRST122。单对象 Accept 恰好匹配一行时返回对象，否则返回 406 PGRST116。 其他不支持的 Accept 返回 406 PGRST107。

## 未开放服务 [#未开放服务]

| 路径 | HTTP | code |
| --- | --- | --- |
| /supabase/&#123;database_id&#125;/auth/v1/&#123;+path&#125; | 501 | not_implemented |
| /supabase/&#123;database_id&#125;/storage/v1/&#123;+path&#125; | 501 | not_implemented |
| /supabase/&#123;database_id&#125;/realtime/v1/&#123;+path&#125; | 501 | not_implemented |
| /supabase/&#123;database_id&#125;/functions/v1/&#123;+path&#125; | 501 | not_implemented |
| /supabase/&#123;database_id&#125;/graphql/v1/&#123;+path&#125; | 501 | not_implemented |

这些服务返回 x-should-retry: false。它们的错误体与表端点不同，只有 code 和 message。

[错误码表与错误体](/docs/api/native/database/errors)

# 读写行

[指南 →](/docs/cloud/services/database/quickstart)

`/supabase/{database_id}/rest/v1/{table}`

与同一库的其它入口读写相同的行；错误使用 PostgREST code。

[支持矩阵与初始化](/docs/api/compatible/supabase)

## 参数与请求头 [#参数与请求头]

| 名称 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |
| table | path | 表 ID 或名称。 |
| select | query | 列名列表；支持 *、别名、JSON 路径及 link 关联展开。不支持类型转换、聚合、展开运算和连接修饰。 |
| &#123;column&#125; | query | 把 &#123;column&#125; 换为字段名或 JSON 路径，例如 title=eq.summary；不同列的条件同时生效。 |
| and | query | 括号内的条件全部成立，例如 (done.eq.false,title.neq.draft)。 |
| or | query | 括号内任一条件成立。 |
| not.and | query | 否定全部条件成立。 |
| not.or | query | 否定任一条件成立。 |
| order | query | 逗号分隔的字段，可带 asc/desc、nullsfirst/nullslast；支持 JSON 路径。 |
| limit | query | 最多返回的条数。 |
| offset | query | 跳过的行数。 |
| on_conflict | query | upsert 的冲突键：id 或单个 unique 字段；配合 Prefer 的 resolution。 |
| columns | query | 写入列的逗号分隔列表；列表之外的输入键被忽略。 |
| Range | header | GET/HEAD 的闭区间，例如 0-9；与 limit/offset 取交集。 |
| Range-Unit | header | items；其它单位使 Range 被忽略。 |
| Prefer | header | 逗号分隔的偏好。未知值默认被忽略；handling=strict 时返回 400 PGRST122。 |
| Accept | header | application/json、*/* 或 application/vnd.pgrst.object+json；单对象模式必须恰好匹配一行，否则返回 406 PGRST116。其他媒体类型返回 406 PGRST107；text/csv、application/geo+json 与 application/vnd.pgrst.plan 返回 400 PGRST127。 |
| If-None-Match | header | 上次 GET/HEAD 返回的 ETag（弱比较）；与当前 ETag 匹配时返回 304，无正文。 |

POST 接受单个对象或对象数组；PATCH 接受对象。系统列由服务管理。写入默认不返回正文，使用 Prefer: return=representation（SDK 的 .select()）返回行。PATCH 和 DELETE 只影响匹配过滤器的行；省略过滤器会影响全部匹配行。

| 响应头 | 说明 |
| --- | --- |
| Content-Range | 本次行范围/总数；未请求计数时总数为 *。 |
| Preference-Applied | 已应用的偏好。 |
| ETag | GET/HEAD 返回的版本标记；请求带 If-None-Match 且与之匹配时返回 304、无正文。 |
| Location | POST 使用 return=headers-only 时的新行地址。 |

读取通常为 200；请求计数且只返回部分行时为 206。POST 为 201。PATCH/DELETE 使用 representation 时为 200，否则为 204。HEAD 没有正文。If-None-Match 与当前 ETag 匹配时返回 304。datetime 值统一按 UTC、3 位毫秒保存和读出（如 2026-10-11T00:30:00.000Z），精度为毫秒，超过 3 位的小数秒四舍五入。

## 查询行 [#查询行]

`GET /supabase/{database_id}/rest/v1/{table}`

```typescript
const { data, error } = await supabase.from("tasks").select("*").order("title").limit(10);
if (error) throw error;
console.log(data);
```

### 响应 [#响应]

#### HTTP 200 [#http-200]

Success; write bodies require Prefer: return=representation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string |  |
| [].version | integer |  |
| [].created_at | string |  |
| [].updated_at | string |  |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| version | integer |  |
| created_at | string |  |
| updated_at | string |  |

#### HTTP 206 [#http-206]

Partial range with requested count

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string |  |
| [].version | integer |  |
| [].created_at | string |  |
| [].updated_at | string |  |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| version | integer |  |
| created_at | string |  |
| updated_at | string |  |

响应示例 — HTTP 200

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| etag | W/"5.1" |
| range-unit | items |

```json
[
  {
    "id": "rec_e88fcbd357aa49c9",
    "version": 1,
    "created_at": "2026-10-11T17:42:00.094Z",
    "updated_at": "2026-10-11T17:42:00.094Z",
    "title": "Write a summary",
    "done": false
  }
]
```

## 统计行 [#统计行]

`HEAD /supabase/{database_id}/rest/v1/{table}`

```typescript
const { data, error, count } = await supabase.from("tasks").select("*", { head: true, count: "exact" });
if (error) throw error;
console.log(count);
```

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Success; write bodies require Prefer: return=representation

未声明响应体。

#### HTTP 206 [#http-206-1]

Partial range with requested count

未声明响应体。

响应示例 — HTTP 200

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/1 |
| preference-applied | count=exact |
| etag | W/"5.1" |
| range-unit | items |

无响应正文。

## 插入行 [#插入行]

`POST /supabase/{database_id}/rest/v1/{table}`

```typescript
const { data, error } = await supabase.from("tasks").insert({"title":"Write a summary","done":false}).select();
if (error) throw error;
console.log(data);
```

### 响应 [#响应-2]

#### HTTP 201 [#http-201]

Success; write bodies require Prefer: return=representation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string |  |
| [].version | integer |  |
| [].created_at | string |  |
| [].updated_at | string |  |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| version | integer |  |
| created_at | string |  |
| updated_at | string |  |

响应示例 — HTTP 201

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| preference-applied | return=representation |
| range-unit | items |

```json
[
  {
    "id": "rec_e88fcbd357aa49c9",
    "version": 1,
    "created_at": "2026-10-11T17:42:00.094Z",
    "updated_at": "2026-10-11T17:42:00.094Z",
    "title": "Write a summary",
    "done": false
  }
]
```

## 更新行 [#更新行]

`PATCH /supabase/{database_id}/rest/v1/{table}`

```typescript
const { data, error } = await supabase.from("tasks").update({ done: true }).eq("title", "Write a summary").select();
if (error) throw error;
console.log(data);
```

### 响应 [#响应-3]

#### HTTP 200 [#http-200-2]

Success; write bodies require Prefer: return=representation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string |  |
| [].version | integer |  |
| [].created_at | string |  |
| [].updated_at | string |  |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| version | integer |  |
| created_at | string |  |
| updated_at | string |  |

#### HTTP 204 [#http-204]

Success without a body

未声明响应体。

响应示例 — HTTP 200

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| preference-applied | return=representation |
| range-unit | items |

```json
[
  {
    "id": "rec_e88fcbd357aa49c9",
    "version": 2,
    "created_at": "2026-10-11T17:42:00.094Z",
    "updated_at": "2026-10-11T17:42:01.047Z",
    "title": "Write a summary",
    "done": true
  }
]
```

## 合并行 [#合并行]

`POST /supabase/{database_id}/rest/v1/{table}`

```typescript
const { data, error } = await supabase.from("tasks").upsert({"title":"Write a summary","done":true}, { onConflict: "title" }).select();
if (error) throw error;
console.log(data);
```

### 响应 [#响应-4]

#### HTTP 201 [#http-201-1]

Success; write bodies require Prefer: return=representation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string |  |
| [].version | integer |  |
| [].created_at | string |  |
| [].updated_at | string |  |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| version | integer |  |
| created_at | string |  |
| updated_at | string |  |

响应示例 — HTTP 201

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| preference-applied | resolution=merge-duplicates, return=representation |
| range-unit | items |

```json
[
  {
    "id": "rec_e88fcbd357aa49c9",
    "version": 3,
    "created_at": "2026-10-11T17:42:00.094Z",
    "updated_at": "2026-10-11T17:42:01.735Z",
    "title": "Write a summary",
    "done": true
  }
]
```

## 删除行 [#删除行]

`DELETE /supabase/{database_id}/rest/v1/{table}`

```typescript
const { data, error } = await supabase.from("tasks").delete().eq("title", "Write a summary").select();
if (error) throw error;
console.log(data);
```

### 响应 [#响应-5]

#### HTTP 200 [#http-200-3]

Success; write bodies require Prefer: return=representation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string |  |
| [].version | integer |  |
| [].created_at | string |  |
| [].updated_at | string |  |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| version | integer |  |
| created_at | string |  |
| updated_at | string |  |

#### HTTP 204 [#http-204-1]

Success without a body

未声明响应体。

响应示例 — HTTP 200

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| preference-applied | return=representation |
| range-unit | items |

```json
[
  {
    "id": "rec_e88fcbd357aa49c9",
    "version": 3,
    "created_at": "2026-10-11T17:42:00.094Z",
    "updated_at": "2026-10-11T17:42:01.735Z",
    "title": "Write a summary",
    "done": true
  }
]
```

# Cloudinary 兼容接口

用官方 Cloudinary SDK 管理一个素材库。只需以下三项配置；API Key 作为 Bearer 凭据发送。

[指南 →](/docs/cloud/services/media/quickstart)

`https://api.deepraxis.ai/cloudinary/v1_1/{library_id}`

| 配置 | 值 |
| --- | --- |
| cloud_name | library_id |
| oauth_token | API Key |
| upload_prefix | https://api.deepraxis.ai/cloudinary |

## Node.js [#nodejs]

```bash
npm install cloudinary@2
```

```javascript
import { v2 as cloudinary } from "cloudinary";

cloudinary.config({
  cloud_name: process.env.LIBRARY_ID,
  oauth_token: process.env.PRAXIS_API_KEY,
  upload_prefix: "https://api.deepraxis.ai/cloudinary",
});
```

## Python [#python]

```bash
python -m pip install cloudinary
```

```python
import os
import cloudinary
import cloudinary.uploader
import cloudinary.api

cloudinary.config(
    cloud_name=os.environ["LIBRARY_ID"],
    oauth_token=os.environ["PRAXIS_API_KEY"],
    upload_prefix="https://api.deepraxis.ai/cloudinary",
)
```

## 支持矩阵 [#支持矩阵]

| 操作 | 支持 |
| --- | --- |
| GET /v1_1/&#123;library_id&#125;/resources/visual_search | 支持 |
| POST /v1_1/&#123;library_id&#125;/resources/visual_search | 支持 |
| POST /v1_1/&#123;library_id&#125;/&#123;resource_type&#125;/upload | 支持 |
| POST /v1_1/&#123;library_id&#125;/&#123;resource_type&#125;/destroy | 支持 |
| POST /v1_1/&#123;library_id&#125;/&#123;resource_type&#125;/rename | 支持 |
| POST /v1_1/&#123;library_id&#125;/&#123;resource_type&#125;/tags | 支持 |
| POST /v1_1/&#123;library_id&#125;/&#123;resource_type&#125;/context | 支持 |
| POST /v1_1/&#123;library_id&#125;/&#123;resource_type&#125;/explicit | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/search | 支持 |
| POST /v1_1/&#123;library_id&#125;/resources/search | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125; | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125;/upload | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/&#123;asset_id&#125; | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/by_asset_ids | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/by_asset_folder | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125;/tags/&#123;tag&#125; | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125;/context | 支持 |
| GET /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125;/upload/&#123;public_id&#125; | 支持 |
| POST /v1_1/&#123;library_id&#125;/resources/by_asset_ids | 支持 |
| POST /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125;/upload/&#123;public_id&#125; | 支持 |
| PUT /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125;/upload/&#123;public_id&#125; | 支持 |
| DELETE /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125;/upload | 支持 |
| DELETE /v1_1/&#123;library_id&#125;/resources/&#123;resource_type&#125;/tags/&#123;tag&#125; | 支持 |
| GET /v1_1/&#123;library_id&#125;/tags/&#123;resource_type&#125; | 支持 |
| GET /v1_1/&#123;library_id&#125;/folders | 支持 |
| GET /v1_1/&#123;library_id&#125;/folders/&#123;folder&#125; | 支持 |
| POST /v1_1/&#123;library_id&#125;/folders/&#123;folder&#125; | 支持 |
| PUT /v1_1/&#123;library_id&#125;/folders/&#123;folder&#125; | 支持 |
| DELETE /v1_1/&#123;library_id&#125;/folders/&#123;folder&#125; | 支持 |
| GET /v1_1/&#123;library_id&#125;/ping | 支持 |
| GET /v1_1/&#123;library_id&#125;/usage | 部分支持 |
| GET /v1_1/&#123;library_id&#125;/usage/&#123;date&#125; | 部分支持 |

usage 只返回当前存储字节数与素材数，日期不选择历史统计。

## 不支持的操作 [#不支持的操作]

| 端点 | HTTP |
| --- | --- |
| upload_presets | 400 |
| metadata_fields | 400 |
| transformations | 400 |
| streaming_profiles | 400 |
| upload_mappings | 400 |
| triggers | 400 |
| derived_resources | 400 |
| relations | 400 |
| restore | 400 |
| backups | 400 |
| text | 400 |
| sprite | 400 |
| multi | 400 |
| explode | 400 |
| generate_archive | 400 |
| create_slideshow | 400 |
| download_backup_asset | 400 |
| folders/search | 400 |

上述端点错误消息含 is not supported；private 与 authenticated 交付类型也返回 400。

## 上传参数 [#上传参数]

| 参数 | 支持 |
| --- | --- |
| file | 支持 |
| public_id | 支持 |
| public_id_prefix | 支持 |
| display_name | 支持 |
| asset_folder | 支持 |
| use_filename | 支持 |
| unique_filename | 支持 |
| use_filename_as_display_name | 支持 |
| filename_override | 支持 |
| overwrite | 支持 |
| tags | 支持 |
| context | 支持 |
| auto_tagging | 部分支持 |
| resource_type | 支持 |
| eager | 不支持 |
| eager_async | 不支持 |
| eager_notification_url | 不支持 |
| async | 不支持 |
| notification_url | 不支持 |
| upload_preset | 不支持 |
| moderation | 不支持 |
| detection | 不支持 |
| ocr | 不支持 |
| raw_convert | 不支持 |
| background_removal | 不支持 |
| categorization | 不支持 |
| transformation | 不支持 |
| responsive_breakpoints | 不支持 |
| proxy | 不支持 |
| backup | 不支持 |
| return_delete_token | 不支持 |
| access_control | 不支持 |
| access_mode | 不支持 |
| metadata | 不支持 |
| face_coordinates | 不支持 |
| custom_coordinates | 不支持 |
| regions | 不支持 |
| quality_analysis | 不支持 |
| accessibility_analysis | 不支持 |
| cinemagraph_analysis | 不支持 |
| media_metadata | 不支持 |
| phash | 不支持 |
| colors | 不支持 |
| faces | 不支持 |
| image_metadata | 不支持 |
| exif | 不支持 |
| invalidate | 不支持 |
| type | 不支持 |

不支持的上传参数返回 400，消息为 Unsupported upload parameter: 参数名。

[错误体与错误码](/docs/api/native/media/errors)

# 上传与管理

官方 SDK 的 `upload("file_…")` 会把字符串当作本地路径。从文件导入请使用自有接口 `POST /media/v1/libraries/{library_id}/assets/import`，见[导入文件](/docs/api/native/media/assets#导入文件)。

[指南 →](/docs/cloud/services/media/quickstart)

上传接受文件字节、HTTPS URL 或 data URI。音频使用 video，自动识别使用 auto。SDK 的 upload\_large 将分片发送到同一 upload 端点。

tags 可写成逗号分隔字符串、数组或多个 tags 字段（-F tags=a -F tags=b），三者等价；逗号分隔时每项去首尾空白并丢弃空项。0 字节文件返回 FILE\_EMPTY；读不出宽高的图片返回 Invalid image file；其他任意文件作为 raw 接受。

```javascript
await new Promise((resolve, reject) => {
  cloudinary.uploader.upload_large("./video.mp4", {
    resource_type: "video",
    chunk_size: 20 * 1024 * 1024,
  }, (error, result) => error ? reject(error) : resolve(result));
});
```

每片共享 X-Unique-Upload-Id。Content-Range 为 bytes 起点-终点/总字节数；未知总数用 -1，末片给最终大小。非末片至少 5 MiB 且等长。会话有效期 24 小时。中间片返回 done=false 与 upload\_id；末片返回素材和 done=true。

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/compatible/cloudinary)

## 上传素材 [#上传素材]

`POST /cloudinary/v1_1/{library_id}/{resource_type}/upload`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw / auto | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| X-Unique-Upload-Id | header | string | — |
| Content-Range | header | string | — |

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| file | string / string | 是 | 文件字节、HTTPS URL、data URI 或同账户 file_… |
| public_id | string | 否 | 交付地址中的素材名称，可带路径 |
| public_id_prefix | string | 否 | public_id 的路径前缀；末尾的 / 可有可无，前缀与 ID 之间只保留一个 / |
| display_name | string | 否 | 显示名称 |
| asset_folder | string | 否 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| use_filename | boolean | 否 | 用文件名生成 public_id |
| unique_filename | boolean | 否 | 自动附加唯一后缀 |
| use_filename_as_display_name | boolean | 否 | 用文件名作为显示名称 |
| filename_override | string | 否 | 覆盖原文件名称 |
| overwrite | boolean | 否 | 是否覆盖同名素材 |
| tags | string / string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | string / object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| auto_tagging | number | 否 | 理解后将达到阈值的标签合并；0–1 |
| resource_type | ResourceType / "auto" | 否 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |

返回: `CloudinaryResource`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string |  |
| public_id | string |  |
| display_name | string |  |
| asset_folder | string |  |
| resource_type | string |  |
| type | string |  |
| format | string |  |
| version | number |  |
| version_id | string |  |
| bytes | number |  |
| etag | string |  |
| width | number |  |
| height | number |  |
| duration | number |  |
| pages | number |  |
| is_audio | boolean |  |
| original_filename | string |  |
| tags | array&lt;string&gt; |  |
| context | object |  |
| context.custom | object |  |
| created_at | string |  |
| url | string |  |
| secure_url | string |  |
| placeholder | boolean |  |
| existing | boolean |  |
| processing | object |  |
| processing.state | string |  |
| processing.kinds | object |  |
| processing.updated_at | string |  |
| done | boolean |  |
| upload_id | string |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/image/upload" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"file":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==","public_id":"walk-lib-r1-MDP-1791733789929-plain","tags":["docs"]}'
```

HTTP 200

```json
{
  "asset_id": "85b7ef616a8b4719a41777a036ebc1d2",
  "public_id": "walk-lib-r1-MDP-1791733789929-plain",
  "display_name": "walk-lib-r1-MDP-1791733789929-plain",
  "asset_folder": "",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791733810,
  "version_id": "fdf3c8cd40c2424d86e8397425a69857",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "created_at": "2026-10-11T15:50:10.842Z",
  "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
  "placeholder": false
}
```

## 删除素材 [#删除素材]

`POST /cloudinary/v1_1/{library_id}/{resource_type}/destroy`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw / auto | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |

返回: `DestroyResult`.

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| result | string |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/image/destroy" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"public_id":"docs/renamed"}'
```

HTTP 200

```json
{
  "result": "ok"
}
```

## 重命名 [#重命名]

`POST /cloudinary/v1_1/{library_id}/{resource_type}/rename`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw / auto | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |

### 请求体 [#请求体-2]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| from_public_id | string | 是 | 原 public_id |
| to_public_id | string | 是 | 新 public_id |
| overwrite | boolean | 否 | 是否覆盖同名素材 |

返回: `CloudinaryResource`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string |  |
| public_id | string |  |
| display_name | string |  |
| asset_folder | string |  |
| resource_type | string |  |
| type | string |  |
| format | string |  |
| version | number |  |
| version_id | string |  |
| bytes | number |  |
| etag | string |  |
| width | number |  |
| height | number |  |
| duration | number |  |
| pages | number |  |
| is_audio | boolean |  |
| original_filename | string |  |
| tags | array&lt;string&gt; |  |
| context | object |  |
| context.custom | object |  |
| created_at | string |  |
| url | string |  |
| secure_url | string |  |
| placeholder | boolean |  |
| existing | boolean |  |
| processing | object |  |
| processing.state | string |  |
| processing.kinds | object |  |
| processing.updated_at | string |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/image/rename" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"from_public_id":"docs/pixel","to_public_id":"docs/renamed"}'
```

HTTP 200

```json
{
  "asset_id": "9339cdae93804c0c8c65d5189ef1f646",
  "public_id": "docs/renamed",
  "display_name": "Sample image",
  "asset_folder": "examples",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791538418,
  "version_id": "35848c1529994e338e7aa634a1c13d9c",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "context": {
    "custom": {
      "alt": "Sample"
    }
  },
  "created_at": "2026-10-09T09:33:38.899Z",
  "url": "https://media-develop.praxisusercontent.com/lib_77374d4ee73b4ae79c4aa430f3ba3885/image/upload/v1791538418/docs/renamed.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_77374d4ee73b4ae79c4aa430f3ba3885/image/upload/v1791538418/docs/renamed.png",
  "placeholder": false
}
```

## 修改标签 [#修改标签]

`POST /cloudinary/v1_1/{library_id}/{resource_type}/tags`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw / auto | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |

### 请求体 [#请求体-3]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| public_ids | string[] | 是 | 素材 public_id 列表 |
| tag | string | 否 | 标签名称 |
| command | add / remove / replace / remove_all | 是 | 标签或上下文操作 |

返回: `PublicIds`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| public_ids | array&lt;string&gt; |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/image/tags" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"public_ids":["docs/pixel"],"tag":"sample","command":"add"}'
```

HTTP 200

```json
{
  "public_ids": [
    "docs/pixel"
  ]
}
```

## 修改上下文 [#修改上下文]

`POST /cloudinary/v1_1/{library_id}/{resource_type}/context`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw / auto | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |

### 请求体 [#请求体-4]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| public_ids | string[] | 是 | 素材 public_id 列表 |
| context | string / object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| command | add / remove_all | 是 | 标签或上下文操作 |

返回: `PublicIds`.

### 响应 [#响应-4]

#### HTTP 200 [#http-200-4]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| public_ids | array&lt;string&gt; |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/image/context" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"public_ids":["docs/pixel"],"context":"alt=Sample","command":"add"}'
```

HTTP 200

```json
{
  "public_ids": [
    "docs/pixel"
  ]
}
```

## 更新素材 [#更新素材]

`POST /cloudinary/v1_1/{library_id}/{resource_type}/explicit`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw / auto | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |

### 请求体 [#请求体-5]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |
| tags | string / string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | string / object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |

返回: `CloudinaryResource`.

### 响应 [#响应-5]

#### HTTP 200 [#http-200-5]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string |  |
| public_id | string |  |
| display_name | string |  |
| asset_folder | string |  |
| resource_type | string |  |
| type | string |  |
| format | string |  |
| version | number |  |
| version_id | string |  |
| bytes | number |  |
| etag | string |  |
| width | number |  |
| height | number |  |
| duration | number |  |
| pages | number |  |
| is_audio | boolean |  |
| original_filename | string |  |
| tags | array&lt;string&gt; |  |
| context | object |  |
| context.custom | object |  |
| created_at | string |  |
| url | string |  |
| secure_url | string |  |
| placeholder | boolean |  |
| existing | boolean |  |
| processing | object |  |
| processing.state | string |  |
| processing.kinds | object |  |
| processing.updated_at | string |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/image/explicit" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"public_id":"docs/pixel","tags":["docs"]}'
```

HTTP 200

```json
{
  "asset_id": "9339cdae93804c0c8c65d5189ef1f646",
  "public_id": "docs/pixel",
  "display_name": "Sample image",
  "asset_folder": "examples",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791538418,
  "version_id": "35848c1529994e338e7aa634a1c13d9c",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "context": {
    "custom": {
      "alt": "Sample"
    }
  },
  "created_at": "2026-10-09T09:33:38.899Z",
  "url": "https://media-develop.praxisusercontent.com/lib_77374d4ee73b4ae79c4aa430f3ba3885/image/upload/v1791538418/docs/pixel.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_77374d4ee73b4ae79c4aa430f3ba3885/image/upload/v1791538418/docs/pixel.png",
  "placeholder": false
}
```

## CloudinaryResource [#cloudinaryresource]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_id | AssetId | 是 | 素材 ID |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |
| display_name | string | 是 | 显示名称 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| resource_type | ResourceType | 是 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| type | DeliveryType | 是 | 资源或事件类型 |
| format | string | 是 | 文件格式 |
| version | number | 是 | 交付版本号 |
| version_id | string | 是 | 版本标识 |
| bytes | number | 是 | 文件字节数 |
| etag | string | 是 | 文件校验标识 |
| width | number | 否 | 宽度像素 |
| height | number | 否 | 高度像素 |
| duration | number | 否 | 时长秒数 |
| pages | number | 否 | 文档页数 |
| is_audio | boolean | 否 | 是否为音频 |
| original_filename | string | 否 | 原文件名称 |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| created_at | IsoTimestamp | 是 | 创建时间 |
| url | string | 是 | 原文件地址 |
| secure_url | string | 是 | HTTPS 交付地址 |
| placeholder | false | 是 | 固定为 false |
| existing | boolean | 否 | 未覆盖时是否返回已有素材 |
| processing | Processing | 否 | 整体与各项理解状态 |

## DestroyResult [#destroyresult]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| result | ok / not found | 是 | 操作结果 |

## PublicIds [#publicids]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| public_ids | string[] | 是 | 素材 public_id 列表 |

## ChunkPending [#chunkpending]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| done | false | 是 | 已完成数量；分片响应中表示是否完成 |
| upload_id | string | 是 | 分片会话标识 |

## ChunkComplete [#chunkcomplete]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_id | AssetId | 是 | 素材 ID |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |
| display_name | string | 是 | 显示名称 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| resource_type | ResourceType | 是 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| type | DeliveryType | 是 | 资源或事件类型 |
| format | string | 是 | 文件格式 |
| version | number | 是 | 交付版本号 |
| version_id | string | 是 | 版本标识 |
| bytes | number | 是 | 文件字节数 |
| etag | string | 是 | 文件校验标识 |
| width | number | 否 | 宽度像素 |
| height | number | 否 | 高度像素 |
| duration | number | 否 | 时长秒数 |
| pages | number | 否 | 文档页数 |
| is_audio | boolean | 否 | 是否为音频 |
| original_filename | string | 否 | 原文件名称 |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| created_at | IsoTimestamp | 是 | 创建时间 |
| url | string | 是 | 原文件地址 |
| secure_url | string | 是 | HTTPS 交付地址 |
| placeholder | false | 是 | 固定为 false |
| existing | boolean | 否 | 未覆盖时是否返回已有素材 |
| processing | Processing | 否 | 整体与各项理解状态 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| done | true | 是 | 已完成数量；分片响应中表示是否完成 |

# 资源管理

Admin 管理当前库的素材。usage 只返回当前存储量和素材数。

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/compatible/cloudinary)

## 读取素材 [#读取素材]

`GET /cloudinary/v1_1/{library_id}/resources`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `ResourcePage`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "resources": [
    {
      "asset_id": "9dfa312ef9bc4b00816339b598b1152c",
      "public_id": "walk-lib-r1-MDP-1791733789929-tagged",
      "display_name": "walk-lib-r1-MDP-1791733789929-tagged",
      "asset_folder": "",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791733815,
      "version_id": "26cb8171caa5431b8373ad417fd71e32",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "processing": {
        "state": "processing",
        "kinds": {
          "embedding": "running",
          "visual": "failed",
          "tagging": "failed"
        },
        "updated_at": "2026-10-11T15:50:21.512Z"
      },
      "created_at": "2026-10-11T15:50:15.996Z",
      "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
      "placeholder": false
    },
    {
      "asset_id": "85b7ef616a8b4719a41777a036ebc1d2",
      "public_id": "walk-lib-r1-MDP-1791733789929-plain",
      "display_name": "walk-lib-r1-MDP-1791733789929-plain",
      "asset_folder": "",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791733810,
      "version_id": "fdf3c8cd40c2424d86e8397425a69857",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-11T15:50:10.842Z",
      "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
      "placeholder": false
    }
  ]
}
```

## 读取素材 [#读取素材-1]

`GET /cloudinary/v1_1/{library_id}/resources/{resource_type}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `ResourcePage`.

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "resources": [
    {
      "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
      "public_id": "examples/pixel",
      "display_name": "pixel",
      "asset_folder": "examples",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791538435,
      "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-09T09:33:55.536Z",
      "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "placeholder": false
    }
  ]
}
```

## 读取素材 [#读取素材-2]

`GET /cloudinary/v1_1/{library_id}/resources/{resource_type}/upload`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `ResourcePage`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image/upload" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "resources": [
    {
      "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
      "public_id": "examples/pixel",
      "display_name": "pixel",
      "asset_folder": "examples",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791538435,
      "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-09T09:33:55.536Z",
      "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "placeholder": false
    }
  ]
}
```

## 读取素材 [#读取素材-3]

`GET /cloudinary/v1_1/{library_id}/resources/{asset_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| asset_id | path | string | 素材 ID |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `CloudinaryResource`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string |  |
| public_id | string |  |
| display_name | string |  |
| asset_folder | string |  |
| resource_type | string |  |
| type | string |  |
| format | string |  |
| version | number |  |
| version_id | string |  |
| bytes | number |  |
| etag | string |  |
| width | number |  |
| height | number |  |
| duration | number |  |
| pages | number |  |
| is_audio | boolean |  |
| original_filename | string |  |
| tags | array&lt;string&gt; |  |
| context | object |  |
| context.custom | object |  |
| created_at | string |  |
| url | string |  |
| secure_url | string |  |
| placeholder | boolean |  |
| existing | boolean |  |
| processing | object |  |
| processing.state | string |  |
| processing.kinds | object |  |
| processing.updated_at | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/9dfa312ef9bc4b00816339b598b1152c" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "asset_id": "9dfa312ef9bc4b00816339b598b1152c",
  "public_id": "walk-lib-r1-MDP-1791733789929-tagged",
  "display_name": "walk-lib-r1-MDP-1791733789929-tagged",
  "asset_folder": "",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791733815,
  "version_id": "26cb8171caa5431b8373ad417fd71e32",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "processing": {
    "state": "processing",
    "kinds": {
      "embedding": "running",
      "visual": "failed",
      "tagging": "failed"
    },
    "updated_at": "2026-10-11T15:50:21.512Z"
  },
  "created_at": "2026-10-11T15:50:15.996Z",
  "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
  "placeholder": false
}
```

## 读取素材 [#读取素材-4]

`GET /cloudinary/v1_1/{library_id}/resources/by_asset_ids`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `ResourcePage`.

### 响应 [#响应-4]

#### HTTP 200 [#http-200-4]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/by_asset_ids?asset_ids[]=e5f3de0d8609482d8b351894b133c8cb" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "resources": [
    {
      "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
      "public_id": "examples/pixel",
      "display_name": "pixel",
      "asset_folder": "examples",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791538435,
      "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-09T09:33:55.536Z",
      "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "placeholder": false
    }
  ]
}
```

## 读取素材 [#读取素材-5]

`GET /cloudinary/v1_1/{library_id}/resources/by_asset_folder`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `ResourcePage`.

### 响应 [#响应-5]

#### HTTP 200 [#http-200-5]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/by_asset_folder?asset_folder=examples" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "resources": [
    {
      "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
      "public_id": "examples/pixel",
      "display_name": "pixel",
      "asset_folder": "examples",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791538435,
      "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-09T09:33:55.536Z",
      "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "placeholder": false
    }
  ]
}
```

## 读取素材 [#读取素材-6]

`GET /cloudinary/v1_1/{library_id}/resources/{resource_type}/tags/{tag}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| tag | path | string | 标签名称 |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `ResourcePage`.

### 响应 [#响应-6]

#### HTTP 200 [#http-200-6]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image/tags/docs" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "resources": [
    {
      "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
      "public_id": "examples/pixel",
      "display_name": "pixel",
      "asset_folder": "examples",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791538435,
      "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-09T09:33:55.536Z",
      "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "placeholder": false
    }
  ]
}
```

## 读取素材 [#读取素材-7]

`GET /cloudinary/v1_1/{library_id}/resources/{resource_type}/context`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `ResourcePage`.

### 响应 [#响应-7]

#### HTTP 200 [#http-200-7]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image/context?key=alt&value=sample" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "resources": [
    {
      "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
      "public_id": "examples/pixel",
      "display_name": "pixel",
      "asset_folder": "examples",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791538435,
      "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-09T09:33:55.536Z",
      "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "placeholder": false
    }
  ]
}
```

## 读取素材 [#读取素材-8]

`GET /cloudinary/v1_1/{library_id}/resources/{resource_type}/upload/{public_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| public_id | path | string | 交付地址中的素材名称，可带路径 |
| prefix | query | string | — |
| public_ids | query | string[] | 素材 public_id 列表 |
| asset_ids | query | string[] | — |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| key | query | string | — |
| value | query | string | — |
| tags | query | string | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | query | string | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| direction | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `CloudinaryResource`.

### 响应 [#响应-8]

#### HTTP 200 [#http-200-8]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string |  |
| public_id | string |  |
| display_name | string |  |
| asset_folder | string |  |
| resource_type | string |  |
| type | string |  |
| format | string |  |
| version | number |  |
| version_id | string |  |
| bytes | number |  |
| etag | string |  |
| width | number |  |
| height | number |  |
| duration | number |  |
| pages | number |  |
| is_audio | boolean |  |
| original_filename | string |  |
| tags | array&lt;string&gt; |  |
| context | object |  |
| context.custom | object |  |
| created_at | string |  |
| url | string |  |
| secure_url | string |  |
| placeholder | boolean |  |
| existing | boolean |  |
| processing | object |  |
| processing.state | string |  |
| processing.kinds | object |  |
| processing.updated_at | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image/upload/examples/pixel" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
  "public_id": "examples/pixel",
  "display_name": "pixel",
  "asset_folder": "examples",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791538435,
  "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "context": {
    "custom": {
      "alt": "sample"
    }
  },
  "created_at": "2026-10-09T09:33:55.536Z",
  "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
  "placeholder": false
}
```

## 按 ID 读取 [#按-id-读取]

`POST /cloudinary/v1_1/{library_id}/resources/by_asset_ids`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_ids | string[] | 是 | — |
| max_results | integer | 否 | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |

返回: `ResourcePage`.

### 响应 [#响应-9]

#### HTTP 200 [#http-200-9]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| next_cursor | string |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/by_asset_ids" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"asset_ids":["e5f3de0d8609482d8b351894b133c8cb"]}'
```

HTTP 200

```json
{
  "resources": [
    {
      "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
      "public_id": "examples/pixel",
      "display_name": "pixel",
      "asset_folder": "examples",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791538435,
      "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-09T09:33:55.536Z",
      "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
      "placeholder": false
    }
  ]
}
```

## 更新素材 [#更新素材]

`POST /cloudinary/v1_1/{library_id}/resources/{resource_type}/upload/{public_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| public_id | path | string | 交付地址中的素材名称，可带路径 |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| display_name | string | 否 | 显示名称 |
| asset_folder | string | 否 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| tags | string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |

返回: `CloudinaryResource`.

### 响应 [#响应-10]

#### HTTP 200 [#http-200-10]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string |  |
| public_id | string |  |
| display_name | string |  |
| asset_folder | string |  |
| resource_type | string |  |
| type | string |  |
| format | string |  |
| version | number |  |
| version_id | string |  |
| bytes | number |  |
| etag | string |  |
| width | number |  |
| height | number |  |
| duration | number |  |
| pages | number |  |
| is_audio | boolean |  |
| original_filename | string |  |
| tags | array&lt;string&gt; |  |
| context | object |  |
| context.custom | object |  |
| created_at | string |  |
| url | string |  |
| secure_url | string |  |
| placeholder | boolean |  |
| existing | boolean |  |
| processing | object |  |
| processing.state | string |  |
| processing.kinds | object |  |
| processing.updated_at | string |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image/upload/examples/pixel" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"display_name":"Sample image"}'
```

HTTP 200

```json
{
  "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
  "public_id": "examples/pixel",
  "display_name": "Sample image",
  "asset_folder": "examples",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791538435,
  "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "context": {
    "custom": {
      "alt": "sample"
    }
  },
  "created_at": "2026-10-09T09:33:55.536Z",
  "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
  "placeholder": false
}
```

## 更新素材 [#更新素材-1]

`PUT /cloudinary/v1_1/{library_id}/resources/{resource_type}/upload/{public_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| public_id | path | string | 交付地址中的素材名称，可带路径 |

### 请求体 [#请求体-2]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| display_name | string | 否 | 显示名称 |
| asset_folder | string | 否 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| tags | string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |

返回: `CloudinaryResource`.

### 响应 [#响应-11]

#### HTTP 200 [#http-200-11]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string |  |
| public_id | string |  |
| display_name | string |  |
| asset_folder | string |  |
| resource_type | string |  |
| type | string |  |
| format | string |  |
| version | number |  |
| version_id | string |  |
| bytes | number |  |
| etag | string |  |
| width | number |  |
| height | number |  |
| duration | number |  |
| pages | number |  |
| is_audio | boolean |  |
| original_filename | string |  |
| tags | array&lt;string&gt; |  |
| context | object |  |
| context.custom | object |  |
| created_at | string |  |
| url | string |  |
| secure_url | string |  |
| placeholder | boolean |  |
| existing | boolean |  |
| processing | object |  |
| processing.state | string |  |
| processing.kinds | object |  |
| processing.updated_at | string |  |

```bash
curl -X PUT "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image/upload/examples/pixel" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"tags":["docs"]}'
```

HTTP 200

```json
{
  "asset_id": "e5f3de0d8609482d8b351894b133c8cb",
  "public_id": "examples/pixel",
  "display_name": "Sample image",
  "asset_folder": "examples",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791538435,
  "version_id": "001fb6336c9b4a4c9e4597b69fdec3cd",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "context": {
    "custom": {
      "alt": "sample"
    }
  },
  "created_at": "2026-10-09T09:33:55.536Z",
  "url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_b762c40631bd42278a204cd0370fed36/image/upload/v1791538435/examples/pixel.png",
  "placeholder": false
}
```

## 删除素材 [#删除素材]

`DELETE /cloudinary/v1_1/{library_id}/resources/{resource_type}/upload`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| public_ids | query | string[] | 素材 public_id 列表 |
| prefix | query | string | — |
| all | query | boolean | — |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `DeletedResources`.

### 响应 [#响应-12]

#### HTTP 200 [#http-200-12]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| deleted | object |  |
| partial | boolean |  |
| next_cursor | string |  |

```bash
curl -X DELETE "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image/upload" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"prefix":"imported/"}'
```

HTTP 200

```json
{
  "deleted": {},
  "partial": false
}
```

## 删除素材 [#删除素材-1]

`DELETE /cloudinary/v1_1/{library_id}/resources/{resource_type}/tags/{tag}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| tag | path | string | 标签名称 |
| public_ids | query | string[] | 素材 public_id 列表 |
| prefix | query | string | — |
| all | query | boolean | — |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `DeletedResources`.

### 响应 [#响应-13]

#### HTTP 200 [#http-200-13]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| deleted | object |  |
| partial | boolean |  |
| next_cursor | string |  |

```bash
curl -X DELETE "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/image/tags/remove-me" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{}'
```

HTTP 200

```json
{
  "deleted": {
    "tagged/pixel": "deleted"
  },
  "partial": false
}
```

## 列出标签 [#列出标签]

`GET /cloudinary/v1_1/{library_id}/tags/{resource_type}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| resource_type | path | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| prefix | query | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `Tags`.

### 响应 [#响应-14]

#### HTTP 200 [#http-200-14]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| tags | array&lt;string&gt; |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/tags/image" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "tags": [
    "docs"
  ]
}
```

## 列出文件夹 [#列出文件夹]

`GET /cloudinary/v1_1/{library_id}/folders`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `CompatFolders`.

### 响应 [#响应-15]

#### HTTP 200 [#http-200-15]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| folders | array&lt;object&gt; |  |
| folders[].name | string |  |
| folders[].path | string |  |
| total_count | number |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/folders" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "folders": [
    {
      "name": "examples",
      "path": "examples"
    }
  ],
  "total_count": 1
}
```

## 列出文件夹 [#列出文件夹-1]

`GET /cloudinary/v1_1/{library_id}/folders/{folder}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| folder | path | string | — |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |

返回: `CompatFolders`.

### 响应 [#响应-16]

#### HTTP 200 [#http-200-16]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| folders | array&lt;object&gt; |  |
| folders[].name | string |  |
| folders[].path | string |  |
| total_count | number |  |
| next_cursor | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/folders/examples" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "folders": [],
  "total_count": 0
}
```

## 创建文件夹 [#创建文件夹]

`POST /cloudinary/v1_1/{library_id}/folders/{folder}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| folder | path | string | — |

返回: `FolderResult`.

### 响应 [#响应-17]

#### HTTP 200 [#http-200-17]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/folders/sample" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{}'
```

HTTP 200

```json
{
  "success": true,
  "path": "sample"
}
```

## 重命名文件夹 [#重命名文件夹]

`PUT /cloudinary/v1_1/{library_id}/folders/{folder}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| folder | path | string | — |

### 请求体 [#请求体-3]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| to_folder | string | 是 | 目标文件夹路径 |

返回: `FolderResult`.

### 响应 [#响应-18]

#### HTTP 200 [#http-200-18]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

## 删除文件夹 [#删除文件夹]

`DELETE /cloudinary/v1_1/{library_id}/folders/{folder}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| folder | path | string | — |

返回: `FolderResult`.

### 响应 [#响应-19]

#### HTTP 200 [#http-200-19]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

```bash
curl -X DELETE "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/folders/sample" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{}'
```

HTTP 200

```json
{
  "success": true,
  "path": "sample"
}
```

## 检查连接 [#检查连接]

`GET /cloudinary/v1_1/{library_id}/ping`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

返回: `Ping`.

### 响应 [#响应-20]

#### HTTP 200 [#http-200-20]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| status | string |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/ping" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "status": "ok"
}
```

## 读取用量 [#读取用量]

`GET /cloudinary/v1_1/{library_id}/usage`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

返回: `Usage`.

### 响应 [#响应-21]

#### HTTP 200 [#http-200-21]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| storage | object |  |
| storage.usage | number |  |
| objects | object |  |
| objects.usage | number |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/usage" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "storage": {
    "usage": 70
  },
  "objects": {
    "usage": 1
  }
}
```

## 读取用量 [#读取用量-1]

`GET /cloudinary/v1_1/{library_id}/usage/{date}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| date | path | string | — |

返回: `Usage`.

### 响应 [#响应-22]

#### HTTP 200 [#http-200-22]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| storage | object |  |
| storage.usage | number |  |
| objects | object |  |
| objects.usage | number |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/usage/2026-10-09" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "storage": {
    "usage": 70
  },
  "objects": {
    "usage": 1
  }
}
```

## ResourcePage [#resourcepage]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| resources | SearchResource[] | 是 | 本页素材 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |

## CloudinaryResource [#cloudinaryresource]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_id | AssetId | 是 | 素材 ID |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |
| display_name | string | 是 | 显示名称 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| resource_type | ResourceType | 是 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| type | DeliveryType | 是 | 资源或事件类型 |
| format | string | 是 | 文件格式 |
| version | number | 是 | 交付版本号 |
| version_id | string | 是 | 版本标识 |
| bytes | number | 是 | 文件字节数 |
| etag | string | 是 | 文件校验标识 |
| width | number | 否 | 宽度像素 |
| height | number | 否 | 高度像素 |
| duration | number | 否 | 时长秒数 |
| pages | number | 否 | 文档页数 |
| is_audio | boolean | 否 | 是否为音频 |
| original_filename | string | 否 | 原文件名称 |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| created_at | IsoTimestamp | 是 | 创建时间 |
| url | string | 是 | 原文件地址 |
| secure_url | string | 是 | HTTPS 交付地址 |
| placeholder | false | 是 | 固定为 false |
| existing | boolean | 否 | 未覆盖时是否返回已有素材 |
| processing | Processing | 否 | 整体与各项理解状态 |

## DeletedResources [#deletedresources]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| deleted | object | 是 | 删除结果 |
| partial | boolean | 是 | 是否还有未处理的后续页 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |

## Tags [#tags]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |

## CompatFolders [#compatfolders]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| folders | object[] | 是 | 文件夹列表 |
| total_count | number | 是 | 匹配总数 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |

## FolderResult [#folderresult]

| 字段 | 类型 | 必填 | 说明 |
| -- | -- | -- | -- |

## Ping [#ping]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| status | "ok" | 是 | 资源状态 |

## Usage [#usage]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| storage | object | 是 | 存储字节用量 |
| objects | object | 是 | 素材数量 |

# 检索

[指南 →](/docs/cloud/services/media/quickstart)

表达式检索仅支持以下子集。不支持的语法或字段返回 HTTP 400 INVALID\_EXPRESSION；兼容错误体只包含消息。默认省略 tags 与 context；需要时用 with\_field 请求。

| 语法 | 含义 |
| --- | --- |
| AND / OR / NOT / - / ( ) | 布尔组合；相邻条件默认 AND |
| field:value / field=value | 字段匹配 |
| bytes > 1000 / width >= 160 | 数值比较；也支持 height、duration |
| created_at >= 2026-01-01 / uploaded_at > 7d | 日期或相对时间，支持 d/w/m/y |
| tags:docs / context.alt:"sample image" | 标签和自定义文字 |
| public_id:docs* | 仅末尾通配符 |
| "sample image" | 短语 |
| sunset | 裸词：在 public_id、display_name、tags、context 以及理解得到的描述、图片文字、转写中做全文匹配，不区分大小写 |
| ~ / ^ / [a TO z] / *prefix / a*b | 不支持，返回 400 |

字段名不区分大小写（RESOURCE\_TYPE:image 等同 resource\_type:image）；resource\_type、type、format 的值不区分大小写；tags、context 等其他字段的值区分大小写。空表达式返回全部素材；无法解析的表达式返回 400 INVALID\_EXPRESSION。

查询字段: `asset_id, resource_type, type, format, public_id, asset_folder, display_name, tags, bytes, width, height, duration, created_at, uploaded_at, context.<key>`.

排序字段: `created_at, public_id, display_name, bytes, uploaded_at`.

统计字段: `resource_type, format, asset_folder, processing_state`.
[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/compatible/cloudinary)

## 以图搜图 [#以图搜图]

`GET /cloudinary/v1_1/{library_id}/resources/visual_search`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| image_asset_id | query | string | 本库素材 ID |
| image_url | query | string | 仅接受本库交付 URL，不支持抓取外部 URL |
| text | query | string | 自然语言查询，使用语义检索 |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| filter | query | string | 表达式筛选条件 |

返回: `VisualResources`.

库的 `search.image` 为 true 时可用；不支持的库返回 LIBRARY\_INVALID\_STATE。图片仅接受 JPEG、PNG、WebP、GIF，解码后最大 10 MiB。每个素材返回最高分命中，视频定位到最佳帧。qwen3-vl-embedding 的图片相似度门槛为 0.35。标定来自 2026-10-10 的测试：同图变体 0.82–0.96，同类场景 0.38–0.66，无关图片最高 0.34。

`image_asset_id`、`image_file`（multipart）、`image_url`、`text` 必须且只能传一个。text 使用纯语义检索；返回 `{ "resources": [...] }`。image\_url 只接受本库交付 URL，不抓取外部 URL；外部 URL 返回 400「不支持抓取外部 URL」。

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |

## 以图搜图 [#以图搜图-1]

`POST /cloudinary/v1_1/{library_id}/resources/visual_search`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| image_asset_id | string | 否 | 本库素材 ID |
| image_url | string | 否 | 仅接受本库交付 URL，不支持抓取外部 URL |
| image_file | string | 否 | JPEG、PNG、WebP 或 GIF 文件，最大 10 MiB |
| text | string | 否 | 自然语言查询，使用语义检索 |
| max_results | integer | 否 | 最多 500；检索默认 100，Admin 默认 10 |
| filter | string | 否 | 表达式筛选条件 |

返回: `VisualResources`.

库的 `search.image` 为 true 时可用；不支持的库返回 LIBRARY\_INVALID\_STATE。图片仅接受 JPEG、PNG、WebP、GIF，解码后最大 10 MiB。每个素材返回最高分命中，视频定位到最佳帧。qwen3-vl-embedding 的图片相似度门槛为 0.35。标定来自 2026-10-10 的测试：同图变体 0.82–0.96，同类场景 0.38–0.66，无关图片最高 0.34。

`image_asset_id`、`image_file`（multipart）、`image_url`、`text` 必须且只能传一个。text 使用纯语义检索；返回 `{ "resources": [...] }`。image\_url 只接受本库交付 URL，不抓取外部 URL；外部 URL 返回 400「不支持抓取外部 URL」。

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |

## 表达式检索 [#表达式检索]

`GET /cloudinary/v1_1/{library_id}/resources/search`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| expression | query | string | 结构化查询表达式；空表达式返回全部素材 |
| sort_by | query | string | 排序字段与方向 |
| max_results | query | integer | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | query | string | 下一页游标；没有时为 null 或省略 |
| with_field | query | string[] | 额外返回 tags 或 context |
| aggregate | query | string[] | 统计字段 |

返回: `CompatExpressionSearchResult`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| total_count | number |  |
| time | number |  |
| next_cursor | string |  |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| aggregations | object |  |

```bash
curl -X GET "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/search?expression=tags%3Adocs" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "total_count": 1,
  "time": 0,
  "resources": [
    {
      "asset_id": "9339cdae93804c0c8c65d5189ef1f646",
      "public_id": "docs/pixel",
      "display_name": "Sample image",
      "asset_folder": "examples",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791538418,
      "version_id": "35848c1529994e338e7aa634a1c13d9c",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-09T09:33:38.899Z",
      "url": "https://media-develop.praxisusercontent.com/lib_77374d4ee73b4ae79c4aa430f3ba3885/image/upload/v1791538418/docs/pixel.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_77374d4ee73b4ae79c4aa430f3ba3885/image/upload/v1791538418/docs/pixel.png",
      "placeholder": false
    }
  ]
}
```

## 表达式检索 [#表达式检索-1]

`POST /cloudinary/v1_1/{library_id}/resources/search`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| expression | string | 否 | 结构化查询表达式；空表达式返回全部素材 |
| sort_by | object[] | 否 | 排序字段与方向 |
| max_results | integer | 否 | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |
| with_field | "tags" / "context"[] | 否 | 额外返回 tags 或 context |
| aggregate | AggregateField[] | 否 | 统计字段 |

返回: `CompatExpressionSearchResult`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| total_count | number |  |
| time | number |  |
| next_cursor | string |  |
| resources | array&lt;object&gt; |  |
| resources[].asset_id | string |  |
| resources[].public_id | string |  |
| resources[].display_name | string |  |
| resources[].asset_folder | string |  |
| resources[].resource_type | string |  |
| resources[].type | string |  |
| resources[].format | string |  |
| resources[].version | number |  |
| resources[].version_id | string |  |
| resources[].bytes | number |  |
| resources[].etag | string |  |
| resources[].width | number |  |
| resources[].height | number |  |
| resources[].duration | number |  |
| resources[].pages | number |  |
| resources[].is_audio | boolean |  |
| resources[].original_filename | string |  |
| resources[].tags | array&lt;string&gt; |  |
| resources[].context | object |  |
| resources[].created_at | string |  |
| resources[].url | string |  |
| resources[].secure_url | string |  |
| resources[].placeholder | boolean |  |
| resources[].existing | boolean |  |
| resources[].processing | object |  |
| aggregations | object |  |

```bash
curl -X POST "https://api.deepraxis.ai/cloudinary/v1_1/${LIBRARY_ID}/resources/search" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"expression":"tags:docs"}'
```

HTTP 200

```json
{
  "total_count": 2,
  "time": 0,
  "resources": [
    {
      "asset_id": "9dfa312ef9bc4b00816339b598b1152c",
      "public_id": "walk-lib-r1-MDP-1791733789929-tagged",
      "display_name": "walk-lib-r1-MDP-1791733789929-tagged",
      "asset_folder": "",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791733815,
      "version_id": "26cb8171caa5431b8373ad417fd71e32",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "processing": {
        "state": "processing",
        "kinds": {
          "embedding": "running",
          "visual": "failed",
          "tagging": "failed"
        },
        "updated_at": "2026-10-11T15:50:21.512Z"
      },
      "created_at": "2026-10-11T15:50:15.996Z",
      "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
      "placeholder": false
    },
    {
      "asset_id": "85b7ef616a8b4719a41777a036ebc1d2",
      "public_id": "walk-lib-r1-MDP-1791733789929-plain",
      "display_name": "walk-lib-r1-MDP-1791733789929-plain",
      "asset_folder": "",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791733810,
      "version_id": "fdf3c8cd40c2424d86e8397425a69857",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-11T15:50:10.842Z",
      "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
      "placeholder": false
    }
  ]
}
```

## VisualResources [#visualresources]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| resources | CloudinaryResource[] | 是 | 本页素材 |

## CompatExpressionSearchResult [#compatexpressionsearchresult]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| total_count | number | 是 | 匹配总数 |
| time | number | 是 | 检索耗时，整数毫秒，由服务端测得 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |
| resources | SearchResource[] | 是 | 本页素材 |
| aggregations | object | 否 | 按请求字段统计 |

## SearchResource [#searchresource]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_id | AssetId | 是 | 素材 ID |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |
| display_name | string | 是 | 显示名称 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| resource_type | ResourceType | 是 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| type | DeliveryType | 是 | 资源或事件类型 |
| format | string | 是 | 文件格式 |
| version | number | 是 | 交付版本号 |
| version_id | string | 是 | 版本标识 |
| bytes | number | 是 | 文件字节数 |
| etag | string | 是 | 文件校验标识 |
| width | number | 否 | 宽度像素 |
| height | number | 否 | 高度像素 |
| duration | number | 否 | 时长秒数 |
| pages | number | 否 | 文档页数 |
| is_audio | boolean | 否 | 是否为音频 |
| original_filename | string | 否 | 原文件名称 |
| tags | string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| created_at | IsoTimestamp | 是 | 创建时间 |
| url | string | 是 | 原文件地址 |
| secure_url | string | 是 | HTTPS 交付地址 |
| placeholder | false | 是 | 固定为 false |
| existing | boolean | 否 | 未覆盖时是否返回已有素材 |
| processing | Processing | 否 | 整体与各项理解状态 |

# 交付与变换

[指南 →](/docs/cloud/services/media/quickstart)

用上传响应的 secure\_url 读取原文件，在 upload 与版本之间插入变换。

`https://media-develop.praxisusercontent.com/{library_id}/{resource_type}/upload/{transformation}/v{version}/{public_id}.{format}`

原文件省略 transformation 及其后斜杠。仅接受以下白名单；其它变换返回错误。

| 参数 | 允许值 |
| --- | --- |
| w_ | 160, 320, 640, 1280 |
| c_ | fill, fit, limit, scale, pad |
| g_ | auto, center |
| f_ | auto, jpg, png, webp, avif |
| q_ | auto, auto:good, auto:eco |
| dpr_ | 1, 2 |
| so_ | 视频秒数，扩展名 .jpg；源文件不超过 100 MiB |

```text
w_160,c_fit
w_320,c_fill,g_center,f_webp,q_auto,dpr_2
```

## 用户内容安全 [#用户内容安全]

交付使用独立的可注册域 `praxisusercontent.com`，与 API 和登录域隔离：Develop 为 `media-develop.praxisusercontent.com`，生产为 `media.praxisusercontent.com`。URL 路径形状不变，交付不携带任何 cookie。

* 只允许 GET 和 HEAD；其他方法返回 405。
* 不向上游转发 cookie 和凭据，响应移除 Set-Cookie。
* 所有响应都带 `X-Content-Type-Options: nosniff`。
* HTML、SVG、XML、JavaScript 类内容都带 `Content-Security-Policy: sandbox` 和 `Content-Disposition: attachment`。
* 支持 Range 请求，部分内容返回 206。

# Browserbase

[连接与使用指南](/docs/cloud/services/browser)

基础地址: `https://api-develop.deepraxis.ai/browserbase`

请求头: `X-BB-API-Key: $PRAXIS_API_KEY`

请求 ID 响应头: `X-Request-Id`

官方 SDK 设置 baseURL 后使用以下接口。代理、反检测、扩展和 Selenium 不可用；region 与 solveCaptchas 接受但忽略。删除登录态返回 200 和 deleted=true；会话响应还可能包含 currentUrl、clients、handoff。

| 操作                                                               | 方法与路径                                         |
| ---------------------------------------------------------------- | --------------------------------------------- |
| [创建浏览器会话](/docs/api/compatible/browserbase/Sessions_create)      | `POST /browserbase/v1/sessions`               |
| [列出浏览器会话](/docs/api/compatible/browserbase/Sessions_list)        | `GET /browserbase/v1/sessions`                |
| [读取浏览器会话](/docs/api/compatible/browserbase/Sessions_get)         | `GET /browserbase/v1/sessions/{id}`           |
| [关闭浏览器会话](/docs/api/compatible/browserbase/Sessions_update)      | `POST /browserbase/v1/sessions/{id}`          |
| [读取调试地址](/docs/api/compatible/browserbase/Sessions_getDebug)     | `GET /browserbase/v1/sessions/{id}/debug`     |
| [读取会话日志](/docs/api/compatible/browserbase/Sessions_getLogs)      | `GET /browserbase/v1/sessions/{id}/logs`      |
| [读取会话录像](/docs/api/compatible/browserbase/Sessions_getRecording) | `GET /browserbase/v1/sessions/{id}/recording` |
| [创建登录态](/docs/api/compatible/browserbase/Contexts_create)        | `POST /browserbase/v1/contexts`               |
| [读取登录态](/docs/api/compatible/browserbase/Contexts_get)           | `GET /browserbase/v1/contexts/{id}`           |
| [删除登录态](/docs/api/compatible/browserbase/Contexts_delete)        | `DELETE /browserbase/v1/contexts/{id}`        |

# 创建浏览器会话

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 201 [#http-201]

The request has succeeded and a new resource has been created as a result.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| createdAt | string |  |
| updatedAt | string |  |
| projectId | string | The Project ID linked to the Session. |
| startedAt | string |  |
| endedAt | string |  |
| expiresAt | string |  |
| status | string |  |
| proxyBytes | integer | Bytes used via the [Proxy](/features/stealth-mode#proxies-and-residential-ips) |
| keepAlive | boolean | Indicates if the Session was created to be kept alive upon disconnections |
| contextId | string | Optional. The Context linked to the Session. |
| region | string | The region where the Session is running. |
| userMetadata | object | Arbitrary user metadata to attach to the session. To learn more about user metadata, see [User Metadata](/features/sessions#user-metadata). |
| connectUrl | string | WebSocket URL to connect to the Session. |
| seleniumRemoteUrl | string | HTTP URL to connect to the Session. |
| signingKey | string | Signing key to use when connecting to the Session via HTTP. |

# 列出浏览器会话

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 200 [#http-200]

The request has succeeded.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string |  |
| [].createdAt | string |  |
| [].updatedAt | string |  |
| [].projectId | string | The Project ID linked to the Session. |
| [].startedAt | string |  |
| [].endedAt | string |  |
| [].expiresAt | string |  |
| [].status | string |  |
| [].proxyBytes | integer | Bytes used via the [Proxy](/features/stealth-mode#proxies-and-residential-ips) |
| [].keepAlive | boolean | Indicates if the Session was created to be kept alive upon disconnections |
| [].contextId | string | Optional. The Context linked to the Session. |
| [].region | string | The region where the Session is running. |
| [].userMetadata | object | Arbitrary user metadata to attach to the session. To learn more about user metadata, see [User Metadata](/features/sessions#user-metadata). |

# 读取浏览器会话

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 200 [#http-200]

The request has succeeded.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| createdAt | string |  |
| updatedAt | string |  |
| projectId | string | The Project ID linked to the Session. |
| startedAt | string |  |
| endedAt | string |  |
| expiresAt | string |  |
| status | string |  |
| proxyBytes | integer | Bytes used via the [Proxy](/features/stealth-mode#proxies-and-residential-ips) |
| keepAlive | boolean | Indicates if the Session was created to be kept alive upon disconnections |
| contextId | string | Optional. The Context linked to the Session. |
| region | string | The region where the Session is running. |
| userMetadata | object | Arbitrary user metadata to attach to the session. To learn more about user metadata, see [User Metadata](/features/sessions#user-metadata). |
| connectUrl | string | WebSocket URL to connect to the Session. |
| seleniumRemoteUrl | string | HTTP URL to connect to the Session. |
| signingKey | string | Signing key to use when connecting to the Session via HTTP. |

# 关闭浏览器会话

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 200 [#http-200]

The request has succeeded.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| createdAt | string |  |
| updatedAt | string |  |
| projectId | string | The Project ID linked to the Session. |
| startedAt | string |  |
| endedAt | string |  |
| expiresAt | string |  |
| status | string |  |
| proxyBytes | integer | Bytes used via the [Proxy](/features/stealth-mode#proxies-and-residential-ips) |
| keepAlive | boolean | Indicates if the Session was created to be kept alive upon disconnections |
| contextId | string | Optional. The Context linked to the Session. |
| region | string | The region where the Session is running. |
| userMetadata | object | Arbitrary user metadata to attach to the session. To learn more about user metadata, see [User Metadata](/features/sessions#user-metadata). |

# 读取调试地址

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 200 [#http-200]

The request has succeeded.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| debuggerFullscreenUrl | string |  |
| debuggerUrl | string |  |
| pages | array&lt;object&gt; |  |
| pages[].id | string |  |
| pages[].url | string |  |
| pages[].faviconUrl | string |  |
| pages[].title | string |  |
| pages[].debuggerUrl | string |  |
| pages[].debuggerFullscreenUrl | string |  |
| wsUrl | string |  |

# 读取会话日志

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 200 [#http-200]

The request has succeeded.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].method | string |  |
| [].pageId | integer |  |
| [].sessionId | string |  |
| [].request | object |  |
| [].request.timestamp | integer | milliseconds that have elapsed since the UNIX epoch |
| [].request.params | object |  |
| [].request.rawBody | string |  |
| [].response | object |  |
| [].response.timestamp | integer | milliseconds that have elapsed since the UNIX epoch |
| [].response.result | object |  |
| [].response.rawBody | string |  |
| [].timestamp | integer | milliseconds that have elapsed since the UNIX epoch |
| [].frameId | string |  |
| [].loaderId | string |  |

# 读取会话录像

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 200 [#http-200]

The request has succeeded.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string |  |
| [].data | object | See [rrweb documentation](https://github.com/rrweb-io/rrweb/blob/master/docs/recipes/dive-into-event.md). |
| [].sessionId | string |  |
| [].timestamp | integer | milliseconds that have elapsed since the UNIX epoch |
| [].type | integer |  |

# 创建登录态

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 201 [#http-201]

The request has succeeded and a new resource has been created as a result.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| publicKey | string | The public key to encrypt the user-data-directory. |
| cipherAlgorithm | string | The cipher algorithm used to encrypt the user-data-directory. AES-256-CBC is currently the only supported algorithm. |
| initializationVectorSize | integer | The initialization vector size used to encrypt the user-data-directory. [Read more about how to use it](/features/contexts). |

# 读取登录态

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

## 响应 [#响应]

### HTTP 200 [#http-200]

The request has succeeded.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string |  |
| createdAt | string |  |
| updatedAt | string |  |
| projectId | string | The Project ID linked to the uploaded Context. |
| name | string | Optional user-defined name for the Context. Leading and trailing whitespace is trimmed before storage. Names are unique within the project among active Contexts, compared case-insensitively. |

# 删除登录态

[连接与使用指南](/docs/cloud/services/browser)

代理、反检测、扩展和 Selenium 不可用。region 和 solveCaptchas 接受但忽略；不提供区域选择或验证码代解。

此接口返回 200 和 JSON 确认；Browserbase 官方为 204。

## 响应 [#响应]

### HTTP 200 [#http-200]

Context deleted. Praxis returns JSON instead of Browserbase's 204.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| deleted | boolean |  |

# Cloudflare API

（待译）

Cloudflare Workers-compatible face of Application: the official cloudflare SDK paths for Workers, versions, deployments and static assets. Concepts, differences and limits are described under the Application tag.

## 基础地址 [#基础地址]

## 鉴权 [#鉴权]

Authorization: Bearer \<PRAXIS\_API\_KEY>

## 端点 [#端点]

* [列出 Worker](/docs/api/compatible/cloudflare/listWorkers) — `GET /cloudflare/client/v4/accounts/{account_id}/workers/workers`
* [创建 Worker](/docs/api/compatible/cloudflare/createWorker) — `POST /cloudflare/client/v4/accounts/{account_id}/workers/workers`
* [获取 Worker](/docs/api/compatible/cloudflare/getWorker) — `GET /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}`
* [更新 Worker](/docs/api/compatible/cloudflare/updateWorker) — `PUT /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}`
* [编辑 Worker](/docs/api/compatible/cloudflare/editWorker) — `PATCH /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}`
* [删除 Worker](/docs/api/compatible/cloudflare/deleteWorker) — `DELETE /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}`
* [列出版本](/docs/api/compatible/cloudflare/listVersions) — `GET /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}/versions`
* [创建版本](/docs/api/compatible/cloudflare/createVersion) — `POST /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}/versions`
* [获取版本](/docs/api/compatible/cloudflare/getVersion) — `GET /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}/versions/{version_id}`
* [列出部署](/docs/api/compatible/cloudflare/listDeployments) — `GET /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}/deployments`
* [创建部署](/docs/api/compatible/cloudflare/createDeployment) — `POST /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}/deployments`
* [获取部署](/docs/api/compatible/cloudflare/getDeployment) — `GET /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}/deployments/{deployment_id}`
* [获取账号子域](/docs/api/compatible/cloudflare/getSubdomain) — `GET /cloudflare/client/v4/accounts/{account_id}/workers/subdomain`
* [修改账号子域](/docs/api/compatible/cloudflare/putSubdomain) — `PUT /cloudflare/client/v4/accounts/{account_id}/workers/subdomain`
* [创建静态资源上传会话](/docs/api/compatible/cloudflare/createAssetUploadSession) — `POST /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}/assets-upload-session`
* [上传静态资源](/docs/api/compatible/cloudflare/uploadAssets) — `POST /cloudflare/client/v4/accounts/{account_id}/workers/assets/upload`
* [旧版脚本上传（未支持）](/docs/api/compatible/cloudflare/uploadScriptLegacy) — `PUT /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}`

# 

`GET /cloudflare/client/v4/accounts/{account_id}/workers/workers`

List Workers. order and order\_by are accepted and ignored.

**支持状态: partial**

List Workers. order and order\_by are accepted and ignored.

## 参数 [#参数]

| 名称          | 位置    | 类型      | 必填    | 说明                                              |
| ----------- | ----- | ------- | ----- | ----------------------------------------------- |
| account\_id | path  | string  | true  | Any value; your account comes from the API key. |
| page        | query | integer | false | Page number, from 1.                            |
| per\_page   | query | integer | false | Items per page (default 20).                    |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | array&lt;object&gt; | Workers. |
| result[].id | string | Worker ID, prefixed wkr_. |
| result[].name | string | Unique per account; lowercase letters, digits and single hyphens. |
| result[].subdomain | object | Public address of the Worker. |
| result[].tags | array&lt;string&gt; | Up to 8 tags. |
| result[].observability | object | Observability settings. |
| result[].logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| result[].created_on | string | When the Worker was created. |
| result[].updated_on | string | When the Worker last changed. |
| result[].deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| result[].praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 创建 Worker

`POST /cloudflare/client/v4/accounts/{account_id}/workers/workers`

Create a Worker.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                                              |
| ----------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id | path | string | true | Any value; your account comes from the API key. |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                    | 类型             | 说明                                                                                                                                                                                                                                                     |
| --------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| name                  | string         | Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved. |
| tags                  | array\<string> | Up to 8 tags.                                                                                                                                                                                                                                          |
| observability         | object         | Observability settings.                                                                                                                                                                                                                                |
| observability.enabled | boolean        | Collect logs.                                                                                                                                                                                                                                          |
| subdomain             | object         | Subdomain settings.                                                                                                                                                                                                                                    |
| subdomain.enabled     | boolean        | Serve the Worker on its public subdomain (default true).                                                                                                                                                                                               |
| praxis                | object         | Praxis settings.                                                                                                                                                                                                                                       |
| praxis.labels         | object         | Up to 16 labels.                                                                                                                                                                                                                                       |

```json
{
  "type": "object",
  "required": [
    "name"
  ],
  "properties": {
    "name": {
      "type": "string",
      "description": "Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved.",
      "pattern": "^(?!(?:www|api|admin|app|canary|canary-probe|status|docs|console)$)(?!.*--)[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$",
      "example": "my-app"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "maxItems": 8,
      "description": "Up to 8 tags."
    },
    "observability": {
      "type": "object",
      "description": "Observability settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Collect logs."
        }
      }
    },
    "subdomain": {
      "type": "object",
      "description": "Subdomain settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Serve the Worker on its public subdomain (default true)."
        }
      }
    },
    "praxis": {
      "type": "object",
      "description": "Praxis settings.",
      "required": [],
      "properties": {
        "labels": {
          "type": "object",
          "additionalProperties": {
            "type": "string"
          },
          "description": "Up to 16 labels."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.id | string | Worker ID, prefixed wkr_. |
| result.name | string | Unique per account; lowercase letters, digits and single hyphens. |
| result.subdomain | object | Public address of the Worker. |
| result.tags | array&lt;string&gt; | Up to 8 tags. |
| result.observability | object | Observability settings. |
| result.logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| result.created_on | string | When the Worker was created. |
| result.updated_on | string | When the Worker last changed. |
| result.deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| result.praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 获取 Worker

`GET /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}`

Get a Worker by ID or name.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                                              |
| ----------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id | path | string | true | Any value; your account comes from the API key. |
| worker\_id  | path | string | true | Worker ID or name.                              |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.id | string | Worker ID, prefixed wkr_. |
| result.name | string | Unique per account; lowercase letters, digits and single hyphens. |
| result.subdomain | object | Public address of the Worker. |
| result.tags | array&lt;string&gt; | Up to 8 tags. |
| result.observability | object | Observability settings. |
| result.logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| result.created_on | string | When the Worker was created. |
| result.updated_on | string | When the Worker last changed. |
| result.deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| result.praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 

`PUT /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}`

Update a Worker. Omitted fields stay unchanged (same as PATCH).

**支持状态: partial**

Update a Worker. Omitted fields stay unchanged (same as PATCH).

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                                              |
| ----------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id | path | string | true | Any value; your account comes from the API key. |
| worker\_id  | path | string | true | Worker ID or name.                              |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                    | 类型             | 说明                                                                                                                                                                                                                                                     |
| --------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| name                  | string         | Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved. |
| tags                  | array\<string> | Replaces the tags.                                                                                                                                                                                                                                     |
| observability         | object         | Observability settings.                                                                                                                                                                                                                                |
| observability.enabled | boolean        | Collect logs.                                                                                                                                                                                                                                          |
| subdomain             | object         | Subdomain settings.                                                                                                                                                                                                                                    |
| subdomain.enabled     | boolean        | Serve the Worker on its public subdomain.                                                                                                                                                                                                              |
| praxis                | object         | Praxis settings.                                                                                                                                                                                                                                       |
| praxis.labels         | object         | Replaces the labels.                                                                                                                                                                                                                                   |

```json
{
  "type": "object",
  "required": [],
  "properties": {
    "name": {
      "type": "string",
      "description": "Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved.",
      "pattern": "^(?!(?:www|api|admin|app|canary|canary-probe|status|docs|console)$)(?!.*--)[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$",
      "example": "my-app"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "maxItems": 8,
      "description": "Replaces the tags."
    },
    "observability": {
      "type": "object",
      "description": "Observability settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Collect logs."
        }
      }
    },
    "subdomain": {
      "type": "object",
      "description": "Subdomain settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Serve the Worker on its public subdomain."
        }
      }
    },
    "praxis": {
      "type": "object",
      "description": "Praxis settings.",
      "required": [],
      "properties": {
        "labels": {
          "type": "object",
          "additionalProperties": {
            "type": "string"
          },
          "description": "Replaces the labels."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.id | string | Worker ID, prefixed wkr_. |
| result.name | string | Unique per account; lowercase letters, digits and single hyphens. |
| result.subdomain | object | Public address of the Worker. |
| result.tags | array&lt;string&gt; | Up to 8 tags. |
| result.observability | object | Observability settings. |
| result.logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| result.created_on | string | When the Worker was created. |
| result.updated_on | string | When the Worker last changed. |
| result.deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| result.praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 编辑 Worker

`PATCH /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}`

Change some fields of a Worker.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                                              |
| ----------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id | path | string | true | Any value; your account comes from the API key. |
| worker\_id  | path | string | true | Worker ID or name.                              |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                    | 类型             | 说明                                                                                                                                                                                                                                                     |
| --------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| name                  | string         | Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved. |
| tags                  | array\<string> | Replaces the tags.                                                                                                                                                                                                                                     |
| observability         | object         | Observability settings.                                                                                                                                                                                                                                |
| observability.enabled | boolean        | Collect logs.                                                                                                                                                                                                                                          |
| subdomain             | object         | Subdomain settings.                                                                                                                                                                                                                                    |
| subdomain.enabled     | boolean        | Serve the Worker on its public subdomain.                                                                                                                                                                                                              |
| praxis                | object         | Praxis settings.                                                                                                                                                                                                                                       |
| praxis.labels         | object         | Replaces the labels.                                                                                                                                                                                                                                   |

```json
{
  "type": "object",
  "required": [],
  "properties": {
    "name": {
      "type": "string",
      "description": "Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved.",
      "pattern": "^(?!(?:www|api|admin|app|canary|canary-probe|status|docs|console)$)(?!.*--)[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$",
      "example": "my-app"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "maxItems": 8,
      "description": "Replaces the tags."
    },
    "observability": {
      "type": "object",
      "description": "Observability settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Collect logs."
        }
      }
    },
    "subdomain": {
      "type": "object",
      "description": "Subdomain settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Serve the Worker on its public subdomain."
        }
      }
    },
    "praxis": {
      "type": "object",
      "description": "Praxis settings.",
      "required": [],
      "properties": {
        "labels": {
          "type": "object",
          "additionalProperties": {
            "type": "string"
          },
          "description": "Replaces the labels."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.id | string | Worker ID, prefixed wkr_. |
| result.name | string | Unique per account; lowercase letters, digits and single hyphens. |
| result.subdomain | object | Public address of the Worker. |
| result.tags | array&lt;string&gt; | Up to 8 tags. |
| result.observability | object | Observability settings. |
| result.logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| result.created_on | string | When the Worker was created. |
| result.updated_on | string | When the Worker last changed. |
| result.deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| result.praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 删除 Worker

`DELETE /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}`

Delete a Worker. It can be restored on the native API for 7 days. force is accepted and ignored.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                                              |
| ----------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id | path | string | true | Any value; your account comes from the API key. |
| worker\_id  | path | string | true | Worker ID or name.                              |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | null | No result. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 列出版本

`GET /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}/versions`

List versions, newest first.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置    | 类型      | 必填    | 说明                                              |
| ----------- | ----- | ------- | ----- | ----------------------------------------------- |
| account\_id | path  | string  | true  | Any value; your account comes from the API key. |
| worker\_id  | path  | string  | true  | Worker ID or name.                              |
| page        | query | integer | false | Page number, from 1.                            |
| per\_page   | query | integer | false | Items per page (default 20).                    |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | array&lt;object&gt; | Versions. |
| result[].id | string | Version ID, prefixed ver_. |
| result[].number | integer | Per-Worker counter (v1, v2, …). |
| result[].created_on | string | When the version was created. |
| result[].main_module | string &#124; null | Entry module name, or null for a version containing only static assets. |
| result[].modules | array&lt;object&gt; | Module names and types; content is never returned. |
| result[].compatibility_date | string | Workers runtime compatibility date. |
| result[].compatibility_flags | array&lt;string&gt; | Runtime compatibility flags. |
| result[].bindings | array&lt;object&gt; | Bindings; secret values are never returned. |
| result[].assets | object &#124; null | Static asset settings. |
| result[].annotations | object | Free-form annotations. |
| result[].author_id | string &#124; null | Who created the version. |
| result[].source | string | Upload origin, e.g. api or sdk. |
| result[].urls | array&lt;string&gt; | Preview URLs of this version. |
| result[].praxis | object | Platform fields: owning Worker, build source, script size and asset manifest summary. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 

`POST /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}/versions`

Upload a version. With deploy=true a deployment starts as well. Static assets are declared with assets.manifest; triggers, migrations, containers and placement are refused.

**支持状态: partial**

Upload a version. With deploy=true a deployment starts as well. Static assets are declared with assets.manifest; triggers, migrations, containers and placement are refused.

## 参数 [#参数]

| 名称          | 位置    | 类型      | 必填    | 说明                                              |
| ----------- | ----- | ------- | ----- | ----------------------------------------------- |
| account\_id | path  | string  | true  | Any value; your account comes from the API key. |
| worker\_id  | path  | string  | true  | Worker ID or name.                              |
| deploy      | query | boolean | false | Also deploy this version.                       |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                          | 类型             | 说明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| --------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| deploy                      | boolean        | Also create a deployment of this version (own face only; on the compatible face use the deploy query parameter).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| main\_module                | string         | Entry module name; must equal the name of one of modules. Defaults to the first module; omit it when there are no modules.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| modules                     | array\<object> | Inline modules.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| modules\[].name             | string         | Module file name.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| modules\[].content\_type    | string         | Module content type: application/javascript+module, text/javascript, application/javascript, application/wasm, text/plain, application/octet-stream, application/json or application/x-python. Omit it to use application/javascript+module.                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| modules\[].content\_base64  | string         | Module content, base64.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| compatibility\_date         | string         | Workers runtime compatibility date: a real date in YYYY-MM-DD form, not later than today (UTC). Defaults to today (UTC).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| compatibility\_flags        | array\<string> | Runtime compatibility flags.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| bindings                    | array\<object> | Bindings of this version.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| bindings\[].type            | string         | Binding type; see the binding description for what each needs and which are unavailable.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| bindings\[].name            | string         | Name of the binding in the Worker's env: 1–64 letters, digits or underscores, not starting with a digit; unique within a version.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| assets                      | object         | Static assets. Pass either manifest (every file already uploaded through an upload session) or jwt (the completion token from the last upload batch), not both.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| assets.config               | object         | Routing settings for the static assets.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| assets.manifest             | object         | Map of static file path to content hash and byte size. Paths start with /; the same hash must declare the same size. The root paths /\_headers and /\_redirects are response-header and redirect rule files and are not served as assets; same-named files in subdirectories are ordinary assets. \_headers allows at most 100 rules and 2000 characters per line (whitespace included); \_redirects allows at most 2000 static and 100 dynamic rules and 1000 characters per rule (whitespace included), and rules after the first dynamic rule count toward the dynamic quota. Exceeding a limit makes CreateVersion return INVALID\_PARAMS, with violations.field pointing at the manifest entry. |
| assets.jwt                  | string         | Completion token from the last assets/upload batch; it carries this version's manifest, so do not also pass manifest.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| annotations                 | object         | Free-form annotations.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| annotations.workers/message | string         | Version message.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| annotations.workers/tag     | string         | Version tag.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| praxis                      | object         | Praxis settings.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| praxis.source               | object         | Build source: \{type:inline}, \{type:machine, path} or \{type:file, file\_id}.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |

```json
{
  "type": "object",
  "required": [],
  "properties": {
    "deploy": {
      "type": "boolean",
      "description": "Also create a deployment of this version (own face only; on the compatible face use the deploy query parameter)."
    },
    "main_module": {
      "type": "string",
      "description": "Entry module name; must equal the name of one of modules. Defaults to the first module; omit it when there are no modules.",
      "example": "index.js"
    },
    "modules": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/cloudflare-Module"
      },
      "description": "Inline modules."
    },
    "compatibility_date": {
      "type": "string",
      "description": "Workers runtime compatibility date: a real date in YYYY-MM-DD form, not later than today (UTC). Defaults to today (UTC).",
      "format": "date",
      "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
      "example": "2026-01-01"
    },
    "compatibility_flags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "description": "Runtime compatibility flags."
    },
    "bindings": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/cloudflare-Binding"
      },
      "description": "Bindings of this version."
    },
    "assets": {
      "type": "object",
      "description": "Static assets. Pass either manifest (every file already uploaded through an upload session) or jwt (the completion token from the last upload batch), not both.",
      "required": [],
      "properties": {
        "config": {
          "$ref": "#/components/schemas/cloudflare-AssetsConfig",
          "description": "Routing settings for the static assets."
        },
        "manifest": {
          "$ref": "#/components/schemas/cloudflare-AssetManifest"
        },
        "jwt": {
          "type": "string",
          "description": "Completion token from the last assets/upload batch; it carries this version's manifest, so do not also pass manifest."
        }
      }
    },
    "annotations": {
      "type": "object",
      "description": "Free-form annotations.",
      "required": [],
      "properties": {
        "workers/message": {
          "type": "string",
          "description": "Version message."
        },
        "workers/tag": {
          "type": "string",
          "description": "Version tag."
        }
      }
    },
    "praxis": {
      "type": "object",
      "description": "Praxis settings.",
      "required": [],
      "properties": {
        "source": {
          "type": "object",
          "additionalProperties": true,
          "description": "Build source: {type:inline}, {type:machine, path} or {type:file, file_id}."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.id | string | Version ID, prefixed ver_. |
| result.number | integer | Per-Worker counter (v1, v2, …). |
| result.created_on | string | When the version was created. |
| result.main_module | string &#124; null | Entry module name, or null for a version containing only static assets. |
| result.modules | array&lt;object&gt; | Module names and types; content is never returned. |
| result.compatibility_date | string | Workers runtime compatibility date. |
| result.compatibility_flags | array&lt;string&gt; | Runtime compatibility flags. |
| result.bindings | array&lt;object&gt; | Bindings; secret values are never returned. |
| result.assets | object &#124; null | Static asset settings. |
| result.annotations | object | Free-form annotations. |
| result.author_id | string &#124; null | Who created the version. |
| result.source | string | Upload origin, e.g. api or sdk. |
| result.urls | array&lt;string&gt; | Preview URLs of this version. |
| result.praxis | object | Platform fields: owning Worker, build source, script size and asset manifest summary. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 获取版本

`GET /cloudflare/client/v4/accounts/{account_id}/workers/workers/{worker_id}/versions/{version_id}`

Get one version.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                                              |
| ----------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id | path | string | true | Any value; your account comes from the API key. |
| worker\_id  | path | string | true | Worker ID or name.                              |
| version\_id | path | string | true | Version ID.                                     |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.id | string | Version ID, prefixed ver_. |
| result.number | integer | Per-Worker counter (v1, v2, …). |
| result.created_on | string | When the version was created. |
| result.main_module | string &#124; null | Entry module name, or null for a version containing only static assets. |
| result.modules | array&lt;object&gt; | Module names and types; content is never returned. |
| result.compatibility_date | string | Workers runtime compatibility date. |
| result.compatibility_flags | array&lt;string&gt; | Runtime compatibility flags. |
| result.bindings | array&lt;object&gt; | Bindings; secret values are never returned. |
| result.assets | object &#124; null | Static asset settings. |
| result.annotations | object | Free-form annotations. |
| result.author_id | string &#124; null | Who created the version. |
| result.source | string | Upload origin, e.g. api or sdk. |
| result.urls | array&lt;string&gt; | Preview URLs of this version. |
| result.praxis | object | Platform fields: owning Worker, build source, script size and asset manifest summary. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 列出部署

`GET /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}/deployments`

List deployments of a Worker, newest first.

**支持状态: supported**

## 参数 [#参数]

| 名称           | 位置    | 类型      | 必填    | 说明                                              |
| ------------ | ----- | ------- | ----- | ----------------------------------------------- |
| account\_id  | path  | string  | true  | Any value; your account comes from the API key. |
| script\_name | path  | string  | true  | Worker name.                                    |
| page         | query | integer | false | Page number, from 1.                            |
| per\_page    | query | integer | false | Items per page (default 20).                    |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.deployments | array&lt;object&gt; | Deployments. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 

`POST /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}/deployments`

Deploy one version at 100 percent (no gradual rollout). Deployment is asynchronous; read praxis.status.

**支持状态: partial**

Deploy one version at 100 percent (no gradual rollout). Deployment is asynchronous; read praxis.status.

## 参数 [#参数]

| 名称           | 位置    | 类型      | 必填    | 说明                                                     |
| ------------ | ----- | ------- | ----- | ------------------------------------------------------ |
| account\_id  | path  | string  | true  | Any value; your account comes from the API key.        |
| script\_name | path  | string  | true  | Worker name.                                           |
| force        | query | boolean | false | Deploy even if the last deployment changed in between. |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                          | 类型             | 说明                                                                   |
| --------------------------- | -------------- | -------------------------------------------------------------------- |
| strategy                    | string         | Rollout strategy.                                                    |
| versions                    | array\<object> | Exactly one version at 100 percent.                                  |
| versions\[].version\_id     | string         | Version to deploy.                                                   |
| versions\[].percentage      | number         | Must be 100.                                                         |
| force                       | boolean        | Own face only; on the compatible face use the force query parameter. |
| annotations                 | object         | Free-form annotations.                                               |
| annotations.workers/message | string         | Deployment message.                                                  |

```json
{
  "type": "object",
  "required": [
    "strategy",
    "versions"
  ],
  "properties": {
    "strategy": {
      "type": "string",
      "description": "Rollout strategy.",
      "enum": [
        "percentage"
      ],
      "x-enum-descriptions": {
        "percentage": "Split traffic by percentage; only a single version at 100 is accepted."
      },
      "example": "percentage"
    },
    "versions": {
      "type": "array",
      "description": "Exactly one version at 100 percent.",
      "items": {
        "type": "object",
        "required": [
          "version_id",
          "percentage"
        ],
        "properties": {
          "version_id": {
            "type": "string",
            "description": "Version to deploy."
          },
          "percentage": {
            "type": "number",
            "description": "Must be 100."
          }
        }
      }
    },
    "force": {
      "type": "boolean",
      "description": "Own face only; on the compatible face use the force query parameter."
    },
    "annotations": {
      "type": "object",
      "description": "Free-form annotations.",
      "required": [],
      "properties": {
        "workers/message": {
          "type": "string",
          "description": "Deployment message."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.id | string | Deployment ID, prefixed dep_. |
| result.created_on | string | When the deployment was created. |
| result.source | string | Origin: api, sdk, console or rollback. |
| result.strategy | string | Rollout strategy. |
| result.versions | array&lt;object&gt; | Exactly one version at 100 percent. |
| result.annotations | object | Free-form annotations. |
| result.author_email | string &#124; null | Who created the deployment. |
| result.praxis | object | Platform fields: deployments run asynchronously, so track status, progress and error here. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 获取部署

`GET /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}/deployments/{deployment_id}`

Get one deployment.

**支持状态: supported**

## 参数 [#参数]

| 名称             | 位置   | 类型     | 必填   | 说明                                              |
| -------------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id    | path | string | true | Any value; your account comes from the API key. |
| script\_name   | path | string | true | Worker name.                                    |
| deployment\_id | path | string | true | Deployment ID.                                  |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.id | string | Deployment ID, prefixed dep_. |
| result.created_on | string | When the deployment was created. |
| result.source | string | Origin: api, sdk, console or rollback. |
| result.strategy | string | Rollout strategy. |
| result.versions | array&lt;object&gt; | Exactly one version at 100 percent. |
| result.annotations | object | Free-form annotations. |
| result.author_email | string &#124; null | Who created the deployment. |
| result.praxis | object | Platform fields: deployments run asynchronously, so track status, progress and error here. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 获取账号子域

`GET /cloudflare/client/v4/accounts/{account_id}/workers/subdomain`

Get the account subdomain.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                                              |
| ----------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id | path | string | true | Any value; your account comes from the API key. |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.subdomain | string | Account subdomain, 8–32 lowercase letters and digits; part of every Worker URL. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 修改账号子域

`PUT /cloudflare/client/v4/accounts/{account_id}/workers/subdomain`

Change the account subdomain.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                                              |
| ----------- | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id | path | string | true | Any value; your account comes from the API key. |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称        | 类型     | 说明                                                                              |
| --------- | ------ | ------------------------------------------------------------------------------- |
| subdomain | string | Account subdomain, 8–32 lowercase letters and digits; part of every Worker URL. |

```json
{
  "type": "object",
  "required": [
    "subdomain"
  ],
  "properties": {
    "subdomain": {
      "type": "string",
      "description": "Account subdomain, 8–32 lowercase letters and digits; part of every Worker URL.",
      "pattern": "^[a-z0-9]{8,32}$",
      "example": "acme1234"
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.subdomain | string | Account subdomain, 8–32 lowercase letters and digits; part of every Worker URL. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 创建静态资源上传会话

`POST /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}/assets-upload-session`

Declare the static file manifest; the answer lists missing hashes in batches and an upload token.

**支持状态: supported**

## 参数 [#参数]

| 名称           | 位置   | 类型     | 必填   | 说明                                              |
| ------------ | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id  | path | string | true | Any value; your account comes from the API key. |
| script\_name | path | string | true | Worker name.                                    |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称       | 类型     | 说明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| -------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| manifest | object | Map of static file path to content hash and byte size. Paths start with /; the same hash must declare the same size. The root paths /\_headers and /\_redirects are response-header and redirect rule files and are not served as assets; same-named files in subdirectories are ordinary assets. \_headers allows at most 100 rules and 2000 characters per line (whitespace included); \_redirects allows at most 2000 static and 100 dynamic rules and 1000 characters per rule (whitespace included), and rules after the first dynamic rule count toward the dynamic quota. Exceeding a limit makes CreateVersion return INVALID\_PARAMS, with violations.field pointing at the manifest entry. |

```json
{
  "type": "object",
  "required": [
    "manifest"
  ],
  "properties": {
    "manifest": {
      "$ref": "#/components/schemas/cloudflare-AssetManifest"
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.jwt | string | Upload token, valid for one hour. |
| result.buckets | array&lt;array&lt;string&gt;&gt; | Hashes still missing, grouped into upload batches. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 

`POST /cloudflare/client/v4/accounts/{account_id}/workers/assets/upload`

Upload one batch as multipart form fields (hash → content; base64 when base64=true). Send the upload token as Authorization: Bearer and your API key in X-API-Key. Earlier batches answer 202; the last answers 201 with the completion token.

**支持状态: partial**

Upload one batch as multipart form fields (hash → content; base64 when base64=true). Send the upload token as Authorization: Bearer and your API key in X-API-Key. Earlier batches answer 202; the last answers 201 with the completion token.

## 参数 [#参数]

| 名称          | 位置    | 类型      | 必填    | 说明                                              |
| ----------- | ----- | ------- | ----- | ----------------------------------------------- |
| account\_id | path  | string  | true  | Any value; your account comes from the API key. |
| base64      | query | boolean | false | Field values are base64.                        |

## 请求体 (multipart/form-data) [#请求体-multipartform-data]

必填: true

| 名称 | 类型 | 说明 |
| -- | -- | -- |

```json
{
  "type": "object",
  "additionalProperties": {
    "type": "string"
  },
  "description": "One form field per file: the field name is the hash, the value the content."
}
```

## 响应 [#响应]

### HTTP 201 [#http-201]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result.jwt | string &#124; null | Completion token after the last batch; null for earlier batches. |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

### HTTP 202 [#http-202]

Batch stored; more batches remain (no completion token yet).

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| success | boolean | Always true on success. |
| errors | array&lt;any&gt; | Always empty on success. |
| messages | array&lt;any&gt; | Always empty on success. |
| result | object |  |
| result_info | object | Present on list responses. |
| result_info.page | integer | Page number. |
| result_info.per_page | integer | Page size. |
| result_info.count | integer | Items on this page. |

# 

`PUT /cloudflare/client/v4/accounts/{account_id}/workers/scripts/{script_name}`

Not supported: answers 501. Use POST workers/workers and POST workers/workers/\{worker\_id}/versions?deploy=true.

**支持状态: unsupported**

Not supported: answers 501. Use POST workers/workers and POST workers/workers/\{worker\_id}/versions?deploy=true.

## 参数 [#参数]

| 名称           | 位置   | 类型     | 必填   | 说明                                              |
| ------------ | ---- | ------ | ---- | ----------------------------------------------- |
| account\_id  | path | string | true | Any value; your account comes from the API key. |
| script\_name | path | string | true | Worker name.                                    |

## 响应 [#响应]

此端点没有声明成功响应。

# 智能体 API

（待译）

Agent runs versioned agents and conversations through /agent/v1. Concepts and behavior follow Anthropic Managed Agents (agents, environments, sessions and events), so Anthropic Managed Agents experience applies. Differences: omitting environment\_id selects a light machine unless a Computer is selected, and self-hosted environments are unavailable; the native toolset includes codemode, Skill and subagents, while /anthropic/v1 sessions expose only the eight official tools; nonempty skills attachments and custom tools are rejected; native events include steering, withdrawal, notifications, forks and goals, with remembered permissions and question answers on approvals. Start with `praxis.agent.agents.create`, then open a session and read its events for the result.

## 基础地址 [#基础地址]

## 接入 [#接入]

智能体域的概念与整体介绍见[智能体服务](/docs/cloud/services/agent)；鉴权方式见[鉴权](/docs/api/authentication)。

## 端点 [#端点]

### 电脑（10 个端点，10 个可用） [#电脑10-个端点10-个可用]

| 方法     | 路径                                                                                                | 说明       | 支持   |
| ------ | ------------------------------------------------------------------------------------------------- | -------- | ---- |
| POST   | [`/v1/computers`](/docs/api/native/agent/createComputer)                                          | 创建电脑     | ● 支持 |
| GET    | [`/v1/computers`](/docs/api/native/agent/listComputers)                                           | 列出电脑     | ● 支持 |
| GET    | [`/v1/computers/{computer_id}`](/docs/api/native/agent/retrieveComputer)                          | 读取电脑     | ● 支持 |
| POST   | [`/v1/computers/{computer_id}`](/docs/api/native/agent/updateComputer)                            | 更新电脑     | ● 支持 |
| POST   | [`/v1/computers/{computer_id}/archive`](/docs/api/native/agent/archiveComputer)                   | 归档电脑     | ● 支持 |
| DELETE | [`/v1/computers/{computer_id}`](/docs/api/native/agent/deleteComputer)                            | 删除已归档电脑  | ● 支持 |
| GET    | [`/v1/computers/{computer_id}/files`](/docs/api/native/agent/listComputerFiles)                   | 浏览电脑文件   | ● 支持 |
| GET    | [`/v1/computers/{computer_id}/files/content`](/docs/api/native/agent/retrieveComputerFileContent) | 读取电脑文件内容 | ● 支持 |
| POST   | [`/v1/computers/{computer_id}/connect`](/docs/api/native/agent/connectComputer)                   | 连接电脑     | ● 支持 |
| POST   | [`/v1/computers/{computer_id}/attachments`](/docs/api/native/agent/createComputerAttachment)      | 上传电脑附件   | ● 支持 |

### 会话资源（4 个端点，4 个可用） [#会话资源4-个端点4-个可用]

| 方法     | 路径                                                                                                    | 说明     | 支持     |
| ------ | ----------------------------------------------------------------------------------------------------- | ------ | ------ |
| POST   | [`/v1/sessions/{session_id}/resources`](/docs/api/native/agent/addSessionResource)                    | 添加会话资源 | ◐ 部分支持 |
| GET    | [`/v1/sessions/{session_id}/resources`](/docs/api/native/agent/listSessionResources)                  | 列出会话资源 | ◐ 部分支持 |
| GET    | [`/v1/sessions/{session_id}/resources/{resource_id}`](/docs/api/native/agent/retrieveSessionResource) | 读取会话资源 | ◐ 部分支持 |
| DELETE | [`/v1/sessions/{session_id}/resources/{resource_id}`](/docs/api/native/agent/deleteSessionResource)   | 删除会话资源 | ◐ 部分支持 |

### 智能体（6 个端点，6 个可用） [#智能体6-个端点6-个可用]

| 方法   | 路径                                                                           | 说明    | 支持     |
| ---- | ---------------------------------------------------------------------------- | ----- | ------ |
| GET  | [`/v1/agents`](/docs/api/native/agent/listAgents)                            | 列出智能体 | ● 支持   |
| POST | [`/v1/agents`](/docs/api/native/agent/createAgent)                           | 创建智能体 | ◐ 部分支持 |
| GET  | [`/v1/agents/{agent_id}`](/docs/api/native/agent/retrieveAgent)              | 读取智能体 | ● 支持   |
| POST | [`/v1/agents/{agent_id}`](/docs/api/native/agent/updateAgent)                | 更新智能体 | ◐ 部分支持 |
| GET  | [`/v1/agents/{agent_id}/versions`](/docs/api/native/agent/listAgentVersions) | 列出版本  | ● 支持   |
| POST | [`/v1/agents/{agent_id}/archive`](/docs/api/native/agent/archiveAgent)       | 归档智能体 | ● 支持   |

### 会话与事件（16 个端点，16 个可用） [#会话与事件16-个端点16-个可用]

| 方法   | 路径                                                                                                                     | 说明           | 支持     |
| ---- | ---------------------------------------------------------------------------------------------------------------------- | ------------ | ------ |
| GET  | [`/v1/sessions`](/docs/api/native/agent/listSessions)                                                                  | 列出会话         | ◐ 部分支持 |
| POST | [`/v1/sessions`](/docs/api/native/agent/createSession)                                                                 | 创建会话         | ◐ 部分支持 |
| GET  | [`/v1/sessions/{session_id}`](/docs/api/native/agent/retrieveSession)                                                  | 读取会话         | ● 支持   |
| POST | [`/v1/sessions/{session_id}/fork`](/docs/api/native/agent/forkSession)                                                 | 分支会话（扩展）     | ● 支持   |
| GET  | [`/v1/sessions/{session_id}/context`](/docs/api/native/agent/getSessionContext)                                        | 读取会话上下文（扩展）  | ● 支持   |
| GET  | [`/v1/sessions/{session_id}/background_tasks`](/docs/api/native/agent/listSessionBackgroundTasks)                      | 列出后台任务（扩展）   | ● 支持   |
| GET  | [`/v1/sessions/{session_id}/background_tasks/{task_id}/output`](/docs/api/native/agent/getSessionBackgroundTaskOutput) | 读取后台任务输出（扩展） | ● 支持   |
| POST | [`/v1/sessions/{session_id}/background_tasks/{task_id}/stop`](/docs/api/native/agent/stopSessionBackgroundTask)        | 停止后台任务（扩展）   | ● 支持   |
| POST | [`/v1/sessions/{session_id}/compact`](/docs/api/native/agent/compactSession)                                           | 压缩会话（扩展）     | ● 支持   |
| GET  | [`/v1/sessions/{session_id}/compact/{operation_id}`](/docs/api/native/agent/getSessionCompaction)                      | 读取压缩操作（扩展）   | ● 支持   |
| GET  | [`/v1/sessions/{session_id}/compactions`](/docs/api/native/agent/listSessionCompactions)                               | 列出压缩历史（扩展）   | ● 支持   |
| GET  | [`/v1/sessions/{session_id}/events`](/docs/api/native/agent/listEvents)                                                | 列出事件         | ● 支持   |
| POST | [`/v1/sessions/{session_id}/events`](/docs/api/native/agent/sendEvents)                                                | 发送事件         | ◐ 部分支持 |
| GET  | [`/v1/sessions/{session_id}/events/stream`](/docs/api/native/agent/streamEvents)                                       | 订阅事件         | ◐ 部分支持 |
| POST | [`/v1/sessions/{session_id}`](/docs/api/native/agent/updateSession)                                                    | 更新会话         | ◐ 部分支持 |
| POST | [`/v1/sessions/{session_id}/archive`](/docs/api/native/agent/archiveSession)                                           | 归档会话         | ● 支持   |

### 会话线程（5 个端点，5 个可用） [#会话线程5-个端点5-个可用]

| 方法   | 路径                                                                                                         | 说明     | 支持     |
| ---- | ---------------------------------------------------------------------------------------------------------- | ------ | ------ |
| GET  | [`/v1/sessions/{session_id}/threads`](/docs/api/native/agent/listSessionThreads)                           | 列出线程   | ◐ 部分支持 |
| GET  | [`/v1/sessions/{session_id}/threads/{thread_id}`](/docs/api/native/agent/retrieveSessionThread)            | 读取线程   | ◐ 部分支持 |
| GET  | [`/v1/sessions/{session_id}/threads/{thread_id}/events`](/docs/api/native/agent/listSessionThreadEvents)   | 列出线程事件 | ◐ 部分支持 |
| GET  | [`/v1/sessions/{session_id}/threads/{thread_id}/stream`](/docs/api/native/agent/streamSessionThreadEvents) | 订阅线程事件 | ◐ 部分支持 |
| POST | [`/v1/sessions/{session_id}/threads/{thread_id}/archive`](/docs/api/native/agent/archiveSessionThread)     | 归档线程   | ◐ 部分支持 |

### 执行环境（5 个端点，5 个可用） [#执行环境5-个端点5-个可用]

| 方法   | 路径                                                                                       | 说明   | 支持     |
| ---- | ---------------------------------------------------------------------------------------- | ---- | ------ |
| POST | [`/v1/environments`](/docs/api/native/agent/createEnvironment)                           | 创建环境 | ◐ 部分支持 |
| POST | [`/v1/environments/{environment_id}`](/docs/api/native/agent/updateEnvironment)          | 更新环境 | ◐ 部分支持 |
| POST | [`/v1/environments/{environment_id}/archive`](/docs/api/native/agent/archiveEnvironment) | 归档环境 | ◐ 部分支持 |
| GET  | [`/v1/environments`](/docs/api/native/agent/listEnvironments)                            | 列出环境 | ◐ 部分支持 |
| GET  | [`/v1/environments/{environment_id}`](/docs/api/native/agent/retrieveEnvironment)        | 读取环境 | ◐ 部分支持 |

### 工具集（1 个端点，1 个可用） [#工具集1-个端点1-个可用]

| 方法  | 路径                                                    | 说明    | 支持   |
| --- | ----------------------------------------------------- | ----- | ---- |
| GET | [`/v1/toolsets`](/docs/api/native/agent/listToolsets) | 列出工具集 | ● 支持 |

## 与官方的差异 [#与官方的差异]

* 本面只声明列出的 30 个端点（含工具集目录、上下文快照、压缩操作与后台任务）：官方其余 Managed Agents 操作不在本面，调用得到 404。需要 Anthropic 协议兼容接入时用兼容面 /anthropic —— 官方有、平台未支持的操作在那里如实返回 501（not\_implemented\_error），不产生任何副作用。
* <a href="/docs/api/native/agent/createEnvironment">创建环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/native/agent/updateEnvironment">更新环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/native/agent/archiveEnvironment">归档环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/native/agent/createComputer">创建电脑</a>：Praxis 超集：MA 只有会话级临时容器与 memory\_stores，没有可长期存续、可浏览的整台电脑。归档后文件仍可读，但不能用于新会话。environment\_id 是可空配方引用；电脑默认使用 light sandbox，sandbox\_id 为 SDK 可用的公开 ID。分页包含归档电脑。
* <a href="/docs/api/native/agent/listComputers">列出电脑</a>：Praxis 超集：MA 只有会话级临时容器与 memory\_stores，没有可长期存续、可浏览的整台电脑。归档后文件仍可读，但不能用于新会话。environment\_id 是可空配方引用；电脑默认使用 light sandbox，sandbox\_id 为 SDK 可用的公开 ID。分页包含归档电脑。
* <a href="/docs/api/native/agent/retrieveComputer">读取电脑</a>：Praxis 超集：MA 只有会话级临时容器与 memory\_stores，没有可长期存续、可浏览的整台电脑。归档后文件仍可读，但不能用于新会话。environment\_id 是可空配方引用；电脑默认使用 light sandbox，sandbox\_id 为 SDK 可用的公开 ID。分页包含归档电脑。
* <a href="/docs/api/native/agent/updateComputer">更新电脑</a>：Praxis 超集：MA 只有会话级临时容器与 memory\_stores，没有可长期存续、可浏览的整台电脑。归档后文件仍可读，但不能用于新会话。environment\_id 是可空配方引用；电脑默认使用 light sandbox，sandbox\_id 为 SDK 可用的公开 ID。分页包含归档电脑。
* <a href="/docs/api/native/agent/archiveComputer">归档电脑</a>：Praxis 超集：MA 只有会话级临时容器与 memory\_stores，没有可长期存续、可浏览的整台电脑。归档后文件仍可读，但不能用于新会话。environment\_id 是可空配方引用；电脑默认使用 light sandbox，sandbox\_id 为 SDK 可用的公开 ID。分页包含归档电脑。
* <a href="/docs/api/native/agent/deleteComputer">删除已归档电脑</a>：Praxis 扩展：Managed Agents 没有持久 Computer 的删除生命周期。仅允许已归档的电脑；active 返回 400 COMPUTER\_ACTIVE（先归档），先销毁电脑数据再删除登记，成功返回 id 和 type=computer\_deleted；不存在或跨租户返回 404。
* <a href="/docs/api/native/agent/listComputerFiles">浏览电脑文件</a>：Praxis 超集：MA 只有会话级临时容器与 memory\_stores，没有可长期存续、可浏览的整台电脑。归档后文件仍可读，但不能用于新会话。environment\_id 是可空配方引用；电脑默认使用 light sandbox，sandbox\_id 为 SDK 可用的公开 ID。分页包含归档电脑。
* <a href="/docs/api/native/agent/retrieveComputerFileContent">读取电脑文件内容</a>：Praxis 超集：MA 只有会话级临时容器与 memory\_stores，没有可长期存续、可浏览的整台电脑。归档后文件仍可读，但不能用于新会话。environment\_id 是可空配方引用；电脑默认使用 light sandbox，sandbox\_id 为 SDK 可用的公开 ID。分页包含归档电脑。
* <a href="/docs/api/native/agent/connectComputer">连接电脑</a>：Praxis 自有扩展：Managed Agents 没有持久 Computer 连接。返回 SDK 可用的公开 sandbox\_id、envd\_access\_token 和 template\_id。归档电脑仍可连接；跨租户或不存在返回 404。连接凭证不可缓存。
* <a href="/docs/api/native/agent/createComputerAttachment">上传电脑附件</a>：Praxis 扩展：Managed Agents 没有持久 Computer 附件目录。用户上传可以覆盖同名附件，智能体始终只读；运行令牌调用上传返回 403 READ\_ONLY。name 是单个文件名、最多 255 UTF-8 字节，MIME 始终按扩展名推断，上传的 Content-Type 不持久保存，digest 可省略。上限 16 MiB，超限 413、非法名字 400；归档电脑也可上传，跨租户 404。
* <a href="/docs/api/native/agent/addSessionResource">添加会话资源</a>：支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/native/agent/listSessionResources">列出会话资源</a>：支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/native/agent/retrieveSessionResource">读取会话资源</a>：支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/native/agent/deleteSessionResource">删除会话资源</a>：支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/native/agent/createAgent">创建智能体</a>：agent\_toolset\_20260401 是原生工具集，包含 bash、edit、glob、grep、read、write、web\_search、web\_fetch，以及 TaskOutput、TaskStop、Monitor、Agent、SendMessage。新建智能体默认全部启用；configs 可逐个设置 name、enabled、permission\_policy，未列出的工具遵循 default\_config（默认启用）。后台任务、Monitor 和子智能体依赖 bash；启用任一后台工具时，bash 提供 run\_in\_background。兼容 API /anthropic 只接受和返回官方 8 个工具，经该入口创建的会话也只注册这 8 个工具。 支持文本提示词、模型、元数据与内置工具。model.settings.reasoning 可选 low、medium、high、xhigh、none，为会话提供默认思考档位；会话显式 thinking 优先，不支持的默认值回退到模型 default\_effort。示例 model: \{id: "deepseek-v4-flash", settings: \{reasoning: "high"}}。Skills 及其它额外模型控制尚不支持，传入会返回 400。可在工具集 permissions 中设置 allow、ask、deny 规则，最多共 100 条，用于以后的对话。 multiagent 接受 null 或 coordinator 名册，1–20 项：智能体 ID、\{type:"agent",id,version?} 或最多一个 \{type:"self"}。创建/更新时固定版本；成员去重且须存在、未归档、不能自身带 multiagent。名册可启用 Agent，仍需启用 bash；SendMessage 遵循工具配置。每个 coordinator 最多一个 advisor，模型须可用且不同于智能体模型；仅主会话可咨询，每次咨询为独立 advisor 线程，建议以 agent.thread\_message\_received 返回。 /agent/v1 顶层 subagent\_model 是可空模型 ID，随智能体版本保存；省略保留、null 清除。模型须存在。优先级为调用 model > subagent\_model > 成员模型（内置类型用父会话模型）。/anthropic 不接受或返回此字段。
* <a href="/docs/api/native/agent/retrieveAgent">读取智能体</a>：tools 在一个 agent\_toolset\_20260401 条目中返回全部原生工具的有效配置，可原样用于更新。将示例中的资源 ID 替换成你创建的资源 ID。
* <a href="/docs/api/native/agent/updateAgent">更新智能体</a>：通过 agent\_toolset\_20260401.configs 逐个开关原生工具并设置权限。未列出的工具遵循 default\_config；后台任务、Monitor 和子智能体依赖 bash。version 可用于乐观并发控制，版本冲突返回 409；无变化的更新不增加版本。Skills 尚不支持。更新工具集 permissions 可把允许的同类操作保存到智能体的新版本，供以后的对话使用。 multiagent 接受 null 或 coordinator 名册，1–20 项：智能体 ID、\{type:"agent",id,version?} 或最多一个 \{type:"self"}。创建/更新时固定版本；成员去重且须存在、未归档、不能自身带 multiagent。名册可启用 Agent，仍需启用 bash；SendMessage 遵循工具配置。每个 coordinator 最多一个 advisor，模型须可用且不同于智能体模型；仅主会话可咨询，每次咨询为独立 advisor 线程，建议以 agent.thread\_message\_received 返回。 /agent/v1 顶层 subagent\_model 是可空模型 ID，随智能体版本保存；省略保留、null 清除。模型须存在。优先级为调用 model > subagent\_model > 成员模型（内置类型用父会话模型）。/anthropic 不接受或返回此字段。
* <a href="/docs/api/native/agent/listAgentVersions">列出版本</a>：将示例中的资源 ID 替换成你创建的资源 ID。
* <a href="/docs/api/native/agent/archiveAgent">归档智能体</a>：归档后保留查询与历史版本，不能继续更新。请只归档自己的测试智能体。
* <a href="/docs/api/native/agent/listSessions">列出会话</a>：支持 limit、page 与 agent\_id；agent\_version、时间范围、deployment\_id、memory\_store\_id、include\_archived、order、statuses 尚不支持，传入返回 400。
* <a href="/docs/api/native/agent/createSession">创建会话</a>：可在创建时传 model（models.allowed 内的 ID 字符串；无 allowed 时只允许默认模型）与 thinking（\{effort: "low|medium|high|xhigh|none"} 或 null），在首条 initial\_events 执行前保存。省略或 null 继承智能体默认，再使用模型默认。档位必须在 model.thinking.efforts 内；none 要求 can\_disable 为 true，否则返回 400 invalid\_request\_error。响应包含 thinking 与 model.thinking: \{efforts, can\_disable, default\_effort}；未知能力为 null，默认档位也可为 null。示例：\{"agent":"agent\_123","model":"deepseek-v4-flash","thinking":\{"effort":"xhigh"}}。这些选择字段只在 /agent/v1 提供。先创建智能体，将示例 agent\_123 换成返回的 id。省略 environment\_id 得到轻量机器（light），有默认或显式 computer\_id 时使用该 Computer；指定 node22 或租户自建 cloud 环境则使用沙箱配方。无配方时响应省略 environment\_id。不支持内联智能体覆盖、预算与凭据库。支持 file 类型资源的持久化、查询和解除关联，单会话最多 500 条。文件须属于当前租户且有效。默认路径为 /mnt/session/uploads/\<file\_id>，自定义路径归一到该目录，拒绝父目录遍历。不修改文件内容；本批尚不将资源同步到沙箱。
* <a href="/docs/api/native/agent/retrieveSession">读取会话</a>：将示例中的资源 ID 替换成你创建的资源 ID。
* <a href="/docs/api/native/agent/forkSession">分支会话（扩展）</a>：仅在 /agent/v1 提供。message\_id 来自 /agent/v1 事件的同名字段，不是事件 id。复制截至并包含该消息的全部对话与工具调用结果；父会话不变，其他轮次正在运行不影响已有完成轮次的分支。新会话沿用智能体及版本、当前模型与思考设置和 cwd 工作目录，标题为父标题加「 的分支」，作为普通根会话出现在列表中。父会话有沙箱时复制沙箱及内存快照，新会话独立拥有该沙箱；继承的运行中后台任务被终止，门铃目标只保留新会话，新后台任务表为空。父会话没有沙箱时保留懒创建。返回 201，响应与读取会话相同，forked\_from 为 \{session\_id, message\_id}，普通会话为 null。新会话历史末尾有 session.forked 事件，包含 forked\_from\_session\_id 与 forked\_from\_message\_id。上述字段和事件仅在 /agent/v1 可见。非法请求返回 400；不满足分支条件返回 409 FORK\_TARGET\_INVALID；会话不存在或不属于调用者返回 404。初始化失败时不公开新会话，并回收已分出的沙箱。
* <a href="/docs/api/native/agent/getSessionContext">读取会话上下文（扩展）</a>：扩展：仅在 /agent/v1 提供，形状参照 Claude Agent SDK getContextUsage()，字段使用 snake\_case。detail 固定为 summary：总量优先使用上次模型实测，各来源按本地估算占比摊分，used 分类之和等于 total\_tokens。categories 只列非零来源，按 kind（used/free/buffer/deferred）判断用途。key 是稳定来源标识扩展；客户端须容忍未知 key 和新增来源，未知名称回退显示 name。MCP 按服务器归组，插件按 id 归组，摘要单独计量。excluded\_items 暂为零。尚无测量时 total\_tokens、total\_tokens\_source、measured\_at 为 null，categories 为空，明细为零或空数组。切换模型后 max\_tokens、auto\_compact\_threshold 与 free/buffer 立即按新模型重算，保留最近测量值。窗口未知或自动压缩熔断时 is\_auto\_compact\_enabled 为 false。例如 model.thinking 为 \{efforts: \[high, xhigh], can\_disable: true, default\_effort: high}。model.thinking 返回 efforts（支持的档位）、can\_disable（是否允许 none）及 default\_effort（模型默认档位，可为 null）；能力未知时整个 thinking 为 null。会话不存在或调用者不可见时返回 404。
* <a href="/docs/api/native/agent/listSessionBackgroundTasks">列出后台任务（扩展）</a>：仅在 /agent/v1 提供。kind 是开放字符串。subagent 行的 thread\_id 指向对应子线程，其他 kind 为 null。completed 且 delivery=pending 显示 result\_pending。notified\_at 是系统通知批次被受理开轮的时间，无则 null。trigger\_count 仅监视器返回已受理的事件批次数，无记录则 null。时间为 RFC3339。会话不存在或不可见返回 404。
* <a href="/docs/api/native/agent/getSessionBackgroundTaskOutput">读取后台任务输出（扩展）</a>：offset 默认 0；max\_bytes 默认 65536，上限 262144。返回 text、next\_offset、eof。沙箱已暂停或不存在时返回空 text、原 offset、eof=true、unavailable=true。读取不确认模型结果。
* <a href="/docs/api/native/agent/stopSessionBackgroundTask">停止后台任务（扩展）</a>：复用 TaskStop：持久化 stop\_requested\_at 并终止进程组。返回 BackgroundTask；终止尚未观察到时仍可为 running，但不可取消。已结束或不支持停止的任务返回 409。
* <a href="/docs/api/native/agent/compactSession">压缩会话（扩展）</a>：仅在 /agent/v1 提供。请求体可省略或为 \{}，可选 instructions 必须为字符串且原样传递。Idempotency-Key 请求头原样传递；缺失时生成 UUID。响应为 \{ type: session\_compaction, id, status, reason? }，id 是操作 ID。queued/running 返回 202；skipped/succeeded/failed 返回 200。非字符串 instructions 返回 400 invalid\_request\_error。不存在或不可见的托管会话返回 404 not\_found\_error。
* <a href="/docs/api/native/agent/getSessionCompaction">读取压缩操作（扩展）</a>：仅在 /agent/v1 提供。响应为 \{ type: session\_compaction, id, status, reason? }，所有状态均返回 200。操作不存在或会话不可见时返回 404 not\_found\_error。
* <a href="/docs/api/native/agent/listSessionCompactions">列出压缩历史（扩展）</a>：仅在 /agent/v1 提供。返回 \{ data: \[...] }。每项包含 type、id、event\_id、trigger、status、model、compacted\_message\_count、input\_tokens\_before、input\_tokens\_after、summary、error、created\_at，字段按服务记录原样返回。不存在或不可见的托管会话返回 404 not\_found\_error。
* <a href="/docs/api/native/agent/listEvents">列出事件</a>：先发送消息再读取历史；处理完成前可能只看到已接纳的输入。支持分页、事件类型和时间过滤。会话等待工具授权时停在 session.status\_idle，stop\_reason 为 requires\_action，event\_ids 列出待确认的 agent.tool\_use；运行失败时先出现 session.error，再出现 session.status\_terminated。agent.thinking 带思考内容 content。使用网页搜索或读取网页时，/agent/v1 与 /anthropic 的工具结果均为官方 search\_result 块；回答文本块的 citations 是 /agent/v1 的扩展字段，/anthropic 将回答引用显示为正文中的 \[n]。
* <a href="/docs/api/native/agent/sendEvents">发送事件</a>：将 sesn\_123 换成创建会话返回的 id。每条 user.message 只接受一个非空文本块。支持文本 user.message、user.interrupt 和工具确认；可发送 user.withdraw 并用 event\_id 指向仍在排队的消息来撤回它，消息已开始处理时返回 409。运行中需要提前补充要求时，发送 user.steer 事件，并用 event\_id 指向仍在排队的消息：当前工具继续执行，消息在下一次模型请求前进入当前回合。返回带 processed\_at 的 user.steer 回执，重复标记返回同一回执；已开始或已撤回返回 409，事件不存在返回 404。有待授权时继续等待；若当前回合先结束，消息仍按普通队列处理。默认发送消息仍然排队，/anthropic 不接受 user.steer。其它事件变体尚不支持。返回的是已接纳事件；模型回复从事件历史或订阅读取。会话等待工具授权时发送的 user.message 会排队：返回的事件 processed\_at 为 null，授权处理完成后按发送顺序执行。允许工具调用时可在 updated\_permissions 中原样提交该调用的 permission\_suggestions，让本次对话记住同类操作；危险操作不提供可记住的建议。使用网页搜索或读取网页时，/agent/v1 与 /anthropic 的工具结果均为官方 search\_result 块；回答文本块的 citations 是 /agent/v1 的扩展字段，/anthropic 将回答引用显示为正文中的 \[n]。
* <a href="/docs/api/native/agent/streamEvents">订阅事件</a>：保持 SSE 连接以接收事件；请求不会像普通 JSON 接口一样立刻结束。先创建会话并替换 sesn\_123，再从另一请求发送消息；停止按钮只断开订阅，不会停止智能体。SDK 0.124.0 会过滤 session.usage，完整用量请读历史。传 event\_deltas\[]=agent.message 或 event\_deltas\[]=agent.thinking 可在最终事件到达前收到逐段预览（event\_start 与 event\_delta）。传 event\_deltas\[]=agent.tool\_use 可以在参数生成过程中收到 input\_json\_delta 片段。使用网页搜索或读取网页时，/agent/v1 与 /anthropic 的工具结果均为官方 search\_result 块；回答文本块的 citations 是 /agent/v1 的扩展字段，/anthropic 将回答引用显示为正文中的 \[n]。
* <a href="/docs/api/native/agent/updateSession">更新会话</a>：可选 model 为钉住版本 allowed 内的 ID，thinking 为 \{effort: "low|medium|high|xhigh|none"} 或 null。省略保留原值，null 恢复继承；仅换模型会清除不支持的会话档位。两者同时传入按新模型校验，不支持返回 400 且原选择不变。下一轮生效，在途一轮不变。示例：\{"model":"deepseek-v4-flash","thinking":\{"effort":"xhigh"}}。响应含 thinking 及 model.thinking: \{efforts, can\_disable, default\_effort}，能力未知为 null。这些选择字段仅在 /agent/v1 提供。支持 title 与 metadata（官方补丁语义：字符串值写入、null 删除该键、整包 null 清空，未提及的键保留）。官方的 agent 覆盖（tools/mcp\_servers）、budget 与 vault\_ids 不支持，传入返回 400 并点名字段。归档后的会话更新返回 409。
* <a href="/docs/api/native/agent/archiveSession">归档会话</a>：归档后的会话拒绝新消息（400 invalid\_request\_error，写明会话已归档），读取与事件历史仍可用；重复归档幂等，archived\_at 保持首次归档时间。
* <a href="/docs/api/native/agent/listSessionThreads">列出线程</a>：按 created\_at 升序返回主线程及全部子线程。线程 id 为 sthr\_ 加所属会话 id 的后缀；子线程的 parent\_thread\_id 指向主线程，session\_id 始终为父会话。agent 是实际运行的定义，内置类型的 name 为类型名，未注册的 id/version 为 null。归档子线程的 status 为 terminated，archived\_at 为归档时间；stats/usage 无线程级追踪时如实为 null。
* <a href="/docs/api/native/agent/retrieveSessionThread">读取线程</a>：返回本会话的主线程或子线程，与列表项逐字段一致。其他会话的线程、未知线程或非 sthr\_ id 一律返回 404，不泄露其存在性。
* <a href="/docs/api/native/agent/listSessionThreadEvents">列出线程事件</a>：读取所选线程自己的事件记录：主线程读主会话，子线程读对应子会话。沿用会话事件接口的查询参数、公开事件类型和 data + next\_page 信封。使用网页工具时，两个接口均返回 search\_result 块；回答 citations 为 /agent/v1 扩展，/anthropic 将引用显示为正文 \[n]。
* <a href="/docs/api/native/agent/streamSessionThreadEvents">订阅线程事件</a>：订阅所选线程自己的实时事件流。复用会话 SSE 实现；/agent 接口支持同址只读 WebSocket。主会话流同时包含子线程创建、状态和消息事件，子线程审批带 session\_thread\_id 上浮；确认或中断携带该字段时路由到所属子线程。
* <a href="/docs/api/native/agent/archiveSessionThread">归档线程</a>：主线程沿用会话归档动作；子线程仅归档对应子会话，不归档父会话或其他子线程。子线程归档后 status 为 terminated，带 archived\_at；历史事件仍可读。
* <a href="/docs/api/native/agent/listEnvironments">列出环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/native/agent/retrieveEnvironment">读取环境</a>：支持租户自建 cloud 环境、配置更新与软归档；内置环境只读。列表支持 limit、page 和 include\_archived。limited 网络在沙箱创建时生效；安装失败会终止会话，错误码为 ENVIRONMENT\_PACKAGE\_INSTALL\_FAILED。self\_hosted、scope 和跨会话包缓存尚不支持。
* <a href="/docs/api/native/agent/listToolsets">列出工具集</a>：返回工具集说明、插件名称与版本，以及每个工具的名称、说明、参数定义、是否只读和默认授权方式。通过 /agent/v1/toolsets 读取此目录；目录不会更改智能体配置。agent\_toolset\_20260401 包含全部 13 个原生工具；TaskOutput、TaskStop、Monitor、Agent、SendMessage 与其他工具一样可逐个开关及设置权限，它们都依赖 bash。兼容 API 只提供官方 8 个工具。

原生工具与参数以本站各端点说明及 `/meta/v1/openapi.yaml` 为准；[Claude Managed Agents 官方文档](https://platform.claude.com/docs/en/managed-agents/overview)描述兼容 API 的官方字段。

错误按 Anthropic 错误格式返回（type / message / request\_id），参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier (e.g., 'env\_...') |
| archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| config.networking | object | Network configuration policy. |
| config.packages | object | Package manager configuration. |
| config.type | string | Environment type |
| created_at | string | RFC 3339 timestamp when environment was created |
| description | null &#124; string | User-provided description for the environment; null when unset |
| metadata | object | User-provided metadata key-value pairs |
| name | string | Human-readable name for the environment |
| type | string | The type of object (always 'environment') |
| updated_at | string | RFC 3339 timestamp when environment was last updated |
| scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |

# 

先调用「创建环境」，用返回的环境 ID 替换 env\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier (e.g., 'env\_...') |
| archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| config.networking | object | Network configuration policy. |
| config.packages | object | Package manager configuration. |
| config.type | string | Environment type |
| created_at | string | RFC 3339 timestamp when environment was created |
| description | null &#124; string | User-provided description for the environment; null when unset |
| metadata | object | User-provided metadata key-value pairs |
| name | string | Human-readable name for the environment |
| type | string | The type of object (always 'environment') |
| updated_at | string | RFC 3339 timestamp when environment was last updated |
| scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |

# 

先调用「创建环境」，用返回的环境 ID 替换 env\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier (e.g., 'env\_...') |
| archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| config.networking | object | Network configuration policy. |
| config.packages | object | Package manager configuration. |
| config.type | string | Environment type |
| created_at | string | RFC 3339 timestamp when environment was created |
| description | null &#124; string | User-provided description for the environment; null when unset |
| metadata | object | User-provided metadata key-value pairs |
| name | string | Human-readable name for the environment |
| type | string | The type of object (always 'environment') |
| updated_at | string | RFC 3339 timestamp when environment was last updated |
| scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |

# 创建电脑

## 响应 [#响应]

### HTTP 201 [#http-201]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | string | Always &#96;computer&#96;. A computer. |
| id | string | Computer id (cmp_...), the computer_id of computer calls. |
| name | string | Display name of the computer, 1 to 255 characters. |
| sandbox_id | string &#124; null | Public id of the sandbox that backs the computer, usable with the sandbox API; null while none has been created. |
| environment_id | string &#124; null | Environment recipe the computer was created with; null when none. |
| status | string | active computers can be used by new sessions; archived ones keep their files readable but cannot start new sessions. |
| created_at | string | RFC 3339 time at which the computer was created. |
| updated_at | string | RFC 3339 time at which the computer was last modified. |
| archived_at | string &#124; null | RFC 3339 time at which the computer was archived; null while active. |

# 列出电脑

## 响应 [#响应]

### HTTP 200 [#http-200]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].type | string | Always &#96;computer&#96;. A computer. |
| data[].id | string | Computer id (cmp_...), the computer_id of computer calls. |
| data[].name | string | Display name of the computer, 1 to 255 characters. |
| data[].sandbox_id | string &#124; null | Public id of the sandbox that backs the computer, usable with the sandbox API; null while none has been created. |
| data[].environment_id | string &#124; null | Environment recipe the computer was created with; null when none. |
| data[].status | string | active computers can be used by new sessions; archived ones keep their files readable but cannot start new sessions. |
| data[].created_at | string | RFC 3339 time at which the computer was created. |
| data[].updated_at | string | RFC 3339 time at which the computer was last modified. |
| data[].archived_at | string &#124; null | RFC 3339 time at which the computer was archived; null while active. |
| has_more | boolean | Whether more items exist beyond this page. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 读取电脑

先调用「创建计算机」，用返回的计算机 ID 替换 cmp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | string | Always &#96;computer&#96;. A computer. |
| id | string | Computer id (cmp_...), the computer_id of computer calls. |
| name | string | Display name of the computer, 1 to 255 characters. |
| sandbox_id | string &#124; null | Public id of the sandbox that backs the computer, usable with the sandbox API; null while none has been created. |
| environment_id | string &#124; null | Environment recipe the computer was created with; null when none. |
| status | string | active computers can be used by new sessions; archived ones keep their files readable but cannot start new sessions. |
| created_at | string | RFC 3339 time at which the computer was created. |
| updated_at | string | RFC 3339 time at which the computer was last modified. |
| archived_at | string &#124; null | RFC 3339 time at which the computer was archived; null while active. |
| implementation | string | How the computer is backed: a virtual file store or a real sandbox. |
| storage_bytes | integer | Bytes stored on the computer. |
| file_count | integer | Number of files stored on the computer. |

# 更新电脑

先调用「创建计算机」，用返回的计算机 ID 替换 cmp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | string | Always &#96;computer&#96;. A computer. |
| id | string | Computer id (cmp_...), the computer_id of computer calls. |
| name | string | Display name of the computer, 1 to 255 characters. |
| sandbox_id | string &#124; null | Public id of the sandbox that backs the computer, usable with the sandbox API; null while none has been created. |
| environment_id | string &#124; null | Environment recipe the computer was created with; null when none. |
| status | string | active computers can be used by new sessions; archived ones keep their files readable but cannot start new sessions. |
| created_at | string | RFC 3339 time at which the computer was created. |
| updated_at | string | RFC 3339 time at which the computer was last modified. |
| archived_at | string &#124; null | RFC 3339 time at which the computer was archived; null while active. |

# 归档电脑

先调用「创建计算机」，用返回的计算机 ID 替换 cmp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | string | Always &#96;computer&#96;. A computer. |
| id | string | Computer id (cmp_...), the computer_id of computer calls. |
| name | string | Display name of the computer, 1 to 255 characters. |
| sandbox_id | string &#124; null | Public id of the sandbox that backs the computer, usable with the sandbox API; null while none has been created. |
| environment_id | string &#124; null | Environment recipe the computer was created with; null when none. |
| status | string | active computers can be used by new sessions; archived ones keep their files readable but cannot start new sessions. |
| created_at | string | RFC 3339 time at which the computer was created. |
| updated_at | string | RFC 3339 time at which the computer was last modified. |
| archived_at | string &#124; null | RFC 3339 time at which the computer was archived; null while active. |

# 删除已归档电脑

先调用「创建计算机」，用返回的计算机 ID 替换 cmp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the deleted computer. |
| type | string | Always &#96;computer_deleted&#96;. Confirms that a computer was deleted. |

# 浏览电脑文件

先调用「创建计算机」，用返回的计算机 ID 替换 cmp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].path | string | Absolute path of the entry on the computer. |
| data[].name | string | Name of the entry or object. |
| data[].type | string | Kind of entry: a file, a directory or a symbolic link. |
| data[].size | integer | Size in bytes. |
| data[].mime_type | string | MIME type of the file. |
| data[].read_only | boolean | True when the entry cannot be modified through the API. |
| data[].digest | string &#124; null | Content digest of the file; null when not computed. |
| data[].updated_at | string &#124; null | RFC 3339 time at which the object was last modified. |
| has_more | boolean | Whether more items exist beyond this page. |

# 读取电脑文件内容

先调用「创建计算机」，用返回的计算机 ID 替换 cmp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Raw file bytes (at most 16 MiB); Content-Type is inferred from the extension. ETag is present only when a digest is available. Larger files require the sandbox connection issued by connect.

**application/octet-stream**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

### HTTP 206 [#http-206]

Single byte range

**application/octet-stream**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

# 连接电脑

先调用「创建计算机」，用返回的计算机 ID 替换 cmp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| sandbox_id | string | Public id of the sandbox that backs the computer, usable with the sandbox API; null while none has been created. |
| envd_access_token | string | Access token for the sandbox's environment daemon, returned by the connect call; treat it as a secret. |
| template_id | string | Sandbox template the computer's sandbox was created from. |

# 上传电脑附件

先调用「创建计算机」，用返回的计算机 ID 替换 cmp\_123。

## 响应 [#响应]

### HTTP 201 [#http-201]

Computer result

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| path | string | Absolute path of the entry on the computer. |
| name | string | Name of the entry or object. |
| type | string | Kind of entry: a file, a directory or a symbolic link. |
| size | integer | Size in bytes. |
| mime_type | string | MIME type of the file. |
| read_only | boolean | True when the entry cannot be modified through the API. |
| digest | string &#124; null | Content digest of the file; null when not computed. |
| updated_at | string &#124; null | RFC 3339 time at which the object was last modified. |

# 

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。 先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Resource id, the resource_id of sessions.resources calls. |
| created_at | string | A timestamp in RFC 3339 format |
| file_id | string | Id of the uploaded file; it must exist and belong to your tenant. |
| mount_path | string | Path inside the machine where the file is mounted; defaults to /mnt/session/uploads/&lt;file_id&gt;, and custom paths are rooted there. |
| type | string | Always &#96;file&#96;. A file resource: an uploaded file mounted into the session's machine. |
| updated_at | string | A timestamp in RFC 3339 format |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Resource id, the resource_id of sessions.resources calls. |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].mount_path | string &#124; null &#124; string | Path inside the machine where the file is mounted; defaults to /mnt/session/uploads/&lt;file_id&gt;, and custom paths are rooted there. / Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| data[].type | string | Always &#96;github_repository&#96;. A GitHub repository resource; not supported on this platform. / Always &#96;file&#96;. A file resource: an uploaded file mounted into the session's machine. / Always &#96;memory_store&#96;. A memory store resource; not supported on this platform. |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].url | string | Repository URL. |
| data[].checkout | null &#124; object | Branch or commit to check out. |
| data[].file_id | string | Id of the uploaded file; it must exist and belong to your tenant. |
| data[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| data[].access | null &#124; string | Access mode for an attached memory store. |
| data[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| data[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| data[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。 先调用「添加会话资源」，用返回的资源 ID 替换 sesrsc\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Resource id, the resource_id of sessions.resources calls. |
| created_at | string | A timestamp in RFC 3339 format |
| mount_path | string &#124; null &#124; string | Path inside the machine where the file is mounted; defaults to /mnt/session/uploads/&lt;file_id&gt;, and custom paths are rooted there. / Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| type | string | Always &#96;github_repository&#96;. A GitHub repository resource; not supported on this platform. / Always &#96;file&#96;. A file resource: an uploaded file mounted into the session's machine. / Always &#96;memory_store&#96;. A memory store resource; not supported on this platform. |
| updated_at | string | A timestamp in RFC 3339 format |
| url | string | Repository URL. |
| checkout | null &#124; object | Branch or commit to check out. |
| checkout.name | string | Branch name to check out. |
| checkout.type | string | Always &#96;branch&#96;. Check out the named branch. / Always &#96;commit&#96;. Check out the commit with the given SHA. |
| checkout.sha | string | Full commit SHA to check out. |
| file_id | string | Id of the uploaded file; it must exist and belong to your tenant. |
| memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| access | null &#124; string | Access mode for an attached memory store. |
| description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。 先调用「添加会话资源」，用返回的资源 ID 替换 sesrsc\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| type | string | Always &#96;session_resource_deleted&#96;. Confirms that a resource was detached from the session. |

# 列出智能体

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| data[].mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| data[].metadata | object | Free-form string key/value pairs stored with the agent for your own bookkeeping. |
| data[].model | object | Model identifier and configuration. |
| data[].multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| data[].name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| data[].skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| data[].system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| data[].tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| data[].type | string | Always &#96;agent&#96;. An agent definition. |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |
| data[].computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| data[].subagent_model | string &#124; null | Praxis extension: default subagent model ID, pinned in the agent revision. Call model overrides this; otherwise it overrides the roster member model or the parent model for built-ins. Null clears the default. /agent/v1 only. |
| data[].models | object | Praxis extension: switchable model ids on /agent/v1 only. The default model must be included. When omitted, only the default model is selectable. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| mcp_servers[].type | string | Always &#96;url&#96;. An MCP server reached over a URL. |
| mcp_servers[].name | string | Name of the MCP server; the mcp_toolset entry that refers to it uses the same name in mcp_server_name. |
| mcp_servers[].url | string | http(s) endpoint of the MCP server, at most 2048 characters. |
| metadata | object | Free-form string key/value pairs stored with the agent for your own bookkeeping. |
| model | object | Model identifier and configuration. |
| model.id | string | The model that will power your agent.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| model.effort | object | How hard Claude works on each turn. Sets &#96;output_config.effort&#96; on every Messages call the session makes. |
| model.inference_geo | string | Geographic region for model inference. When unset, requests fall through to the workspace's default_inference_geo. |
| model.speed | string | Inference speed mode. &#96;fast&#96; provides significantly faster output token generation at premium pricing. Not all models support &#96;fast&#96;; invalid combinations are rejected at create time. |
| model.settings | object | Platform model settings. Only reasoning is supported; other model controls return 400. |
| multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| multiagent.agents | array&lt;object&gt; | Agents the coordinator may spawn as session threads, each resolved to a specific version. |
| multiagent.type | string | Always &#96;coordinator&#96;. The agent coordinates the roster in agents and can delegate to its members. |
| name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| skills[].skill_id | string | Id of the skill to attach. |
| skills[].type | string | Always &#96;anthropic&#96;. A skill provided by Anthropic, identified by skill_id. / Always &#96;custom&#96;. A skill created by you, identified by skill_id. |
| skills[].version | string | Version of the skill; a string. |
| system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| tools[].configs | array&lt;object&gt; &#124; array &#124; null | Per-tool settings that override default_config. Tools that are not listed follow default_config. |
| tools[].default_config | object &#124; object &#124; null | Resolved default configuration for agent tools. / Settings applied to every tool of this toolset that configs does not name. When omitted, tools are enabled with the always_allow policy. |
| tools[].type | string | Always &#96;agent_toolset_20260401&#96;. The native toolset entry (bash, edit, glob, grep, read, write, web_search, web_fetch, TaskOutput, TaskStop, Monitor, Agent, SendMessage). / Always &#96;mcp_toolset&#96;. An entry that exposes the tools of one MCP server from mcp_servers. / Always &#96;custom&#96;. A custom tool defined by name, description and input_schema; its calls are answered by the client with user.custom_tool_result. |
| tools[].mcp_server_name | string | Name of the MCP server in mcp_servers whose tools this entry exposes. |
| tools[].description | string | What the custom tool does and when the model should call it. |
| tools[].input_schema | object | JSON Schema for custom tool input parameters. |
| tools[].name | string | Name of the custom tool, as the model sees and calls it. |
| type | string | Always &#96;agent&#96;. An agent definition. |
| updated_at | string | A timestamp in RFC 3339 format |
| version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| subagent_model | string &#124; null | Praxis extension: default subagent model ID, pinned in the agent revision. Call model overrides this; otherwise it overrides the roster member model or the parent model for built-ins. Null clears the default. /agent/v1 only. |
| models | object | Praxis extension: switchable model ids on /agent/v1 only. The default model must be included. When omitted, only the default model is selectable. |
| models.allowed | array&lt;string&gt; | Model ids a session may select with its model field; it must be non-empty and must contain the agent's default model. |

# 读取智能体

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| mcp_servers[].type | string | Always &#96;url&#96;. An MCP server reached over a URL. |
| mcp_servers[].name | string | Name of the MCP server; the mcp_toolset entry that refers to it uses the same name in mcp_server_name. |
| mcp_servers[].url | string | http(s) endpoint of the MCP server, at most 2048 characters. |
| metadata | object | Free-form string key/value pairs stored with the agent for your own bookkeeping. |
| model | object | Model identifier and configuration. |
| model.id | string | The model that will power your agent.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| model.effort | object | How hard Claude works on each turn. Sets &#96;output_config.effort&#96; on every Messages call the session makes. |
| model.inference_geo | string | Geographic region for model inference. When unset, requests fall through to the workspace's default_inference_geo. |
| model.speed | string | Inference speed mode. &#96;fast&#96; provides significantly faster output token generation at premium pricing. Not all models support &#96;fast&#96;; invalid combinations are rejected at create time. |
| model.settings | object | Platform model settings. Only reasoning is supported; other model controls return 400. |
| multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| multiagent.agents | array&lt;object&gt; | Agents the coordinator may spawn as session threads, each resolved to a specific version. |
| multiagent.type | string | Always &#96;coordinator&#96;. The agent coordinates the roster in agents and can delegate to its members. |
| name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| skills[].skill_id | string | Id of the skill to attach. |
| skills[].type | string | Always &#96;anthropic&#96;. A skill provided by Anthropic, identified by skill_id. / Always &#96;custom&#96;. A skill created by you, identified by skill_id. |
| skills[].version | string | Version of the skill; a string. |
| system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| tools[].configs | array&lt;object&gt; &#124; array &#124; null | Per-tool settings that override default_config. Tools that are not listed follow default_config. |
| tools[].default_config | object &#124; object &#124; null | Resolved default configuration for agent tools. / Settings applied to every tool of this toolset that configs does not name. When omitted, tools are enabled with the always_allow policy. |
| tools[].type | string | Always &#96;agent_toolset_20260401&#96;. The native toolset entry (bash, edit, glob, grep, read, write, web_search, web_fetch, TaskOutput, TaskStop, Monitor, Agent, SendMessage). / Always &#96;mcp_toolset&#96;. An entry that exposes the tools of one MCP server from mcp_servers. / Always &#96;custom&#96;. A custom tool defined by name, description and input_schema; its calls are answered by the client with user.custom_tool_result. |
| tools[].mcp_server_name | string | Name of the MCP server in mcp_servers whose tools this entry exposes. |
| tools[].description | string | What the custom tool does and when the model should call it. |
| tools[].input_schema | object | JSON Schema for custom tool input parameters. |
| tools[].name | string | Name of the custom tool, as the model sees and calls it. |
| type | string | Always &#96;agent&#96;. An agent definition. |
| updated_at | string | A timestamp in RFC 3339 format |
| version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| subagent_model | string &#124; null | Praxis extension: default subagent model ID, pinned in the agent revision. Call model overrides this; otherwise it overrides the roster member model or the parent model for built-ins. Null clears the default. /agent/v1 only. |
| models | object | Praxis extension: switchable model ids on /agent/v1 only. The default model must be included. When omitted, only the default model is selectable. |
| models.allowed | array&lt;string&gt; | Model ids a session may select with its model field; it must be non-empty and must contain the agent's default model. |

# 

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| mcp_servers[].type | string | Always &#96;url&#96;. An MCP server reached over a URL. |
| mcp_servers[].name | string | Name of the MCP server; the mcp_toolset entry that refers to it uses the same name in mcp_server_name. |
| mcp_servers[].url | string | http(s) endpoint of the MCP server, at most 2048 characters. |
| metadata | object | Free-form string key/value pairs stored with the agent for your own bookkeeping. |
| model | object | Model identifier and configuration. |
| model.id | string | The model that will power your agent.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| model.effort | object | How hard Claude works on each turn. Sets &#96;output_config.effort&#96; on every Messages call the session makes. |
| model.inference_geo | string | Geographic region for model inference. When unset, requests fall through to the workspace's default_inference_geo. |
| model.speed | string | Inference speed mode. &#96;fast&#96; provides significantly faster output token generation at premium pricing. Not all models support &#96;fast&#96;; invalid combinations are rejected at create time. |
| model.settings | object | Platform model settings. Only reasoning is supported; other model controls return 400. |
| multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| multiagent.agents | array&lt;object&gt; | Agents the coordinator may spawn as session threads, each resolved to a specific version. |
| multiagent.type | string | Always &#96;coordinator&#96;. The agent coordinates the roster in agents and can delegate to its members. |
| name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| skills[].skill_id | string | Id of the skill to attach. |
| skills[].type | string | Always &#96;anthropic&#96;. A skill provided by Anthropic, identified by skill_id. / Always &#96;custom&#96;. A skill created by you, identified by skill_id. |
| skills[].version | string | Version of the skill; a string. |
| system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| tools[].configs | array&lt;object&gt; &#124; array &#124; null | Per-tool settings that override default_config. Tools that are not listed follow default_config. |
| tools[].default_config | object &#124; object &#124; null | Resolved default configuration for agent tools. / Settings applied to every tool of this toolset that configs does not name. When omitted, tools are enabled with the always_allow policy. |
| tools[].type | string | Always &#96;agent_toolset_20260401&#96;. The native toolset entry (bash, edit, glob, grep, read, write, web_search, web_fetch, TaskOutput, TaskStop, Monitor, Agent, SendMessage). / Always &#96;mcp_toolset&#96;. An entry that exposes the tools of one MCP server from mcp_servers. / Always &#96;custom&#96;. A custom tool defined by name, description and input_schema; its calls are answered by the client with user.custom_tool_result. |
| tools[].mcp_server_name | string | Name of the MCP server in mcp_servers whose tools this entry exposes. |
| tools[].description | string | What the custom tool does and when the model should call it. |
| tools[].input_schema | object | JSON Schema for custom tool input parameters. |
| tools[].name | string | Name of the custom tool, as the model sees and calls it. |
| type | string | Always &#96;agent&#96;. An agent definition. |
| updated_at | string | A timestamp in RFC 3339 format |
| version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| subagent_model | string &#124; null | Praxis extension: default subagent model ID, pinned in the agent revision. Call model overrides this; otherwise it overrides the roster member model or the parent model for built-ins. Null clears the default. /agent/v1 only. |
| models | object | Praxis extension: switchable model ids on /agent/v1 only. The default model must be included. When omitted, only the default model is selectable. |
| models.allowed | array&lt;string&gt; | Model ids a session may select with its model field; it must be non-empty and must contain the agent's default model. |

# 列出版本

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| data[].mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| data[].metadata | object | Free-form string key/value pairs stored with the agent for your own bookkeeping. |
| data[].model | object | Model identifier and configuration. |
| data[].multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| data[].name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| data[].skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| data[].system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| data[].tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| data[].type | string | Always &#96;agent&#96;. An agent definition. |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |
| data[].computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| data[].subagent_model | string &#124; null | Praxis extension: default subagent model ID, pinned in the agent revision. Call model overrides this; otherwise it overrides the roster member model or the parent model for built-ins. Null clears the default. /agent/v1 only. |
| data[].models | object | Praxis extension: switchable model ids on /agent/v1 only. The default model must be included. When omitted, only the default model is selectable. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 归档智能体

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| mcp_servers[].type | string | Always &#96;url&#96;. An MCP server reached over a URL. |
| mcp_servers[].name | string | Name of the MCP server; the mcp_toolset entry that refers to it uses the same name in mcp_server_name. |
| mcp_servers[].url | string | http(s) endpoint of the MCP server, at most 2048 characters. |
| metadata | object | Free-form string key/value pairs stored with the agent for your own bookkeeping. |
| model | object | Model identifier and configuration. |
| model.id | string | The model that will power your agent.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| model.effort | object | How hard Claude works on each turn. Sets &#96;output_config.effort&#96; on every Messages call the session makes. |
| model.inference_geo | string | Geographic region for model inference. When unset, requests fall through to the workspace's default_inference_geo. |
| model.speed | string | Inference speed mode. &#96;fast&#96; provides significantly faster output token generation at premium pricing. Not all models support &#96;fast&#96;; invalid combinations are rejected at create time. |
| model.settings | object | Platform model settings. Only reasoning is supported; other model controls return 400. |
| multiagent | null &#124; object | Resolved coordinator topology with a concrete agent roster. |
| multiagent.agents | array&lt;object&gt; | Agents the coordinator may spawn as session threads, each resolved to a specific version. |
| multiagent.type | string | Always &#96;coordinator&#96;. The agent coordinates the roster in agents and can delegate to its members. |
| name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| skills[].skill_id | string | Id of the skill to attach. |
| skills[].type | string | Always &#96;anthropic&#96;. A skill provided by Anthropic, identified by skill_id. / Always &#96;custom&#96;. A skill created by you, identified by skill_id. |
| skills[].version | string | Version of the skill; a string. |
| system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| tools[].configs | array&lt;object&gt; &#124; array &#124; null | Per-tool settings that override default_config. Tools that are not listed follow default_config. |
| tools[].default_config | object &#124; object &#124; null | Resolved default configuration for agent tools. / Settings applied to every tool of this toolset that configs does not name. When omitted, tools are enabled with the always_allow policy. |
| tools[].type | string | Always &#96;agent_toolset_20260401&#96;. The native toolset entry (bash, edit, glob, grep, read, write, web_search, web_fetch, TaskOutput, TaskStop, Monitor, Agent, SendMessage). / Always &#96;mcp_toolset&#96;. An entry that exposes the tools of one MCP server from mcp_servers. / Always &#96;custom&#96;. A custom tool defined by name, description and input_schema; its calls are answered by the client with user.custom_tool_result. |
| tools[].mcp_server_name | string | Name of the MCP server in mcp_servers whose tools this entry exposes. |
| tools[].description | string | What the custom tool does and when the model should call it. |
| tools[].input_schema | object | JSON Schema for custom tool input parameters. |
| tools[].name | string | Name of the custom tool, as the model sees and calls it. |
| type | string | Always &#96;agent&#96;. An agent definition. |
| updated_at | string | A timestamp in RFC 3339 format |
| version | number | The agent's current version. Starts at 1 and increments when the agent is modified. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| subagent_model | string &#124; null | Praxis extension: default subagent model ID, pinned in the agent revision. Call model overrides this; otherwise it overrides the roster member model or the parent model for built-ins. Null clears the default. /agent/v1 only. |
| models | object | Praxis extension: switchable model ids on /agent/v1 only. The default model must be included. When omitted, only the default model is selectable. |
| models.allowed | array&lt;string&gt; | Model ids a session may select with its model field; it must be non-empty and must contain the agent's default model. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Session id (sesn_...). Pass it as session_id in every session call. |
| data[].agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].environment_id | string | Id of the environment recipe the session's sandbox was created from. Omitted when no recipe was selected, that is, for a light machine or the Computer chosen by computer_id. |
| data[].metadata | object | Free-form string key/value pairs stored with the session, changed through sessions.update patch semantics. |
| data[].outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| data[].resources | array&lt;object&gt; | Resources attached to the session, at most 500; each is a file reference mounted into the session's machine. |
| data[].stats | object | Timing statistics for a session. |
| data[].status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| data[].title | null &#124; string | Title of the session, set on create or through sessions.update; null when none was set. |
| data[].type | string | Always &#96;session&#96;. A session, one conversation of an agent on a machine. |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].usage | object | Cumulative token usage for a session across all turns. |
| data[].vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| data[].deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |
| data[].cwd | string | Normalized session working directory; defaults to /home/user/workspace. Forks inherit this directory. |
| data[].computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| data[].model | object | Praxis extension: the currently selected session model. |
| data[].thinking | object &#124; null | Praxis extension: explicit session thinking effort; null inherits the pinned agent default, then the model default. none disables thinking only when model.thinking.can_disable is true. Unsupported efforts return 400 invalid_request_error. |
| data[].forked_from | object &#124; null | Praxis extension: source of a forked session; null for other sessions. Available only on /agent/v1. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 

先调用「创建智能体」，用返回的智能体 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 201 [#http-201]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Session id (sesn_...). Pass it as session_id in every session call. |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| agent.description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| agent.mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| agent.skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| agent.system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| agent.tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| agent.type | string | Always &#96;agent&#96;. An agent definition. |
| agent.version | number | The agent's current version. Starts at 1 and increments each time the agent is modified. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string | Always &#96;limit&#96;. A spending limit. |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string | Id of the environment recipe the session's sandbox was created from. Omitted when no recipe was selected, that is, for a light machine or the Computer chosen by computer_id. |
| metadata | object | Free-form string key/value pairs stored with the session, changed through sessions.update patch semantics. |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string | Always &#96;outcome_evaluation&#96;. Record of one outcome evaluation. |
| resources | array&lt;object&gt; | Resources attached to the session, at most 500; each is a file reference mounted into the session's machine. |
| resources[].id | string | Resource id, the resource_id of sessions.resources calls. |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Path inside the machine where the file is mounted; defaults to /mnt/session/uploads/&lt;file_id&gt;, and custom paths are rooted there. / Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string | Always &#96;github_repository&#96;. A GitHub repository resource; not supported on this platform. / Always &#96;file&#96;. A file resource: an uploaded file mounted into the session's machine. / Always &#96;memory_store&#96;. A memory store resource; not supported on this platform. |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string | Repository URL. |
| resources[].checkout | null &#124; object | Branch or commit to check out. |
| resources[].file_id | string | Id of the uploaded file; it must exist and belong to your tenant. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string | Title of the session, set on create or through sessions.update; null when none was set. |
| type | string | Always &#96;session&#96;. A session, one conversation of an agent on a machine. |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |
| cwd | string | Normalized session working directory; defaults to /home/user/workspace. Forks inherit this directory. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| model | object | Praxis extension: the currently selected session model. |
| model.id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| model.thinking | object &#124; null | Supported thinking controls, or null when capability is unknown or unavailable. efforts lists selectable strengths; can_disable permits none; default_effort is nullable. |
| thinking | object &#124; null | Praxis extension: explicit session thinking effort; null inherits the pinned agent default, then the model default. none disables thinking only when model.thinking.can_disable is true. Unsupported efforts return 400 invalid_request_error. |
| thinking.effort | string | Thinking level saved for this session: low, medium, high, xhigh, or none to turn thinking off. Null or absent means the session inherits the agent default and then the model default. |
| forked_from | object &#124; null | Praxis extension: source of a forked session; null for other sessions. Available only on /agent/v1. |
| forked_from.session_id | string | Id of the parent session this session was forked from; it is left unchanged by the fork. |
| forked_from.message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |

# 读取会话

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Session id (sesn_...). Pass it as session_id in every session call. |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| agent.description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| agent.mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| agent.skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| agent.system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| agent.tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| agent.type | string | Always &#96;agent&#96;. An agent definition. |
| agent.version | number | The agent's current version. Starts at 1 and increments each time the agent is modified. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string | Always &#96;limit&#96;. A spending limit. |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string | Id of the environment recipe the session's sandbox was created from. Omitted when no recipe was selected, that is, for a light machine or the Computer chosen by computer_id. |
| metadata | object | Free-form string key/value pairs stored with the session, changed through sessions.update patch semantics. |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string | Always &#96;outcome_evaluation&#96;. Record of one outcome evaluation. |
| resources | array&lt;object&gt; | Resources attached to the session, at most 500; each is a file reference mounted into the session's machine. |
| resources[].id | string | Resource id, the resource_id of sessions.resources calls. |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Path inside the machine where the file is mounted; defaults to /mnt/session/uploads/&lt;file_id&gt;, and custom paths are rooted there. / Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string | Always &#96;github_repository&#96;. A GitHub repository resource; not supported on this platform. / Always &#96;file&#96;. A file resource: an uploaded file mounted into the session's machine. / Always &#96;memory_store&#96;. A memory store resource; not supported on this platform. |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string | Repository URL. |
| resources[].checkout | null &#124; object | Branch or commit to check out. |
| resources[].file_id | string | Id of the uploaded file; it must exist and belong to your tenant. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string | Title of the session, set on create or through sessions.update; null when none was set. |
| type | string | Always &#96;session&#96;. A session, one conversation of an agent on a machine. |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |
| cwd | string | Normalized session working directory; defaults to /home/user/workspace. Forks inherit this directory. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| model | object | Praxis extension: the currently selected session model. |
| model.id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| model.thinking | object &#124; null | Supported thinking controls, or null when capability is unknown or unavailable. efforts lists selectable strengths; can_disable permits none; default_effort is nullable. |
| thinking | object &#124; null | Praxis extension: explicit session thinking effort; null inherits the pinned agent default, then the model default. none disables thinking only when model.thinking.can_disable is true. Unsupported efforts return 400 invalid_request_error. |
| thinking.effort | string | Thinking level saved for this session: low, medium, high, xhigh, or none to turn thinking off. Null or absent means the session inherits the agent default and then the model default. |
| forked_from | object &#124; null | Praxis extension: source of a forked session; null for other sessions. Available only on /agent/v1. |
| forked_from.session_id | string | Id of the parent session this session was forked from; it is left unchanged by the fork. |
| forked_from.message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |

# 分支会话（扩展）

## 响应 [#响应]

### HTTP 201 [#http-201]

Forked session (same shape as session retrieval)

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Session id (sesn_...). Pass it as session_id in every session call. |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| agent.description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| agent.mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| agent.skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| agent.system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| agent.tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| agent.type | string | Always &#96;agent&#96;. An agent definition. |
| agent.version | number | The agent's current version. Starts at 1 and increments each time the agent is modified. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string | Always &#96;limit&#96;. A spending limit. |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string | Id of the environment recipe the session's sandbox was created from. Omitted when no recipe was selected, that is, for a light machine or the Computer chosen by computer_id. |
| metadata | object | Free-form string key/value pairs stored with the session, changed through sessions.update patch semantics. |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string | Always &#96;outcome_evaluation&#96;. Record of one outcome evaluation. |
| resources | array&lt;object&gt; | Resources attached to the session, at most 500; each is a file reference mounted into the session's machine. |
| resources[].id | string | Resource id, the resource_id of sessions.resources calls. |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Path inside the machine where the file is mounted; defaults to /mnt/session/uploads/&lt;file_id&gt;, and custom paths are rooted there. / Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string | Always &#96;github_repository&#96;. A GitHub repository resource; not supported on this platform. / Always &#96;file&#96;. A file resource: an uploaded file mounted into the session's machine. / Always &#96;memory_store&#96;. A memory store resource; not supported on this platform. |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string | Repository URL. |
| resources[].checkout | null &#124; object | Branch or commit to check out. |
| resources[].file_id | string | Id of the uploaded file; it must exist and belong to your tenant. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string | Title of the session, set on create or through sessions.update; null when none was set. |
| type | string | Always &#96;session&#96;. A session, one conversation of an agent on a machine. |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |
| cwd | string | Normalized session working directory; defaults to /home/user/workspace. Forks inherit this directory. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| model | object | Praxis extension: the currently selected session model. |
| model.id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| model.thinking | object &#124; null | Supported thinking controls, or null when capability is unknown or unavailable. efforts lists selectable strengths; can_disable permits none; default_effort is nullable. |
| thinking | object &#124; null | Praxis extension: explicit session thinking effort; null inherits the pinned agent default, then the model default. none disables thinking only when model.thinking.can_disable is true. Unsupported efforts return 400 invalid_request_error. |
| thinking.effort | string | Thinking level saved for this session: low, medium, high, xhigh, or none to turn thinking off. Null or absent means the session inherits the agent default and then the model default. |
| forked_from | object &#124; null | Praxis extension: source of a forked session; null for other sessions. Available only on /agent/v1. |
| forked_from.session_id | string | Id of the parent session this session was forked from; it is left unchanged by the fork. |
| forked_from.message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |

# 读取会话上下文（扩展）

## 响应 [#响应]

### HTTP 200 [#http-200]

Current model and latest context measurement

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | string | Always &#96;session_context&#96;. Snapshot of a session's context window usage. |
| session_id | string | Session whose context this snapshot describes. |
| model | object | Model of the session and its context window facts. |
| model.id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| model.display_name | string | Human-readable name of the model. |
| model.thinking | object &#124; null | Thinking capability of the model: supported efforts, whether thinking can be disabled, and the default. Null when the capability is unknown. |
| total_tokens | number &#124; null | Tokens currently occupying the context window; null before the first measurement. |
| total_tokens_source | string &#124; null | Whether total_tokens is the provider-reported input usage (actual) or a local estimate (estimated); null before the first measurement. |
| max_tokens | number &#124; null | Context window of the model in tokens; null when the model does not state one. |
| max_input_tokens | number &#124; null | Maximum input tokens the model accepts per request; null when not stated. |
| percentage | number | Share of the context window in use, as a whole-number percent; 0 when the window or usage is unknown. |
| auto_compact_threshold | number &#124; null | Token count at which automatic compaction starts; null when the window is unknown. |
| is_auto_compact_enabled | boolean | Whether automatic compaction is enabled for this session. |
| clear_tool_results_at | number | Token count at which old tool results are cleared from the context. |
| detail | string | Level of detail of the snapshot. |
| categories | array&lt;object&gt; | Context usage by category; each row has a stable key and a kind. |
| categories[].key | string | Praxis extension: stable source identifier (system, tools, mcp:&lt;server&gt;, plugin:&lt;id&gt;, messages, summary, free, buffer). Clients must tolerate unknown keys and newly added sources; classify rows by kind, not key or name. |
| categories[].name | string | Display name of the category. |
| categories[].tokens | number | Tokens used by the category. |
| categories[].kind | string | How the category counts against the window. |
| mcp_tools | array&lt;object&gt; | Tokens spent on the tool definitions of each MCP server. |
| mcp_tools[].name | string | Name of the MCP tool. |
| mcp_tools[].server_name | string | Name of the MCP server that provides the tool. |
| mcp_tools[].tokens | number | Tokens used by the tool definition. |
| plugin_blocks | array&lt;object&gt; | Tokens spent on context blocks injected by each mod. |
| plugin_blocks[].name | string | Name of the mod that injected the block. |
| plugin_blocks[].tokens | number | Tokens used by the block. |
| message_breakdown | object | Tokens in the conversation messages, split by role and tool traffic. |
| message_breakdown.user_message_tokens | number | Tokens of user messages. |
| message_breakdown.assistant_message_tokens | number | Tokens of assistant text messages. |
| message_breakdown.tool_call_tokens | number | Tokens of tool-call arguments. |
| message_breakdown.tool_result_tokens | number | Tokens of tool results. |
| message_breakdown.reasoning_tokens | number | Tokens of reasoning content. |
| message_breakdown.tool_calls_by_type | array&lt;object&gt; | Tool-call and tool-result tokens grouped by tool name. |
| compaction_summary | object &#124; null | Tokens held by the latest compaction summary; null when the session was never compacted. |
| compaction_summary.tokens | number | Tokens of the compaction summary. |
| excluded_items | object | Items removed from the context for content safety, kept for audit only and not counted as usage. |
| excluded_items.count | number | Number of excluded items. |
| excluded_items.tokens | number | Tokens of the excluded items. |
| measured_at | string &#124; null | RFC 3339 time of the measurement; null before the first measurement. |

# 列出后台任务（扩展）

## 响应 [#响应]

### HTTP 200 [#http-200]

Session background tasks

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| data[].kind | string | Kind of background task: bash for a command started with run_in_background, monitor for a Monitor watch. |
| data[].title | string | Short human-readable title of the task or object. |
| data[].thread_id | string &#124; null | Execution thread the task belongs to; null for the primary thread. |
| data[].status | string | Current lifecycle state. |
| data[].started_at | string | RFC 3339 time at which the task started. |
| data[].ended_at | string &#124; null | RFC 3339 time at which the task ended; null while it is running. |
| data[].cancellable | boolean | Whether the task can still be stopped. |
| data[].notified_at | string &#124; null | RFC 3339 time of the latest run that the task's notification started; null while no notification has been delivered. |
| data[].trigger_count | integer &#124; null | For a monitor task, how many times its matches woke the session; null for other kinds or before the first notification. |

# 读取后台任务输出（扩展）

## 响应 [#响应]

### HTTP 200 [#http-200]

Background task output byte page

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| text | string | Text of the block. |
| next_offset | integer | Byte offset to pass as offset to continue reading the output. |
| eof | boolean | True when the output has ended and no more bytes will follow. |
| unavailable | boolean | True when the output could not be read; text is then empty. |

# 停止后台任务（扩展）

## 响应 [#响应]

### HTTP 200 [#http-200]

Current task after stop request

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| kind | string | Kind of background task: bash for a command started with run_in_background, monitor for a Monitor watch. |
| title | string | Short human-readable title of the task or object. |
| thread_id | string &#124; null | Execution thread the task belongs to; null for the primary thread. |
| status | string | Current lifecycle state. |
| started_at | string | RFC 3339 time at which the task started. |
| ended_at | string &#124; null | RFC 3339 time at which the task ended; null while it is running. |
| cancellable | boolean | Whether the task can still be stopped. |
| notified_at | string &#124; null | RFC 3339 time of the latest run that the task's notification started; null while no notification has been delivered. |
| trigger_count | integer &#124; null | For a monitor task, how many times its matches woke the session; null for other kinds or before the first notification. |

# 压缩会话（扩展）

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Skipped, succeeded or failed compaction

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | string | Always &#96;session_compaction&#96;. Result of a compaction request. |
| id | string | Compaction operation id; pass it as operation_id to sessions.compact.retrieve. |
| status | string | State of the compaction operation: queued and running are in progress, skipped means nothing needed compaction, succeeded and failed are final. |
| reason | string | Why the compaction was skipped or failed; absent otherwise. |

### HTTP 202 [#http-202]

Queued or running compaction

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | string | Always &#96;session_compaction&#96;. Result of a compaction request. |
| id | string | Compaction operation id; pass it as operation_id to sessions.compact.retrieve. |
| status | string | State of the compaction operation: queued and running are in progress, skipped means nothing needed compaction, succeeded and failed are final. |
| reason | string | Why the compaction was skipped or failed; absent otherwise. |

# 读取压缩操作（扩展）

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Compaction operation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | string | Always &#96;session_compaction&#96;. Result of a compaction request. |
| id | string | Compaction operation id; pass it as operation_id to sessions.compact.retrieve. |
| status | string | State of the compaction operation: queued and running are in progress, skipped means nothing needed compaction, succeeded and failed are final. |
| reason | string | Why the compaction was skipped or failed; absent otherwise. |

# 列出压缩历史（扩展）

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Compaction history

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].type | string | Always &#96;context_compaction&#96;. Record of one past compaction. |
| data[].id | string | Compaction record id. |
| data[].event_id | string &#124; null | Id of the agent.thread_context_compacted event emitted for this compaction; null when none. |
| data[].trigger | string | What started the compaction. |
| data[].status | string | Final outcome of the compaction. |
| data[].model | string | Model that wrote the summary. |
| data[].compacted_message_count | number | Number of messages replaced by the summary. |
| data[].input_tokens_before | number | Context tokens before the compaction. |
| data[].input_tokens_after | number &#124; null | Context tokens after the compaction; null when not measured. |
| data[].summary | string &#124; null | Summary text that replaced the messages; null when the compaction failed. |
| data[].error | string &#124; null | Failure reason; null when the compaction succeeded. |
| data[].created_at | string | RFC 3339 time at which the compaction was recorded. |

# 列出事件

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Unique identifier for this event. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. |
| data[].content | array&lt;object&gt; | Array of content blocks comprising the user message. / The result content returned by the tool. / Array of text blocks comprising the agent response. / The result content returned by the tool. / The result content returned by the tool. / Message content blocks. / Message content blocks. / The result content returned by the tool. / System content blocks. Text-only. |
| data[].type | string | Always &#96;user.message&#96;. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. The user interrupted the running turn. / Always &#96;user.tool_confirmation&#96;. The user's decision to allow or deny a tool call that waits for approval. / Always &#96;user.custom_tool_result&#96;. The user's result for a custom tool call. / Always &#96;agent.custom_tool_use&#96;. The agent called a custom tool defined by the client. / Always &#96;agent.message&#96;. A message from the agent, with text content blocks. / Always &#96;agent.thinking&#96;. The agent's thinking text for a step. / Always &#96;agent.mcp_tool_use&#96;. The agent called an MCP tool. / Always &#96;agent.mcp_tool_result&#96;. The result of an MCP tool call. / Always &#96;agent.tool_use&#96;. The agent called a tool. / Always &#96;agent.tool_result&#96;. The result of a tool call. / Always &#96;agent.thread_message_received&#96;. The agent received a message from another thread. / Always &#96;agent.thread_message_sent&#96;. The agent sent a message to another thread. / Always &#96;agent.thread_context_compacted&#96;. The thread's context was compacted into a summary. / Always &#96;session.error&#96;. The session hit an error. / Always &#96;session.status_rescheduled&#96;. The session will retry after a recoverable error. / Always &#96;session.status_running&#96;. The session started running a turn. / Always &#96;session.status_idle&#96;. The session stopped running; stop_reason says why. / Always &#96;session.status_terminated&#96;. The session ended and accepts no more work. / Always &#96;session.thread_created&#96;. A child thread was started. / Always &#96;span.outcome_evaluation_start&#96;. An outcome evaluation started. / Always &#96;span.outcome_evaluation_end&#96;. An outcome evaluation ended. / Always &#96;span.model_request_start&#96;. A model request started. / Always &#96;span.model_request_end&#96;. A model request ended, with its usage. / Always &#96;span.outcome_evaluation_ongoing&#96;. An outcome evaluation is still running. / Always &#96;user.define_outcome&#96;. The user defined the outcome the agent should reach. / Always &#96;session.deleted&#96;. The session was deleted. / Always &#96;session.thread_status_running&#96;. A thread started running. / Always &#96;session.thread_status_idle&#96;. A thread stopped running; stop_reason says why. / Always &#96;session.thread_status_terminated&#96;. A thread ended. / Always &#96;user.tool_result&#96;. The user's result for a client-side tool call. / Always &#96;session.thread_status_rescheduled&#96;. A thread will retry after a recoverable error. / Always &#96;session.updated&#96;. The session's model, title, metadata, agent or budget changed. / Always &#96;system.message&#96;. A message produced by the platform rather than the user or the agent. / Always &#96;session.usage&#96;. Cumulative usage of the session. / Always &#96;session.forked&#96;. The session was created by forking another session. / Always &#96;session.goal_changed&#96;. / Always &#96;session.goal_verification&#96;. / Always &#96;user.steer&#96;. Receipt that a queued user.message was injected into the running turn. / Always &#96;user.tool_confirmation&#96;. |
| data[].processed_at | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string | A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / When the event was recorded, RFC 3339. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / When the event was recorded, RFC 3339. |
| data[].message_id | string | UI transcript message ID. Use the last assistant message in a successfully completed turn as the fork target. / UI transcript message ID shared with this assistant's message parts. |
| data[].session_thread_id | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string | If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Set by the server to the subagent thread this confirmation was routed to. Omitted when it was routed to the primary thread. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / When set, this event was cross-posted from a subagent's thread to surface its custom tool use on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.custom_tool_result&#96; by &#96;custom_tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; or &#96;user.tool_result&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / Public &#96;sthr_&#96; ID of the newly created thread. / Public sthr\_ ID of the thread that started running. / Public sthr\_ ID of the thread that went idle. / Public sthr\_ ID of the thread that terminated. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / Public sthr\_ ID of the thread that is retrying. |
| data[].result | string | UserToolConfirmationResult enum / Evaluation verdict. 'satisfied': criteria met, session goes idle. 'needs_revision': criteria not met, another revision cycle follows. 'max_iterations_reached': evaluation budget exhausted with criteria still unmet — one final acknowledgment turn follows before the session goes idle, but no further evaluation runs. 'failed': grader determined the rubric does not apply to the deliverables. 'interrupted': user sent an interrupt while evaluation was in progress. / Always &#96;allow&#96;. |
| data[].tool_use_id | string | The id of the &#96;agent.tool_use&#96; or &#96;agent.mcp_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. / The id of the &#96;agent.tool_use&#96; event this result corresponds to. / The id of the &#96;agent.tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. / The id of the AskUserQuestion &#96;agent.tool_use&#96; event this answers. |
| data[].deny_message | null &#124; string | Optional message providing context for a 'deny' decision. Only allowed when result is 'deny'. |
| data[].custom_tool_use_id | string | The id of the &#96;agent.custom_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].is_error | null &#124; boolean | Whether the tool execution resulted in an error. / Whether the model request resulted in an error. / Whether the tool execution resulted in an error. |
| data[].input | object | Input parameters for the tool call. |
| data[].name | string | Name of the custom tool being called. / Name of the MCP tool being used. / Name of the agent tool being used. |
| data[].mcp_server_name | string | Name of the MCP server providing the tool. |
| data[].evaluated_permission | string | AgentEvaluatedPermission enum |
| data[].evaluation | object | Names the resolved permission_policy that produced evaluated_permission, and under auto carries the judgement. Open union: clients must tolerate unknown variants. |
| data[]._meta | object | Praxis extension (MCP Apps, SEP-1865): the &#96;ui&#96; and &#96;openai/ui&#96; keys of the MCP tool definition's &#96;_meta&#96;, verbatim; other &#96;_meta&#96; keys are not exposed. When &#96;ui.resourceUri&#96; is a &#96;ui://&#96; URI, the tool has an interactive view: a client that implements MCP Apps can fetch that resource from the MCP server and render it for this call. Absent when the tool declares neither key. Clients that do not render MCP Apps ignore it. / Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;_meta&#96;, verbatim. Views use it for data that should not reach the model; absent when the tool returned none. |
| data[].source | string | Praxis extension (MCP Apps, SEP-1865): &#96;app&#96; when the call was made by an MCP Apps view, &#96;codemode&#96; when a program run by the codemode tool called an MCP tool that declares a view (the event pair exists so a client can render that view; the model already has the result in the codemode tool result); absent for the model's own calls. / What caused the change. |
| data[].parent_tool_use_id | string | Praxis extension (MCP Apps, SEP-1865): present when &#96;source&#96; is &#96;codemode&#96;; the id of the codemode tool use whose program made this call. Absent otherwise. |
| data[].mcp_tool_use_id | string | The id of the &#96;agent.mcp_tool_use&#96; event this result corresponds to. |
| data[].structured_content | any | Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;structuredContent&#96;, verbatim JSON. MCP Apps views read it as the data to render; absent when the tool returned none. |
| data[].from_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread that sent the message. |
| data[].from_agent_name | null &#124; string | Name of the callable agent this message came from. Absent when received from the primary agent. |
| data[].to_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread the message was sent to. |
| data[].to_agent_name | null &#124; string | Name of the callable agent this message was sent to. Absent when sent to the primary agent. |
| data[].error | object | Description of the error and what the client should do next. |
| data[].stop_reason | object | Why the session stopped running, with the variant data needed to continue. |
| data[].agent_name | string | Name of the callable agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. |
| data[].iteration | number | 0-indexed revision cycle. 0 is the first evaluation; 1 is the re-evaluation after the first revision; etc. / 0-indexed revision cycle, matching the corresponding &#96;span.outcome_evaluation_start&#96;. / 0-indexed revision cycle, matching the corresponding &#96;span.outcome_evaluation_start&#96;. |
| data[].outcome_id | string | The &#96;outc_&#96; ID of the outcome being evaluated. / Server-generated &#96;outc_&#96; ID for this outcome. Referenced by &#96;span.outcome_evaluation_*&#96; events and the session's &#96;outcome_evaluations&#96; list. |
| data[].explanation | string | Human-readable explanation of the verdict. For &#96;needs_revision&#96;, describes which criteria failed and why. |
| data[].outcome_evaluation_start_id | string | The id of the corresponding &#96;span.outcome_evaluation_start&#96; event. |
| data[].usage | object | Token usage for a single model request. / Point-in-time snapshot of a session's cumulative usage. |
| data[].model_request_start_id | string | The id of the corresponding &#96;span.model_request_start&#96; event. |
| data[].model_usage | object | Token usage for a single model request. |
| data[].description | string | What the agent should produce. Copied from the input event. |
| data[].max_iterations | null &#124; number | Evaluate-then-revise cycles before giving up. Default 3, max 20. |
| data[].rubric | object | Rubric for grading the quality of an outcome. |
| data[].agent | null &#124; object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| data[].budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| data[].metadata | object | The session's full metadata bag after the update. Present when the update set non-empty metadata; absent when metadata was unchanged or cleared to empty. |
| data[].title | null &#124; string | The session's new title. Present only when the update changed it. |
| data[].model | object | Praxis extension: the changed session model, present only on /agent/v1 session.updated events. Model-only updates are omitted on /anthropic. |
| data[].forked_from_session_id | string | Id of the parent session this session was forked from. |
| data[].forked_from_message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |
| data[].action | string | What changed in the goal. |
| data[].goal | object &#124; null | The goal as the change left it, or null when the session has no goal. |
| data[].previous_goal | object &#124; null | The goal before the change, or null when there was none. |
| data[].status | string | Where the check stands. Read &#96;verification.passed&#96; on the closing event to know whether the goal counts as done. |
| data[].goal_id | string | The goal this check belongs to. |
| data[].goal_iteration | integer | Which check of this goal, matching &#96;iteration&#96; on the goal. |
| data[].verification_id | string | Identifier shared by every event of one check. |
| data[].anchor_message_id | string &#124; null | The assistant message the check follows, or null. |
| data[].verification | object | The verdict; absent on &#96;started&#96;. |
| data[].event_id | string | Id of the event this event refers to. |
| data[].answers | object | The user's answer to each question, keyed by the question text; empty when the questions were dismissed. |
| data[].annotations | object | Per-question notes, keyed by the question text. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Sent events |
| data[].id | string | Unique identifier for this event. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. |
| data[].content | array&lt;object&gt; | Array of content blocks comprising the user message. / The result content returned by the tool. / The result content returned by the tool. / System content blocks. Text-only. |
| data[].type | string | Always &#96;user.message&#96;. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. The user interrupted the running turn. / Always &#96;user.tool_confirmation&#96;. The user's decision to allow or deny a tool call that waits for approval. / Always &#96;user.custom_tool_result&#96;. The user's result for a custom tool call. / Always &#96;user.define_outcome&#96;. The user defined the outcome the agent should reach. / Always &#96;user.tool_result&#96;. The user's result for a client-side tool call. / Always &#96;system.message&#96;. A message produced by the platform rather than the user or the agent. / Always &#96;user.steer&#96;. Receipt that a queued user.message was injected into the running turn. / Always &#96;user.tool_confirmation&#96;. |
| data[].processed_at | null &#124; string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; string | A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / When the event was recorded, RFC 3339. |
| data[].session_thread_id | null &#124; string | If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Set by the server to the subagent thread this confirmation was routed to. Omitted when it was routed to the primary thread. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. |
| data[].result | string | UserToolConfirmationResult enum / Always &#96;allow&#96;. |
| data[].tool_use_id | string | The id of the &#96;agent.tool_use&#96; or &#96;agent.mcp_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. / The id of the &#96;agent.tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. / The id of the AskUserQuestion &#96;agent.tool_use&#96; event this answers. |
| data[].deny_message | null &#124; string | Optional message providing context for a 'deny' decision. Only allowed when result is 'deny'. |
| data[].custom_tool_use_id | string | The id of the &#96;agent.custom_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].is_error | null &#124; boolean | Whether the tool execution resulted in an error. |
| data[].description | string | What the agent should produce. Copied from the input event. |
| data[].max_iterations | null &#124; number | Evaluate-then-revise cycles before giving up. Default 3, max 20. |
| data[].outcome_id | string | Server-generated &#96;outc_&#96; ID for this outcome. Referenced by &#96;span.outcome_evaluation_*&#96; events and the session's &#96;outcome_evaluations&#96; list. |
| data[].rubric | object | Rubric for grading the quality of an outcome. |
| data[].event_id | string | Id of the event this event refers to. |
| data[].answers | object | The user's answer to each question, keyed by the question text; empty when the questions were dismissed. |
| data[].annotations | object | Per-question notes, keyed by the question text. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Server-sent events

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| event | string | Server-Sent Events event name of this frame. / Always &#96;user.message&#96;. SSE event name of this frame; its data is a user.message payload. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. SSE event name of this frame; its data is a user.interrupt payload. The user interrupted the running turn. / Always &#96;agent.message&#96;. SSE event name of this frame; its data is a agent.message payload. A message from the agent, with text content blocks. / Always &#96;agent.thinking&#96;. SSE event name of this frame; its data is a agent.thinking payload. The agent's thinking text for a step. / Always &#96;session.status_running&#96;. SSE event name of this frame; its data is a session.status_running payload. The session started running a turn. / Always &#96;session.status_rescheduled&#96;. SSE event name of this frame; its data is a session.status_rescheduled payload. The session will retry after a recoverable error. / Always &#96;session.status_idle&#96;. SSE event name of this frame; its data is a session.status_idle payload. The session stopped running; stop_reason says why. / Always &#96;session.status_terminated&#96;. SSE event name of this frame; its data is a session.status_terminated payload. The session ended and accepts no more work. / Always &#96;agent.thread_context_compacted&#96;. SSE event name of this frame; its data is a agent.thread_context_compacted payload. The thread's context was compacted into a summary. / Always &#96;agent.thread_context_reset&#96;. SSE event name of this frame; its data is a agent.thread_context_reset payload. Content was removed from the model's context after a content-safety refusal. / Always &#96;session.updated&#96;. SSE event name of this frame; its data is a session.updated payload. The session's model, title, metadata, agent or budget changed. / Always &#96;session.error&#96;. SSE event name of this frame; its data is a session.error payload. The session hit an error. / Always &#96;session.usage&#96;. SSE event name of this frame; its data is a session.usage payload. Cumulative usage of the session. / Always &#96;span.model_request_start&#96;. SSE event name of this frame; its data is a span.model_request_start payload. A model request started. / Always &#96;span.model_request_end&#96;. SSE event name of this frame; its data is a span.model_request_end payload. A model request ended, with its usage. / Always &#96;agent.tool_use&#96;. SSE event name of this frame; its data is a agent.tool_use payload. The agent called a tool. / Always &#96;agent.tool_result&#96;. SSE event name of this frame; its data is a agent.tool_result payload. The result of a tool call. / Always &#96;agent.mcp_tool_use&#96;. SSE event name of this frame; its data is a agent.mcp_tool_use payload. The agent called an MCP tool. / Always &#96;agent.mcp_tool_result&#96;. SSE event name of this frame; its data is a agent.mcp_tool_result payload. The result of an MCP tool call. / Always &#96;user.tool_confirmation&#96;. SSE event name of this frame; its data is a user.tool_confirmation payload. The user's decision to allow or deny a tool call that waits for approval. / Always &#96;session.thread_created&#96;. SSE event name of this frame; its data is a session.thread_created payload. A child thread was started. / Always &#96;session.thread_status_running&#96;. SSE event name of this frame; its data is a session.thread_status_running payload. A thread started running. / Always &#96;session.thread_status_idle&#96;. SSE event name of this frame; its data is a session.thread_status_idle payload. A thread stopped running; stop_reason says why. / Always &#96;session.thread_status_rescheduled&#96;. SSE event name of this frame; its data is a session.thread_status_rescheduled payload. A thread will retry after a recoverable error. / Always &#96;session.thread_status_terminated&#96;. SSE event name of this frame; its data is a session.thread_status_terminated payload. A thread ended. / Always &#96;agent.thread_message_sent&#96;. SSE event name of this frame; its data is a agent.thread_message_sent payload. The agent sent a message to another thread. / Always &#96;agent.thread_message_received&#96;. SSE event name of this frame; its data is a agent.thread_message_received payload. The agent received a message from another thread. / Always &#96;user.withdraw&#96;. SSE event name of this frame; its data is a user.withdraw payload. A queued user.message was withdrawn before it ran. / Always &#96;user.steer&#96;. SSE event name of this frame; its data is a user.steer payload. Receipt that a queued user.message was injected into the running turn. / Always &#96;system.notification&#96;. SSE event name of this frame; its data is a system.notification payload. Background work woke the session with a notification. / Always &#96;session.forked&#96;. SSE event name of this frame; its data is a session.forked payload. The session was created by forking another session. / Always &#96;session.goal_changed&#96;. SSE event name of this frame; its data is a session.goal_changed payload. The session's goal was set, changed status, accounted usage or was cleared. / Always &#96;session.goal_verification&#96;. SSE event name of this frame; its data is a session.goal_verification payload. One completion check of the session's goal started or ended. / Always &#96;event_start&#96;. SSE event name of this frame; its data is a event_start payload. Preview that an event of the requested delta types has started. / Always &#96;event_delta&#96;. SSE event name of this frame; its data is a event_delta payload. Incremental fragment of the event being produced. / Always &#96;ping&#96;. SSE event name of this frame; its data is a ping payload. Keep-alive frame; carries no data. / Always &#96;error&#96;. SSE event name of this frame; its data is a error payload. A stream error. |
| data | object | Decoded JSON payload of this frame; its shape is selected by the event name. / Praxis extension (AskUserQuestion, own face only): the confirmation of an AskUserQuestion call, with the answers it carried. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Praxis extension (goal mode, own face only): the session's goal was set, moved to another status, accounted usage or was cleared. &#96;goal&#96; is the goal after the change, &#96;previous_goal&#96; the one before; each is null when there was none. / Praxis extension (goal mode, own face only): one completion check of the goal. A &#96;started&#96; event opens it; &#96;completed&#96;, &#96;failed_closed&#96; or &#96;cancelled&#96; closes it. Events of one check share &#96;verification_id&#96;. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. |
| data.id | string | Unique identifier for this event. / Text of the block. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Event id, unique within the session. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Text of the block. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Text of the block. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Text of the block. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Event id, unique within the session. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Text of the block. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Text of the block. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. |
| data.content | array&lt;object&gt; | Array of content blocks comprising the user message. / Array of text blocks comprising the agent response. / Content blocks of the event, in order. / The result content returned by the tool. / The result content returned by the tool. / Message content blocks. / Message content blocks. / Array of content blocks comprising the user message. / Array of text blocks comprising the agent response. / Content blocks of the event, in order. / The result content returned by the tool. / The result content returned by the tool. / Message content blocks. / Message content blocks. |
| data.type | string | Always &#96;user.message&#96;. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. The user interrupted the running turn. / Always &#96;agent.message&#96;. A message from the agent, with text content blocks. / Always &#96;agent.thinking&#96;. The agent's thinking text for a step. / Always &#96;session.status_running&#96;. The session started running a turn. / Always &#96;session.status_rescheduled&#96;. The session will retry after a recoverable error. / Always &#96;session.status_idle&#96;. The session stopped running; stop_reason says why. / Always &#96;session.status_terminated&#96;. The session ended and accepts no more work. / Always &#96;agent.thread_context_compacted&#96;. The thread's context was compacted into a summary. / Always &#96;agent.thread_context_reset&#96;. Content was removed from the model's context after a content-safety refusal. / Always &#96;session.updated&#96;. The session's model, title, metadata, agent or budget changed. / Always &#96;session.error&#96;. The session hit an error. / Always &#96;session.usage&#96;. Cumulative usage of the session. / Always &#96;span.model_request_start&#96;. A model request started. / Always &#96;span.model_request_end&#96;. A model request ended, with its usage. / Always &#96;agent.tool_use&#96;. The agent called a tool. / Always &#96;agent.tool_result&#96;. The result of a tool call. / Always &#96;agent.mcp_tool_use&#96;. The agent called an MCP tool. / Always &#96;agent.mcp_tool_result&#96;. The result of an MCP tool call. / Always &#96;user.tool_confirmation&#96;. / Always &#96;session.thread_created&#96;. A child thread was started. / Always &#96;session.thread_status_running&#96;. A thread started running. / Always &#96;session.thread_status_idle&#96;. A thread stopped running; stop_reason says why. / Always &#96;session.thread_status_rescheduled&#96;. A thread will retry after a recoverable error. / Always &#96;session.thread_status_terminated&#96;. A thread ended. / Always &#96;agent.thread_message_sent&#96;. The agent sent a message to another thread. / Always &#96;agent.thread_message_received&#96;. The agent received a message from another thread. / Always &#96;user.withdraw&#96;. A queued user.message was withdrawn before it ran. / Always &#96;user.steer&#96;. Receipt that a queued user.message was injected into the running turn. / Always &#96;system.notification&#96;. Background work woke the session with a notification. / Always &#96;session.forked&#96;. The session was created by forking another session. / Always &#96;session.goal_changed&#96;. / Always &#96;session.goal_verification&#96;. / Always &#96;event_start&#96;. Preview that an event of the requested delta types has started. / Always &#96;event_delta&#96;. Incremental fragment of the event being produced. / Always &#96;ping&#96;. Keep-alive frame; carries no data. / Always &#96;error&#96;. A stream error. / Always &#96;user.message&#96;. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. The user interrupted the running turn. / Always &#96;agent.message&#96;. A message from the agent, with text content blocks. / Always &#96;agent.thinking&#96;. The agent's thinking text for a step. / Always &#96;session.status_running&#96;. The session started running a turn. / Always &#96;session.status_rescheduled&#96;. The session will retry after a recoverable error. / Always &#96;session.status_idle&#96;. The session stopped running; stop_reason says why. / Always &#96;session.status_terminated&#96;. The session ended and accepts no more work. / Always &#96;agent.thread_context_compacted&#96;. The thread's context was compacted into a summary. / Always &#96;agent.thread_context_reset&#96;. Content was removed from the model's context after a content-safety refusal. / Always &#96;session.updated&#96;. The session's model, title, metadata, agent or budget changed. / Always &#96;session.error&#96;. The session hit an error. / Always &#96;session.usage&#96;. Cumulative usage of the session. / Always &#96;span.model_request_start&#96;. A model request started. / Always &#96;span.model_request_end&#96;. A model request ended, with its usage. / Always &#96;agent.tool_use&#96;. The agent called a tool. / Always &#96;agent.tool_result&#96;. The result of a tool call. / Always &#96;agent.mcp_tool_use&#96;. The agent called an MCP tool. / Always &#96;agent.mcp_tool_result&#96;. The result of an MCP tool call. / Always &#96;user.tool_confirmation&#96;. / Always &#96;session.thread_created&#96;. A child thread was started. / Always &#96;session.thread_status_running&#96;. A thread started running. / Always &#96;session.thread_status_idle&#96;. A thread stopped running; stop_reason says why. / Always &#96;session.thread_status_rescheduled&#96;. A thread will retry after a recoverable error. / Always &#96;session.thread_status_terminated&#96;. A thread ended. / Always &#96;agent.thread_message_sent&#96;. The agent sent a message to another thread. / Always &#96;agent.thread_message_received&#96;. The agent received a message from another thread. / Always &#96;user.withdraw&#96;. A queued user.message was withdrawn before it ran. / Always &#96;user.steer&#96;. Receipt that a queued user.message was injected into the running turn. / Always &#96;system.notification&#96;. Background work woke the session with a notification. / Always &#96;session.forked&#96;. The session was created by forking another session. / Always &#96;session.goal_changed&#96;. / Always &#96;session.goal_verification&#96;. / Always &#96;event_start&#96;. Preview that an event of the requested delta types has started. / Always &#96;event_delta&#96;. Incremental fragment of the event being produced. / Always &#96;ping&#96;. Keep-alive frame; carries no data. / Always &#96;error&#96;. A stream error. |
| data.processed_at | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string | A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / When the event was recorded, RFC 3339. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / When the event was recorded, RFC 3339. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / When the event was recorded, RFC 3339. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / When the event was recorded, RFC 3339. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. |
| data.message_id | string | UI transcript message ID. Use the last assistant message in a successfully completed turn as the fork target. / UI transcript message ID shared with this assistant's message parts. / UI transcript message ID. Use the last assistant message in a successfully completed turn as the fork target. / UI transcript message ID. Use the last assistant message in a successfully completed turn as the fork target. / UI transcript message ID shared with this assistant's message parts. |
| data.session_thread_id | null &#124; string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string | If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Text of the block. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; or &#96;user.tool_result&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / Public &#96;sthr_&#96; ID of the newly created thread. / Public sthr\_ ID of the thread that started running. / Public sthr\_ ID of the thread that went idle. / Public sthr\_ ID of the thread that is retrying. / Public sthr\_ ID of the thread that terminated. / Text of the block. / Text of the block. / If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Text of the block. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; or &#96;user.tool_result&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / Public &#96;sthr_&#96; ID of the newly created thread. / Public sthr\_ ID of the thread that started running. / Public sthr\_ ID of the thread that went idle. / Public sthr\_ ID of the thread that is retrying. / Public sthr\_ ID of the thread that terminated. / Text of the block. / Text of the block. |
| data.stop_reason | object | Why the session stopped running, with the variant data needed to continue. |
| data.removed | array&lt;object&gt; | Content removed from the model's context by this reset. |
| data.category | string | Text of the block. |
| data.stopped | boolean | True when the run was stopped instead of retried after the reset. |
| data.agent | null &#124; object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| data.budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| data.metadata | object | The session's full metadata bag after the update. Present when the update set non-empty metadata; absent when metadata was unchanged or cleared to empty. |
| data.title | null &#124; string | The session's new title. Present only when the update changed it. |
| data.model | object | Praxis extension: the changed session model, present only on /agent/v1 session.updated events. Model-only updates are omitted on /anthropic. |
| data.error | object | Description of the error and what the client should do next. / Error detail. / Description of the error and what the client should do next. / Error detail. |
| data.usage | object | Point-in-time snapshot of a session's cumulative usage. |
| data.is_error | null &#124; boolean | Whether the model request resulted in an error. / Whether the tool execution resulted in an error. / Whether the tool execution resulted in an error. / Whether the model request resulted in an error. / Whether the tool execution resulted in an error. / Whether the tool execution resulted in an error. |
| data.model_request_start_id | string | The id of the corresponding &#96;span.model_request_start&#96; event. |
| data.model_usage | object | Token usage for a single model request. |
| data.input | object | Input parameters for the tool call. |
| data.name | string | Name of the agent tool being used. / Name of the MCP tool being used. / Name of the agent tool being used. / Name of the MCP tool being used. |
| data.evaluated_permission | string | AgentEvaluatedPermission enum |
| data.evaluation | object | Names the resolved permission_policy that produced evaluated_permission, and under auto carries the judgement. Open union: clients must tolerate unknown variants. |
| data.tool_use_id | string | The id of the &#96;agent.tool_use&#96; event this result corresponds to. / The id of the AskUserQuestion &#96;agent.tool_use&#96; event this answers. / The id of the &#96;agent.tool_use&#96; event this result corresponds to. / The id of the AskUserQuestion &#96;agent.tool_use&#96; event this answers. |
| data.mcp_server_name | string | Name of the MCP server providing the tool. |
| data._meta | object | Praxis extension (MCP Apps, SEP-1865): the &#96;ui&#96; and &#96;openai/ui&#96; keys of the MCP tool definition's &#96;_meta&#96;, verbatim; other &#96;_meta&#96; keys are not exposed. When &#96;ui.resourceUri&#96; is a &#96;ui://&#96; URI, the tool has an interactive view: a client that implements MCP Apps can fetch that resource from the MCP server and render it for this call. Absent when the tool declares neither key. Clients that do not render MCP Apps ignore it. / Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;_meta&#96;, verbatim. Views use it for data that should not reach the model; absent when the tool returned none. / Praxis extension (MCP Apps, SEP-1865): the &#96;ui&#96; and &#96;openai/ui&#96; keys of the MCP tool definition's &#96;_meta&#96;, verbatim; other &#96;_meta&#96; keys are not exposed. When &#96;ui.resourceUri&#96; is a &#96;ui://&#96; URI, the tool has an interactive view: a client that implements MCP Apps can fetch that resource from the MCP server and render it for this call. Absent when the tool declares neither key. Clients that do not render MCP Apps ignore it. / Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;_meta&#96;, verbatim. Views use it for data that should not reach the model; absent when the tool returned none. |
| data.source | string | Praxis extension (MCP Apps, SEP-1865): &#96;app&#96; when the call was made by an MCP Apps view, &#96;codemode&#96; when a program run by the codemode tool called an MCP tool that declares a view (the event pair exists so a client can render that view; the model already has the result in the codemode tool result); absent for the model's own calls. / What caused the change. / Praxis extension (MCP Apps, SEP-1865): &#96;app&#96; when the call was made by an MCP Apps view, &#96;codemode&#96; when a program run by the codemode tool called an MCP tool that declares a view (the event pair exists so a client can render that view; the model already has the result in the codemode tool result); absent for the model's own calls. / Praxis extension (MCP Apps, SEP-1865): &#96;app&#96; when the call was made by an MCP Apps view, &#96;codemode&#96; when a program run by the codemode tool called an MCP tool that declares a view (the event pair exists so a client can render that view; the model already has the result in the codemode tool result); absent for the model's own calls. / What caused the change. |
| data.parent_tool_use_id | string | Praxis extension (MCP Apps, SEP-1865): present when &#96;source&#96; is &#96;codemode&#96;; the id of the codemode tool use whose program made this call. Absent otherwise. |
| data.mcp_tool_use_id | string | The id of the &#96;agent.mcp_tool_use&#96; event this result corresponds to. |
| data.structured_content | any | Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;structuredContent&#96;, verbatim JSON. MCP Apps views read it as the data to render; absent when the tool returned none. |
| data.result | string | Always &#96;allow&#96;. |
| data.answers | object | The user's answer to each question, keyed by the question text; empty when the questions were dismissed. |
| data.annotations | object | Per-question notes, keyed by the question text. |
| data.agent_name | string | Name of the callable agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the callable agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. |
| data.to_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread the message was sent to. |
| data.to_agent_name | null &#124; string | Name of the callable agent this message was sent to. Absent when sent to the primary agent. |
| data.from_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread that sent the message. |
| data.from_agent_name | null &#124; string | Name of the callable agent this message came from. Absent when received from the primary agent. |
| data.event_id | string | Text of the block. / Id of the event this event refers to. / Text of the block. / Text of the block. / Id of the event this event refers to. / Text of the block. |
| data.sources | array&lt;object&gt; | Background work that woke the session with this notification. |
| data.forked_from_session_id | string | Id of the parent session this session was forked from. |
| data.forked_from_message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |
| data.action | string | What changed in the goal. |
| data.goal | object &#124; null | The goal as the change left it, or null when the session has no goal. |
| data.previous_goal | object &#124; null | The goal before the change, or null when there was none. |
| data.status | string | Where the check stands. Read &#96;verification.passed&#96; on the closing event to know whether the goal counts as done. |
| data.goal_id | string | The goal this check belongs to. |
| data.goal_iteration | integer | Which check of this goal, matching &#96;iteration&#96; on the goal. |
| data.verification_id | string | Identifier shared by every event of one check. |
| data.anchor_message_id | string &#124; null | The assistant message the check follows, or null. |
| data.verification | object | The verdict; absent on &#96;started&#96;. |
| data.event | object | Event name or event payload. |
| data.delta | object | Incremental fragment of the event being produced. |

## 用 WebSocket 接收 [#用-websocket-接收]

同一地址也可以用 `wss://` 建立只读 WebSocket，每个事件一帧，适合服务端长连接。连接、帧格式、关闭码与限额见[用 WebSocket 订阅事件](/docs/api/native/agent/streamEventsWebSocket)。

# 用 WebSocket 订阅事件

会话事件除了用 [订阅事件](/docs/api/native/agent/streamEvents)（SSE）拉取，也可以在**同一个地址**上建立 WebSocket 接收：每个事件一帧，内容与 SSE 的事件数据完全相同。这是本平台在官方 SSE 之外额外提供的接入方式，适合在服务端长期挂着连接、把事件转发给自己系统的场景。

```text
wss://api.deepraxis.com/agent/v1/sessions/{session_id}/events/stream
```

这条连接是**只读**的：它只推送事件，不接收任何消息。发消息、打断仍然用 [发送事件](/docs/api/native/agent/sendEvents)。

## 握手与认证 [#握手与认证]

握手请求带与 HTTP 接口相同的认证头：`Authorization: Bearer <API Key>` 或 `x-api-key: <API Key>`。

浏览器原生的 `WebSocket` 不能设置请求头，所以这是**服务端用法**。浏览器里请用 SSE，或者由你的服务端建立连接后再转给前端。

握手失败时连接不会建立，服务端直接返回 HTTP 错误（错误体格式见[错误](/docs/api/errors)）：

| 情况                      | 返回                                 |
| ----------------------- | ---------------------------------- |
| 没带凭证，或 Key 无效、已禁用       | `401`                              |
| 会话不存在，或不属于这个 Key 所在的工作区 | `404`                              |
| 同时进行的请求超过 Key 的并发上限     | `429`，见[限流](/docs/api/rate-limits) |

一条打开的 WebSocket 和一个进行中的 SSE 一样，会一直占用 Key 的一个并发名额，直到连接关闭。

## 帧 [#帧]

每一帧都是一个 JSON 文本。连接建立后，第一帧是就绪通知：

```json
{"type":"session.events.ready"}
```

收到它之后，会话里产生的每个事件以一帧送达，`event` 字段就是 SSE 里的事件数据：

```json
{"type":"session.event","event":{"id":"d4dc3d96-…","type":"agent.message","processed_at":"2026-09-26T13:35:04.906Z","content":[{"type":"text","text":"好"}]}}
```

| 字段      | 说明                                                                         |
| ------- | -------------------------------------------------------------------------- |
| `type`  | `session.events.ready`（就绪，只出现一次）或 `session.event`（一个事件）                    |
| `event` | 仅 `session.event` 帧有；结构与[事件列表](/docs/api/native/agent/listEvents)返回的单个事件相同 |

同一个事件可能送达不止一次。例如一条 `user.message` 会先以 `processed_at: null`（已接纳、待处理）出现，被处理后再以带时间的形式出现一次。请按 `event.id` 去重，以最后一次为准。

## 关闭码 [#关闭码]

| 关闭码    | 含义          | 你该做什么          |
| ------ | ----------- | -------------- |
| `1000` | 服务端正常结束订阅   | 需要继续接收就重新连接    |
| `1008` | 客户端向连接发送了消息 | 这条连接只读；不要发送任何帧 |
| `1011` | 服务端内部中断     | 重新连接，并用事件列表回填  |
| `1013` | 暂时超出限额（见下）  | 重新连接，并用事件列表回填  |

## 限额 [#限额]

* 一条连接累计最多推送约 **512 KB** 的事件，超出后以 `1013` 关闭。长会话请准备好重连。
* 服务端与会话之间的内部连接断开时会自动重试；多次重试仍失败，也以 `1013` 关闭。

## 断线与回填 [#断线与回填]

断开期间产生的事件**不会补发**。重新连接后，用[事件列表](/docs/api/native/agent/listEvents)按时间补齐：

```http
GET /agent/v1/sessions/{session_id}/events?order=asc&created_at[gt]=<你收到的最后一个事件的 processed_at>
```

回填的事件和新连接推送的事件可能重叠，按 `event.id` 去重即可。

## 示例 [#示例]

Bun（内置 `WebSocket` 支持 `headers`）：

```ts
const ws = new WebSocket(
  `wss://api.deepraxis.com/agent/v1/sessions/${sessionId}/events/stream`,
  { headers: { Authorization: `Bearer ${process.env.PRAXIS_API_KEY}` } },
);
ws.addEventListener("message", (message) => {
  const frame = JSON.parse(String(message.data));
  if (frame.type === "session.events.ready") console.log("ready");
  if (frame.type === "session.event") console.log(frame.event.type, frame.event);
});
ws.addEventListener("close", (close) => console.log("closed", close.code));
```

Node（`ws` 包）：

```ts
import WebSocket from "ws";

const ws = new WebSocket(
  `wss://api.deepraxis.com/agent/v1/sessions/${sessionId}/events/stream`,
  { headers: { Authorization: `Bearer ${process.env.PRAXIS_API_KEY}` } },
);
ws.on("message", (data) => {
  const frame = JSON.parse(String(data));
  if (frame.type === "session.event") console.log(frame.event.type, frame.event);
});
ws.on("close", (code) => console.log("closed", code));
```

Python（`websockets` 包）：

```python
import asyncio, json, os
import websockets

async def main(session_id: str):
    url = f"wss://api.deepraxis.com/agent/v1/sessions/{session_id}/events/stream"
    headers = {"Authorization": f"Bearer {os.environ['PRAXIS_API_KEY']}"}
    async with websockets.connect(url, additional_headers=headers) as ws:
        async for message in ws:
            frame = json.loads(message)
            if frame["type"] == "session.event":
                print(frame["event"]["type"], frame["event"])

asyncio.run(main("sesn_123"))
```

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Session id (sesn_...). Pass it as session_id in every session call. |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| agent.description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| agent.mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| agent.skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| agent.system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| agent.tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| agent.type | string | Always &#96;agent&#96;. An agent definition. |
| agent.version | number | The agent's current version. Starts at 1 and increments each time the agent is modified. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string | Always &#96;limit&#96;. A spending limit. |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string | Id of the environment recipe the session's sandbox was created from. Omitted when no recipe was selected, that is, for a light machine or the Computer chosen by computer_id. |
| metadata | object | Free-form string key/value pairs stored with the session, changed through sessions.update patch semantics. |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string | Always &#96;outcome_evaluation&#96;. Record of one outcome evaluation. |
| resources | array&lt;object&gt; | Resources attached to the session, at most 500; each is a file reference mounted into the session's machine. |
| resources[].id | string | Resource id, the resource_id of sessions.resources calls. |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Path inside the machine where the file is mounted; defaults to /mnt/session/uploads/&lt;file_id&gt;, and custom paths are rooted there. / Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string | Always &#96;github_repository&#96;. A GitHub repository resource; not supported on this platform. / Always &#96;file&#96;. A file resource: an uploaded file mounted into the session's machine. / Always &#96;memory_store&#96;. A memory store resource; not supported on this platform. |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string | Repository URL. |
| resources[].checkout | null &#124; object | Branch or commit to check out. |
| resources[].file_id | string | Id of the uploaded file; it must exist and belong to your tenant. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string | Title of the session, set on create or through sessions.update; null when none was set. |
| type | string | Always &#96;session&#96;. A session, one conversation of an agent on a machine. |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |
| cwd | string | Normalized session working directory; defaults to /home/user/workspace. Forks inherit this directory. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| model | object | Praxis extension: the currently selected session model. |
| model.id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| model.thinking | object &#124; null | Supported thinking controls, or null when capability is unknown or unavailable. efforts lists selectable strengths; can_disable permits none; default_effort is nullable. |
| thinking | object &#124; null | Praxis extension: explicit session thinking effort; null inherits the pinned agent default, then the model default. none disables thinking only when model.thinking.can_disable is true. Unsupported efforts return 400 invalid_request_error. |
| thinking.effort | string | Thinking level saved for this session: low, medium, high, xhigh, or none to turn thinking off. Null or absent means the session inherits the agent default and then the model default. |
| forked_from | object &#124; null | Praxis extension: source of a forked session; null for other sessions. Available only on /agent/v1. |
| forked_from.session_id | string | Id of the parent session this session was forked from; it is left unchanged by the fork. |
| forked_from.message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |

# 归档会话

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Session id (sesn_...). Pass it as session_id in every session call. |
| agent | object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| agent.id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| agent.description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| agent.mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| agent.model | object | Model identifier and configuration. |
| agent.multiagent | null &#124; object | Resolved coordinator topology with full agent definitions for each roster member. |
| agent.name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| agent.skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| agent.system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| agent.tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| agent.type | string | Always &#96;agent&#96;. An agent definition. |
| agent.version | number | The agent's current version. Starts at 1 and increments each time the agent is modified. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| budget.max_list_cost | object | A monetary amount in a specific currency. |
| budget.type | string | Always &#96;limit&#96;. A spending limit. |
| created_at | string | A timestamp in RFC 3339 format |
| environment_id | string | Id of the environment recipe the session's sandbox was created from. Omitted when no recipe was selected, that is, for a light machine or the Computer chosen by computer_id. |
| metadata | object | Free-form string key/value pairs stored with the session, changed through sessions.update patch semantics. |
| outcome_evaluations | array&lt;object&gt; | Per-outcome evaluation state. One entry per &#96;define_outcome&#96; event sent to the session. |
| outcome_evaluations[].completed_at | null &#124; string | A timestamp in RFC 3339 format |
| outcome_evaluations[].description | string | What the agent should produce. |
| outcome_evaluations[].explanation | null &#124; string | Grader's verdict text from the most recent evaluation. For &#96;satisfied&#96;, explains why criteria are met; for &#96;needs_revision&#96; (intermediate), what's missing; for &#96;failed&#96;, why unrecoverable. |
| outcome_evaluations[].iteration | number | 0-indexed revision cycle the outcome is currently on. |
| outcome_evaluations[].outcome_id | string | Server-generated outc\_ ID for this outcome. |
| outcome_evaluations[].result | string | Current evaluation state. &#96;pending&#96; before the agent begins work; &#96;running&#96; while producing or revising; &#96;evaluating&#96; while the grader scores; &#96;satisfied&#96;/&#96;max_iterations_reached&#96;/&#96;failed&#96;/&#96;interrupted&#96; are terminal. |
| outcome_evaluations[].type | string | Always &#96;outcome_evaluation&#96;. Record of one outcome evaluation. |
| resources | array&lt;object&gt; | Resources attached to the session, at most 500; each is a file reference mounted into the session's machine. |
| resources[].id | string | Resource id, the resource_id of sessions.resources calls. |
| resources[].created_at | string | A timestamp in RFC 3339 format |
| resources[].mount_path | string &#124; null &#124; string | Path inside the machine where the file is mounted; defaults to /mnt/session/uploads/&lt;file_id&gt;, and custom paths are rooted there. / Filesystem path where the store is mounted in the session container, e.g. /mnt/memory/user-preferences. Derived from the store's name. Output-only. |
| resources[].type | string | Always &#96;github_repository&#96;. A GitHub repository resource; not supported on this platform. / Always &#96;file&#96;. A file resource: an uploaded file mounted into the session's machine. / Always &#96;memory_store&#96;. A memory store resource; not supported on this platform. |
| resources[].updated_at | string | A timestamp in RFC 3339 format |
| resources[].url | string | Repository URL. |
| resources[].checkout | null &#124; object | Branch or commit to check out. |
| resources[].file_id | string | Id of the uploaded file; it must exist and belong to your tenant. |
| resources[].memory_store_id | string | The memory store ID (memstore\_...). Must belong to the caller's organization and workspace. |
| resources[].access | null &#124; string | Access mode for an attached memory store. |
| resources[].description | string | Description of the memory store, snapshotted at attach time. Rendered into the agent's system prompt. Empty string when the store has no description. |
| resources[].instructions | null &#124; string | Per-attachment guidance for the agent on how to use this store. Rendered into the memory section of the system prompt. Max 4096 chars. |
| resources[].name | null &#124; string | Display name of the memory store, snapshotted at attach time. Later edits to the store's name do not propagate to this resource. |
| stats | object | Timing statistics for a session. |
| stats.active_seconds | number | Cumulative time in seconds the session spent in &#96;running&#96; status. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since session creation in seconds. For terminated sessions, frozen at the final update. |
| status | string | SessionStatus enum  - &#96;rescheduling&#96; - Transient error occurred, retrying automatically. - &#96;running&#96; - Agent is actively executing. - &#96;idle&#96; - Agent is waiting for input, including user messages or tool   confirmations. Sessions start in idle. - &#96;terminated&#96; - Session has ended, either due to an error or completion. |
| title | null &#124; string | Title of the session, set on create or through sessions.update; null when none was set. |
| type | string | Always &#96;session&#96;. A session, one conversation of an agent on a machine. |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | object | Cumulative token usage for a session across all turns. |
| usage.active_seconds | number | Cumulative time in seconds during which the session had at least one thread in running status. Overlapping activity from concurrent threads is counted once, unlike &#96;stats.active_seconds&#96;, which sums each thread's own active time. This is the duration the session's runtime cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |
| vault_ids | array&lt;string&gt; | Vault IDs attached to the session at creation. Empty when no vaults were supplied. |
| deployment_id | null &#124; string | Deployment ID when the session was created from a deployment reference. Null otherwise. |
| cwd | string | Normalized session working directory; defaults to /home/user/workspace. Forks inherit this directory. |
| computer_id | string | Praxis extension: MA only has session-scoped temporary containers and memory_stores, not durable browsable computers. computer_id selects a tenant-owned active computer. Session selection overrides the agent default; a sandbox environment_id and computer_id cannot be combined. Omitted when no computer is selected. |
| model | object | Praxis extension: the currently selected session model. |
| model.id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| model.thinking | object &#124; null | Supported thinking controls, or null when capability is unknown or unavailable. efforts lists selectable strengths; can_disable permits none; default_effort is nullable. |
| thinking | object &#124; null | Praxis extension: explicit session thinking effort; null inherits the pinned agent default, then the model default. none disables thinking only when model.thinking.can_disable is true. Unsupported efforts return 400 invalid_request_error. |
| thinking.effort | string | Thinking level saved for this session: low, medium, high, xhigh, or none to turn thinking off. Null or absent means the session inherits the agent default and then the model default. |
| forked_from | object &#124; null | Praxis extension: source of a forked session; null for other sessions. Available only on /agent/v1. |
| forked_from.session_id | string | Id of the parent session this session was forked from; it is left unchanged by the fork. |
| forked_from.message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Unique identifier for this thread. |
| data[].agent | object | The resolved agent a &#96;session_thread&#96; runs. |
| data[].archived_at | null &#124; string | A timestamp in RFC 3339 format |
| data[].created_at | string | A timestamp in RFC 3339 format |
| data[].parent_thread_id | null &#124; string | Parent thread that spawned this thread. Null for the primary thread. |
| data[].session_id | string | The session this thread belongs to. |
| data[].stats | null &#124; object | Timing statistics for a session thread. |
| data[].status | string | SessionThreadStatus enum |
| data[].type | string | Always &#96;session_thread&#96;. An execution thread of a session. |
| data[].updated_at | string | A timestamp in RFC 3339 format |
| data[].usage | null &#124; object | Cumulative token usage for a session thread across all turns. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this thread. |
| agent | object | The resolved agent a &#96;session_thread&#96; runs. |
| agent.model | string &#124; object | The advisor model id. / Model identifier and configuration. |
| agent.type | string | Always &#96;advisor&#96;. An advisor whose model is consulted for advice in a separate thread (at most one per coordinator). / Always &#96;agent&#96;. A roster member that refers to an agent by id and pinned version. |
| agent.id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| agent.description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| agent.mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| agent.name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| agent.skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| agent.system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| agent.tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| agent.version | number | The agent's current version. Starts at 1 and increments each time the agent is modified. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| parent_thread_id | null &#124; string | Parent thread that spawned this thread. Null for the primary thread. |
| session_id | string | The session this thread belongs to. |
| stats | null &#124; object | Timing statistics for a session thread. |
| stats.active_seconds | number | Cumulative time in seconds the thread spent actively running. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since thread creation in seconds. For archived threads, frozen at the final update. |
| stats.startup_seconds | number | Time in seconds for the thread to begin running. Zero for child threads, which start immediately. |
| status | string | SessionThreadStatus enum |
| type | string | Always &#96;session_thread&#96;. An execution thread of a session. |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | null &#124; object | Cumulative token usage for a session thread across all turns. |
| usage.active_seconds | number | Cumulative time in seconds this thread spent in running status. Equal to &#96;stats.active_seconds&#96;; surfaced here so a thread's usage carries every quantity its cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Unique identifier for this event. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. |
| data[].content | array&lt;object&gt; | Array of content blocks comprising the user message. / The result content returned by the tool. / Array of text blocks comprising the agent response. / The result content returned by the tool. / The result content returned by the tool. / Message content blocks. / Message content blocks. / The result content returned by the tool. / System content blocks. Text-only. |
| data[].type | string | Always &#96;user.message&#96;. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. The user interrupted the running turn. / Always &#96;user.tool_confirmation&#96;. The user's decision to allow or deny a tool call that waits for approval. / Always &#96;user.custom_tool_result&#96;. The user's result for a custom tool call. / Always &#96;agent.custom_tool_use&#96;. The agent called a custom tool defined by the client. / Always &#96;agent.message&#96;. A message from the agent, with text content blocks. / Always &#96;agent.thinking&#96;. The agent's thinking text for a step. / Always &#96;agent.mcp_tool_use&#96;. The agent called an MCP tool. / Always &#96;agent.mcp_tool_result&#96;. The result of an MCP tool call. / Always &#96;agent.tool_use&#96;. The agent called a tool. / Always &#96;agent.tool_result&#96;. The result of a tool call. / Always &#96;agent.thread_message_received&#96;. The agent received a message from another thread. / Always &#96;agent.thread_message_sent&#96;. The agent sent a message to another thread. / Always &#96;agent.thread_context_compacted&#96;. The thread's context was compacted into a summary. / Always &#96;session.error&#96;. The session hit an error. / Always &#96;session.status_rescheduled&#96;. The session will retry after a recoverable error. / Always &#96;session.status_running&#96;. The session started running a turn. / Always &#96;session.status_idle&#96;. The session stopped running; stop_reason says why. / Always &#96;session.status_terminated&#96;. The session ended and accepts no more work. / Always &#96;session.thread_created&#96;. A child thread was started. / Always &#96;span.outcome_evaluation_start&#96;. An outcome evaluation started. / Always &#96;span.outcome_evaluation_end&#96;. An outcome evaluation ended. / Always &#96;span.model_request_start&#96;. A model request started. / Always &#96;span.model_request_end&#96;. A model request ended, with its usage. / Always &#96;span.outcome_evaluation_ongoing&#96;. An outcome evaluation is still running. / Always &#96;user.define_outcome&#96;. The user defined the outcome the agent should reach. / Always &#96;session.deleted&#96;. The session was deleted. / Always &#96;session.thread_status_running&#96;. A thread started running. / Always &#96;session.thread_status_idle&#96;. A thread stopped running; stop_reason says why. / Always &#96;session.thread_status_terminated&#96;. A thread ended. / Always &#96;user.tool_result&#96;. The user's result for a client-side tool call. / Always &#96;session.thread_status_rescheduled&#96;. A thread will retry after a recoverable error. / Always &#96;session.updated&#96;. The session's model, title, metadata, agent or budget changed. / Always &#96;system.message&#96;. A message produced by the platform rather than the user or the agent. / Always &#96;session.usage&#96;. Cumulative usage of the session. / Always &#96;session.forked&#96;. The session was created by forking another session. / Always &#96;session.goal_changed&#96;. / Always &#96;session.goal_verification&#96;. / Always &#96;user.steer&#96;. Receipt that a queued user.message was injected into the running turn. |
| data[].processed_at | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string | A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / When the event was recorded, RFC 3339. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. |
| data[].message_id | string | UI transcript message ID. Use the last assistant message in a successfully completed turn as the fork target. / UI transcript message ID shared with this assistant's message parts. |
| data[].session_thread_id | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string | If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Set by the server to the subagent thread this confirmation was routed to. Omitted when it was routed to the primary thread. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / When set, this event was cross-posted from a subagent's thread to surface its custom tool use on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.custom_tool_result&#96; by &#96;custom_tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; or &#96;user.tool_result&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / Public &#96;sthr_&#96; ID of the newly created thread. / Public sthr\_ ID of the thread that started running. / Public sthr\_ ID of the thread that went idle. / Public sthr\_ ID of the thread that terminated. / Set by the server to the subagent thread this result was routed to. Omitted when it was routed to the primary thread. / Public sthr\_ ID of the thread that is retrying. |
| data[].result | string | UserToolConfirmationResult enum / Evaluation verdict. 'satisfied': criteria met, session goes idle. 'needs_revision': criteria not met, another revision cycle follows. 'max_iterations_reached': evaluation budget exhausted with criteria still unmet — one final acknowledgment turn follows before the session goes idle, but no further evaluation runs. 'failed': grader determined the rubric does not apply to the deliverables. 'interrupted': user sent an interrupt while evaluation was in progress. |
| data[].tool_use_id | string | The id of the &#96;agent.tool_use&#96; or &#96;agent.mcp_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. / The id of the &#96;agent.tool_use&#96; event this result corresponds to. / The id of the &#96;agent.tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].deny_message | null &#124; string | Optional message providing context for a 'deny' decision. Only allowed when result is 'deny'. |
| data[].custom_tool_use_id | string | The id of the &#96;agent.custom_tool_use&#96; event this result corresponds to, which can be found in the last &#96;session.status_idle&#96; [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids) &#96;stop_reason.event_ids&#96; field. |
| data[].is_error | null &#124; boolean | Whether the tool execution resulted in an error. / Whether the model request resulted in an error. / Whether the tool execution resulted in an error. |
| data[].input | object | Input parameters for the tool call. |
| data[].name | string | Name of the custom tool being called. / Name of the MCP tool being used. / Name of the agent tool being used. |
| data[].mcp_server_name | string | Name of the MCP server providing the tool. |
| data[].evaluated_permission | string | AgentEvaluatedPermission enum |
| data[].evaluation | object | Names the resolved permission_policy that produced evaluated_permission, and under auto carries the judgement. Open union: clients must tolerate unknown variants. |
| data[].parent_tool_use_id | string | Praxis extension (MCP Apps, SEP-1865): present when &#96;source&#96; is &#96;codemode&#96;; the id of the codemode tool use whose program made this call. Absent otherwise. |
| data[]._meta | object | Praxis extension (MCP Apps, SEP-1865): the &#96;ui&#96; and &#96;openai/ui&#96; keys of the MCP tool definition's &#96;_meta&#96;, verbatim; other &#96;_meta&#96; keys are not exposed. When &#96;ui.resourceUri&#96; is a &#96;ui://&#96; URI, the tool has an interactive view: a client that implements MCP Apps can fetch that resource from the MCP server and render it for this call. Absent when the tool declares neither key. Clients that do not render MCP Apps ignore it. / Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;_meta&#96;, verbatim. Views use it for data that should not reach the model; absent when the tool returned none. |
| data[].source | string | Praxis extension (MCP Apps, SEP-1865): &#96;app&#96; when the call was made by an MCP Apps view, &#96;codemode&#96; when a program run by the codemode tool called an MCP tool that declares a view (the event pair exists so a client can render that view; the model already has the result in the codemode tool result); absent for the model's own calls. / What caused the change. |
| data[].mcp_tool_use_id | string | The id of the &#96;agent.mcp_tool_use&#96; event this result corresponds to. |
| data[].structured_content | any | Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;structuredContent&#96;, verbatim JSON. MCP Apps views read it as the data to render; absent when the tool returned none. |
| data[].from_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread that sent the message. |
| data[].from_agent_name | null &#124; string | Name of the callable agent this message came from. Absent when received from the primary agent. |
| data[].to_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread the message was sent to. |
| data[].to_agent_name | null &#124; string | Name of the callable agent this message was sent to. Absent when sent to the primary agent. |
| data[].error | object | Description of the error and what the client should do next. |
| data[].stop_reason | object | Why the session stopped running, with the variant data needed to continue. |
| data[].agent_name | string | Name of the callable agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. |
| data[].iteration | number | 0-indexed revision cycle. 0 is the first evaluation; 1 is the re-evaluation after the first revision; etc. / 0-indexed revision cycle, matching the corresponding &#96;span.outcome_evaluation_start&#96;. / 0-indexed revision cycle, matching the corresponding &#96;span.outcome_evaluation_start&#96;. |
| data[].outcome_id | string | The &#96;outc_&#96; ID of the outcome being evaluated. / Server-generated &#96;outc_&#96; ID for this outcome. Referenced by &#96;span.outcome_evaluation_*&#96; events and the session's &#96;outcome_evaluations&#96; list. |
| data[].explanation | string | Human-readable explanation of the verdict. For &#96;needs_revision&#96;, describes which criteria failed and why. |
| data[].outcome_evaluation_start_id | string | The id of the corresponding &#96;span.outcome_evaluation_start&#96; event. |
| data[].usage | object | Token usage for a single model request. / Point-in-time snapshot of a session's cumulative usage. |
| data[].model_request_start_id | string | The id of the corresponding &#96;span.model_request_start&#96; event. |
| data[].model_usage | object | Token usage for a single model request. |
| data[].description | string | What the agent should produce. Copied from the input event. |
| data[].max_iterations | null &#124; number | Evaluate-then-revise cycles before giving up. Default 3, max 20. |
| data[].rubric | object | Rubric for grading the quality of an outcome. |
| data[].agent | null &#124; object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| data[].budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| data[].metadata | object | The session's full metadata bag after the update. Present when the update set non-empty metadata; absent when metadata was unchanged or cleared to empty. |
| data[].title | null &#124; string | The session's new title. Present only when the update changed it. |
| data[].model | object | Praxis extension: the changed session model, present only on /agent/v1 session.updated events. Model-only updates are omitted on /anthropic. |
| data[].forked_from_session_id | string | Id of the parent session this session was forked from. |
| data[].forked_from_message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |
| data[].action | string | What changed in the goal. |
| data[].goal | object &#124; null | The goal as the change left it, or null when the session has no goal. |
| data[].previous_goal | object &#124; null | The goal before the change, or null when there was none. |
| data[].status | string | Where the check stands. Read &#96;verification.passed&#96; on the closing event to know whether the goal counts as done. |
| data[].goal_id | string | The goal this check belongs to. |
| data[].goal_iteration | integer | Which check of this goal, matching &#96;iteration&#96; on the goal. |
| data[].verification_id | string | Identifier shared by every event of one check. |
| data[].anchor_message_id | string &#124; null | The assistant message the check follows, or null. |
| data[].verification | object | The verdict; absent on &#96;started&#96;. |
| data[].event_id | string | Id of the event this event refers to. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Server-sent events

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Identifier of the object, as returned by the API; pass it in the path of follow-up calls on the same resource. |
| event | string | Server-Sent Events event name of this frame. / Always &#96;user.message&#96;. SSE event name of this frame; its data is a user.message payload. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. SSE event name of this frame; its data is a user.interrupt payload. The user interrupted the running turn. / Always &#96;agent.message&#96;. SSE event name of this frame; its data is a agent.message payload. A message from the agent, with text content blocks. / Always &#96;agent.thinking&#96;. SSE event name of this frame; its data is a agent.thinking payload. The agent's thinking text for a step. / Always &#96;session.status_running&#96;. SSE event name of this frame; its data is a session.status_running payload. The session started running a turn. / Always &#96;session.status_rescheduled&#96;. SSE event name of this frame; its data is a session.status_rescheduled payload. The session will retry after a recoverable error. / Always &#96;session.status_idle&#96;. SSE event name of this frame; its data is a session.status_idle payload. The session stopped running; stop_reason says why. / Always &#96;session.status_terminated&#96;. SSE event name of this frame; its data is a session.status_terminated payload. The session ended and accepts no more work. / Always &#96;agent.thread_context_compacted&#96;. SSE event name of this frame; its data is a agent.thread_context_compacted payload. The thread's context was compacted into a summary. / Always &#96;agent.thread_context_reset&#96;. SSE event name of this frame; its data is a agent.thread_context_reset payload. Content was removed from the model's context after a content-safety refusal. / Always &#96;session.updated&#96;. SSE event name of this frame; its data is a session.updated payload. The session's model, title, metadata, agent or budget changed. / Always &#96;session.error&#96;. SSE event name of this frame; its data is a session.error payload. The session hit an error. / Always &#96;session.usage&#96;. SSE event name of this frame; its data is a session.usage payload. Cumulative usage of the session. / Always &#96;span.model_request_start&#96;. SSE event name of this frame; its data is a span.model_request_start payload. A model request started. / Always &#96;span.model_request_end&#96;. SSE event name of this frame; its data is a span.model_request_end payload. A model request ended, with its usage. / Always &#96;agent.tool_use&#96;. SSE event name of this frame; its data is a agent.tool_use payload. The agent called a tool. / Always &#96;agent.tool_result&#96;. SSE event name of this frame; its data is a agent.tool_result payload. The result of a tool call. / Always &#96;agent.mcp_tool_use&#96;. SSE event name of this frame; its data is a agent.mcp_tool_use payload. The agent called an MCP tool. / Always &#96;agent.mcp_tool_result&#96;. SSE event name of this frame; its data is a agent.mcp_tool_result payload. The result of an MCP tool call. / Always &#96;user.tool_confirmation&#96;. SSE event name of this frame; its data is a user.tool_confirmation payload. The user's decision to allow or deny a tool call that waits for approval. / Always &#96;session.thread_created&#96;. SSE event name of this frame; its data is a session.thread_created payload. A child thread was started. / Always &#96;session.thread_status_running&#96;. SSE event name of this frame; its data is a session.thread_status_running payload. A thread started running. / Always &#96;session.thread_status_idle&#96;. SSE event name of this frame; its data is a session.thread_status_idle payload. A thread stopped running; stop_reason says why. / Always &#96;session.thread_status_rescheduled&#96;. SSE event name of this frame; its data is a session.thread_status_rescheduled payload. A thread will retry after a recoverable error. / Always &#96;session.thread_status_terminated&#96;. SSE event name of this frame; its data is a session.thread_status_terminated payload. A thread ended. / Always &#96;agent.thread_message_sent&#96;. SSE event name of this frame; its data is a agent.thread_message_sent payload. The agent sent a message to another thread. / Always &#96;agent.thread_message_received&#96;. SSE event name of this frame; its data is a agent.thread_message_received payload. The agent received a message from another thread. / Always &#96;user.withdraw&#96;. SSE event name of this frame; its data is a user.withdraw payload. A queued user.message was withdrawn before it ran. / Always &#96;user.steer&#96;. SSE event name of this frame; its data is a user.steer payload. Receipt that a queued user.message was injected into the running turn. / Always &#96;system.notification&#96;. SSE event name of this frame; its data is a system.notification payload. Background work woke the session with a notification. / Always &#96;session.forked&#96;. SSE event name of this frame; its data is a session.forked payload. The session was created by forking another session. / Always &#96;session.goal_changed&#96;. SSE event name of this frame; its data is a session.goal_changed payload. The session's goal was set, changed status, accounted usage or was cleared. / Always &#96;session.goal_verification&#96;. SSE event name of this frame; its data is a session.goal_verification payload. One completion check of the session's goal started or ended. / Always &#96;event_start&#96;. SSE event name of this frame; its data is a event_start payload. Preview that an event of the requested delta types has started. / Always &#96;event_delta&#96;. SSE event name of this frame; its data is a event_delta payload. Incremental fragment of the event being produced. / Always &#96;ping&#96;. SSE event name of this frame; its data is a ping payload. Keep-alive frame; carries no data. / Always &#96;error&#96;. SSE event name of this frame; its data is a error payload. A stream error. |
| data | object | Decoded JSON payload of this frame; its shape is selected by the event name. / Praxis extension (AskUserQuestion, own face only): the confirmation of an AskUserQuestion call, with the answers it carried. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Praxis extension (goal mode, own face only): the session's goal was set, moved to another status, accounted usage or was cleared. &#96;goal&#96; is the goal after the change, &#96;previous_goal&#96; the one before; each is null when there was none. / Praxis extension (goal mode, own face only): one completion check of the goal. A &#96;started&#96; event opens it; &#96;completed&#96;, &#96;failed_closed&#96; or &#96;cancelled&#96; closes it. Events of one check share &#96;verification_id&#96;. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. / Decoded JSON payload of this frame; its shape is selected by the event name. |
| data.id | string | Unique identifier for this event. / Text of the block. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Event id, unique within the session. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Text of the block. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Text of the block. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Text of the block. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Event id, unique within the session. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Unique identifier for this event. / Text of the block. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Text of the block. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. / Event id, unique within the session. / Event id, unique within the session. Use it to refer to this event, for example in user.tool_confirmation or user.steer. |
| data.content | array&lt;object&gt; | Array of content blocks comprising the user message. / Array of text blocks comprising the agent response. / Content blocks of the event, in order. / The result content returned by the tool. / The result content returned by the tool. / Message content blocks. / Message content blocks. / Array of content blocks comprising the user message. / Array of text blocks comprising the agent response. / Content blocks of the event, in order. / The result content returned by the tool. / The result content returned by the tool. / Message content blocks. / Message content blocks. |
| data.type | string | Always &#96;user.message&#96;. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. The user interrupted the running turn. / Always &#96;agent.message&#96;. A message from the agent, with text content blocks. / Always &#96;agent.thinking&#96;. The agent's thinking text for a step. / Always &#96;session.status_running&#96;. The session started running a turn. / Always &#96;session.status_rescheduled&#96;. The session will retry after a recoverable error. / Always &#96;session.status_idle&#96;. The session stopped running; stop_reason says why. / Always &#96;session.status_terminated&#96;. The session ended and accepts no more work. / Always &#96;agent.thread_context_compacted&#96;. The thread's context was compacted into a summary. / Always &#96;agent.thread_context_reset&#96;. Content was removed from the model's context after a content-safety refusal. / Always &#96;session.updated&#96;. The session's model, title, metadata, agent or budget changed. / Always &#96;session.error&#96;. The session hit an error. / Always &#96;session.usage&#96;. Cumulative usage of the session. / Always &#96;span.model_request_start&#96;. A model request started. / Always &#96;span.model_request_end&#96;. A model request ended, with its usage. / Always &#96;agent.tool_use&#96;. The agent called a tool. / Always &#96;agent.tool_result&#96;. The result of a tool call. / Always &#96;agent.mcp_tool_use&#96;. The agent called an MCP tool. / Always &#96;agent.mcp_tool_result&#96;. The result of an MCP tool call. / Always &#96;user.tool_confirmation&#96;. / Always &#96;session.thread_created&#96;. A child thread was started. / Always &#96;session.thread_status_running&#96;. A thread started running. / Always &#96;session.thread_status_idle&#96;. A thread stopped running; stop_reason says why. / Always &#96;session.thread_status_rescheduled&#96;. A thread will retry after a recoverable error. / Always &#96;session.thread_status_terminated&#96;. A thread ended. / Always &#96;agent.thread_message_sent&#96;. The agent sent a message to another thread. / Always &#96;agent.thread_message_received&#96;. The agent received a message from another thread. / Always &#96;user.withdraw&#96;. A queued user.message was withdrawn before it ran. / Always &#96;user.steer&#96;. Receipt that a queued user.message was injected into the running turn. / Always &#96;system.notification&#96;. Background work woke the session with a notification. / Always &#96;session.forked&#96;. The session was created by forking another session. / Always &#96;session.goal_changed&#96;. / Always &#96;session.goal_verification&#96;. / Always &#96;event_start&#96;. Preview that an event of the requested delta types has started. / Always &#96;event_delta&#96;. Incremental fragment of the event being produced. / Always &#96;ping&#96;. Keep-alive frame; carries no data. / Always &#96;error&#96;. A stream error. / Always &#96;user.message&#96;. A message from the user to the agent, with content blocks. / Always &#96;user.interrupt&#96;. The user interrupted the running turn. / Always &#96;agent.message&#96;. A message from the agent, with text content blocks. / Always &#96;agent.thinking&#96;. The agent's thinking text for a step. / Always &#96;session.status_running&#96;. The session started running a turn. / Always &#96;session.status_rescheduled&#96;. The session will retry after a recoverable error. / Always &#96;session.status_idle&#96;. The session stopped running; stop_reason says why. / Always &#96;session.status_terminated&#96;. The session ended and accepts no more work. / Always &#96;agent.thread_context_compacted&#96;. The thread's context was compacted into a summary. / Always &#96;agent.thread_context_reset&#96;. Content was removed from the model's context after a content-safety refusal. / Always &#96;session.updated&#96;. The session's model, title, metadata, agent or budget changed. / Always &#96;session.error&#96;. The session hit an error. / Always &#96;session.usage&#96;. Cumulative usage of the session. / Always &#96;span.model_request_start&#96;. A model request started. / Always &#96;span.model_request_end&#96;. A model request ended, with its usage. / Always &#96;agent.tool_use&#96;. The agent called a tool. / Always &#96;agent.tool_result&#96;. The result of a tool call. / Always &#96;agent.mcp_tool_use&#96;. The agent called an MCP tool. / Always &#96;agent.mcp_tool_result&#96;. The result of an MCP tool call. / Always &#96;user.tool_confirmation&#96;. / Always &#96;session.thread_created&#96;. A child thread was started. / Always &#96;session.thread_status_running&#96;. A thread started running. / Always &#96;session.thread_status_idle&#96;. A thread stopped running; stop_reason says why. / Always &#96;session.thread_status_rescheduled&#96;. A thread will retry after a recoverable error. / Always &#96;session.thread_status_terminated&#96;. A thread ended. / Always &#96;agent.thread_message_sent&#96;. The agent sent a message to another thread. / Always &#96;agent.thread_message_received&#96;. The agent received a message from another thread. / Always &#96;user.withdraw&#96;. A queued user.message was withdrawn before it ran. / Always &#96;user.steer&#96;. Receipt that a queued user.message was injected into the running turn. / Always &#96;system.notification&#96;. Background work woke the session with a notification. / Always &#96;session.forked&#96;. The session was created by forking another session. / Always &#96;session.goal_changed&#96;. / Always &#96;session.goal_verification&#96;. / Always &#96;event_start&#96;. Preview that an event of the requested delta types has started. / Always &#96;event_delta&#96;. Incremental fragment of the event being produced. / Always &#96;ping&#96;. Keep-alive frame; carries no data. / Always &#96;error&#96;. A stream error. |
| data.processed_at | null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string | A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / When the event was recorded, RFC 3339. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / When the event was recorded, RFC 3339. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / When the event was recorded, RFC 3339. / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / A timestamp in RFC 3339 format / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. / When the event was recorded, RFC 3339. / RFC 3339 time at which the server processed the event; null while a queued input has not started running. |
| data.message_id | string | UI transcript message ID. Use the last assistant message in a successfully completed turn as the fork target. / UI transcript message ID shared with this assistant's message parts. / UI transcript message ID. Use the last assistant message in a successfully completed turn as the fork target. / UI transcript message ID. Use the last assistant message in a successfully completed turn as the fork target. / UI transcript message ID shared with this assistant's message parts. |
| data.session_thread_id | null &#124; string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string &#124; string | If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Text of the block. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; or &#96;user.tool_result&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / Public &#96;sthr_&#96; ID of the newly created thread. / Public sthr\_ ID of the thread that started running. / Public sthr\_ ID of the thread that went idle. / Public sthr\_ ID of the thread that is retrying. / Public sthr\_ ID of the thread that terminated. / Text of the block. / Text of the block. / If absent, interrupts every non-archived thread in a multiagent session (or the primary alone in a single-agent session). If present, interrupts only the named thread. / Text of the block. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; or &#96;user.tool_result&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / When set, this event was cross-posted from a subagent's thread to surface its permission request on the primary thread's stream. Empty on the thread's own events. Informational only: the server routes the matching &#96;user.tool_confirmation&#96; by &#96;tool_use_id&#96;, so clients do not send it back. / Public &#96;sthr_&#96; ID of the newly created thread. / Public sthr\_ ID of the thread that started running. / Public sthr\_ ID of the thread that went idle. / Public sthr\_ ID of the thread that is retrying. / Public sthr\_ ID of the thread that terminated. / Text of the block. / Text of the block. |
| data.stop_reason | object | Why the session stopped running, with the variant data needed to continue. |
| data.removed | array&lt;object&gt; | Content removed from the model's context by this reset. |
| data.category | string | Text of the block. |
| data.stopped | boolean | True when the run was stopped instead of retried after the reset. |
| data.agent | null &#124; object | Resolved &#96;agent&#96; definition for a &#96;session&#96;. Snapshot of the &#96;agent&#96; at &#96;session&#96; creation time. |
| data.budget | null &#124; object | A hard spend ceiling. The session stops issuing new model requests once the tracked list cost reaches &#96;max_list_cost&#96;. |
| data.metadata | object | The session's full metadata bag after the update. Present when the update set non-empty metadata; absent when metadata was unchanged or cleared to empty. |
| data.title | null &#124; string | The session's new title. Present only when the update changed it. |
| data.model | object | Praxis extension: the changed session model, present only on /agent/v1 session.updated events. Model-only updates are omitted on /anthropic. |
| data.error | object | Description of the error and what the client should do next. / Error detail. / Description of the error and what the client should do next. / Error detail. |
| data.usage | object | Point-in-time snapshot of a session's cumulative usage. |
| data.is_error | null &#124; boolean | Whether the model request resulted in an error. / Whether the tool execution resulted in an error. / Whether the tool execution resulted in an error. / Whether the model request resulted in an error. / Whether the tool execution resulted in an error. / Whether the tool execution resulted in an error. |
| data.model_request_start_id | string | The id of the corresponding &#96;span.model_request_start&#96; event. |
| data.model_usage | object | Token usage for a single model request. |
| data.input | object | Input parameters for the tool call. |
| data.name | string | Name of the agent tool being used. / Name of the MCP tool being used. / Name of the agent tool being used. / Name of the MCP tool being used. |
| data.evaluated_permission | string | AgentEvaluatedPermission enum |
| data.evaluation | object | Names the resolved permission_policy that produced evaluated_permission, and under auto carries the judgement. Open union: clients must tolerate unknown variants. |
| data.tool_use_id | string | The id of the &#96;agent.tool_use&#96; event this result corresponds to. / The id of the AskUserQuestion &#96;agent.tool_use&#96; event this answers. / The id of the &#96;agent.tool_use&#96; event this result corresponds to. / The id of the AskUserQuestion &#96;agent.tool_use&#96; event this answers. |
| data.mcp_server_name | string | Name of the MCP server providing the tool. |
| data._meta | object | Praxis extension (MCP Apps, SEP-1865): the &#96;ui&#96; and &#96;openai/ui&#96; keys of the MCP tool definition's &#96;_meta&#96;, verbatim; other &#96;_meta&#96; keys are not exposed. When &#96;ui.resourceUri&#96; is a &#96;ui://&#96; URI, the tool has an interactive view: a client that implements MCP Apps can fetch that resource from the MCP server and render it for this call. Absent when the tool declares neither key. Clients that do not render MCP Apps ignore it. / Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;_meta&#96;, verbatim. Views use it for data that should not reach the model; absent when the tool returned none. / Praxis extension (MCP Apps, SEP-1865): the &#96;ui&#96; and &#96;openai/ui&#96; keys of the MCP tool definition's &#96;_meta&#96;, verbatim; other &#96;_meta&#96; keys are not exposed. When &#96;ui.resourceUri&#96; is a &#96;ui://&#96; URI, the tool has an interactive view: a client that implements MCP Apps can fetch that resource from the MCP server and render it for this call. Absent when the tool declares neither key. Clients that do not render MCP Apps ignore it. / Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;_meta&#96;, verbatim. Views use it for data that should not reach the model; absent when the tool returned none. |
| data.source | string | Praxis extension (MCP Apps, SEP-1865): &#96;app&#96; when the call was made by an MCP Apps view, &#96;codemode&#96; when a program run by the codemode tool called an MCP tool that declares a view (the event pair exists so a client can render that view; the model already has the result in the codemode tool result); absent for the model's own calls. / What caused the change. / Praxis extension (MCP Apps, SEP-1865): &#96;app&#96; when the call was made by an MCP Apps view, &#96;codemode&#96; when a program run by the codemode tool called an MCP tool that declares a view (the event pair exists so a client can render that view; the model already has the result in the codemode tool result); absent for the model's own calls. / Praxis extension (MCP Apps, SEP-1865): &#96;app&#96; when the call was made by an MCP Apps view, &#96;codemode&#96; when a program run by the codemode tool called an MCP tool that declares a view (the event pair exists so a client can render that view; the model already has the result in the codemode tool result); absent for the model's own calls. / What caused the change. |
| data.parent_tool_use_id | string | Praxis extension (MCP Apps, SEP-1865): present when &#96;source&#96; is &#96;codemode&#96;; the id of the codemode tool use whose program made this call. Absent otherwise. |
| data.mcp_tool_use_id | string | The id of the &#96;agent.mcp_tool_use&#96; event this result corresponds to. |
| data.structured_content | any | Praxis extension (MCP Apps, SEP-1865): the MCP CallToolResult &#96;structuredContent&#96;, verbatim JSON. MCP Apps views read it as the data to render; absent when the tool returned none. |
| data.result | string | Always &#96;allow&#96;. |
| data.answers | object | The user's answer to each question, keyed by the question text; empty when the questions were dismissed. |
| data.annotations | object | Per-question notes, keyed by the question text. |
| data.agent_name | string | Name of the callable agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the callable agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. / Name of the agent the thread runs. |
| data.to_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread the message was sent to. |
| data.to_agent_name | null &#124; string | Name of the callable agent this message was sent to. Absent when sent to the primary agent. |
| data.from_session_thread_id | string | Public &#96;sthr_&#96; ID of the thread that sent the message. |
| data.from_agent_name | null &#124; string | Name of the callable agent this message came from. Absent when received from the primary agent. |
| data.event_id | string | Text of the block. / Id of the event this event refers to. / Text of the block. / Text of the block. / Id of the event this event refers to. / Text of the block. |
| data.sources | array&lt;object&gt; | Background work that woke the session with this notification. |
| data.forked_from_session_id | string | Id of the parent session this session was forked from. |
| data.forked_from_message_id | string | message_id of the agent message in the parent session up to which the conversation was copied. |
| data.action | string | What changed in the goal. |
| data.goal | object &#124; null | The goal as the change left it, or null when the session has no goal. |
| data.previous_goal | object &#124; null | The goal before the change, or null when there was none. |
| data.status | string | Where the check stands. Read &#96;verification.passed&#96; on the closing event to know whether the goal counts as done. |
| data.goal_id | string | The goal this check belongs to. |
| data.goal_iteration | integer | Which check of this goal, matching &#96;iteration&#96; on the goal. |
| data.verification_id | string | Identifier shared by every event of one check. |
| data.anchor_message_id | string &#124; null | The assistant message the check follows, or null. |
| data.verification | object | The verdict; absent on &#96;started&#96;. |
| data.event | object | Event name or event payload. |
| data.delta | object | Incremental fragment of the event being produced. |

# 

先调用「创建会话」，用返回的会话 ID 替换示例 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique identifier for this thread. |
| agent | object | The resolved agent a &#96;session_thread&#96; runs. |
| agent.model | string &#124; object | The advisor model id. / Model identifier and configuration. |
| agent.type | string | Always &#96;advisor&#96;. An advisor whose model is consulted for advice in a separate thread (at most one per coordinator). / Always &#96;agent&#96;. A roster member that refers to an agent by id and pinned version. |
| agent.id | string | Agent id (agent_...). Pass it as agent when creating a session and as agent_id in agent calls. |
| agent.description | null &#124; string | Free-text description of what the agent is for; null when none was set. |
| agent.mcp_servers | array&lt;object&gt; | URL MCP servers the agent can call, paired one-to-one with mcp_toolset entries in tools and saved with the agent version. No credentials are stored here. |
| agent.name | string | Display name of the agent, as set on create or update. It is a label, not a unique key. |
| agent.skills | array&lt;object&gt; | Skill attachments are not supported: a nonempty skills array returns 400. Omit this field or send an empty array. The native Skill tool loads available runtime skills independently of this field. |
| agent.system | null &#124; string | System prompt given to the model at the start of every session of this agent; null when none was set. |
| agent.tools | array&lt;object&gt; | Tools of the agent: one agent_toolset_20260401 entry for the native tools (all resolved settings are returned, ready to send back on update), plus mcp_toolset entries; custom tool definitions are rejected with 400. Keep bash enabled to use codemode, Skill and subagents. |
| agent.version | number | The agent's current version. Starts at 1 and increments each time the agent is modified. |
| archived_at | null &#124; string | A timestamp in RFC 3339 format |
| created_at | string | A timestamp in RFC 3339 format |
| parent_thread_id | null &#124; string | Parent thread that spawned this thread. Null for the primary thread. |
| session_id | string | The session this thread belongs to. |
| stats | null &#124; object | Timing statistics for a session thread. |
| stats.active_seconds | number | Cumulative time in seconds the thread spent actively running. Excludes idle time. |
| stats.duration_seconds | number | Elapsed time since thread creation in seconds. For archived threads, frozen at the final update. |
| stats.startup_seconds | number | Time in seconds for the thread to begin running. Zero for child threads, which start immediately. |
| status | string | SessionThreadStatus enum |
| type | string | Always &#96;session_thread&#96;. An execution thread of a session. |
| updated_at | string | A timestamp in RFC 3339 format |
| usage | null &#124; object | Cumulative token usage for a session thread across all turns. |
| usage.active_seconds | number | Cumulative time in seconds this thread spent in running status. Equal to &#96;stats.active_seconds&#96;; surfaced here so a thread's usage carries every quantity its cost is priced on. |
| usage.cache_creation | object | Prompt-cache creation token usage broken down by cache lifetime. |
| usage.cache_read_input_tokens | number | Total tokens read from prompt cache. |
| usage.input_tokens | number | Total input tokens consumed across all turns. |
| usage.list_cost | null &#124; object | A monetary amount in a specific currency. |
| usage.output_tokens | number | Total output tokens generated across all turns. |
| usage.server_tool_use | null &#124; object | Cumulative count of server-executed tool invocations, broken down by tool. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].id | string | Environment identifier (e.g., 'env\_...') |
| data[].archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| data[].config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| data[].created_at | string | RFC 3339 timestamp when environment was created |
| data[].description | null &#124; string | User-provided description for the environment; null when unset |
| data[].metadata | object | User-provided metadata key-value pairs |
| data[].name | string | Human-readable name for the environment |
| data[].type | string | The type of object (always 'environment') |
| data[].updated_at | string | RFC 3339 timestamp when environment was last updated |
| data[].scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |
| next_page | string &#124; null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Environment identifier (e.g., 'env\_...') |
| archived_at | null &#124; string | RFC 3339 timestamp when environment was archived, or null if not archived |
| config | object | Environment configuration (either Anthropic Cloud or self-hosted) |
| config.networking | object | Network configuration policy. |
| config.packages | object | Package manager configuration. |
| config.type | string | Environment type |
| created_at | string | RFC 3339 timestamp when environment was created |
| description | null &#124; string | User-provided description for the environment; null when unset |
| metadata | object | User-provided metadata key-value pairs |
| name | string | Human-readable name for the environment |
| type | string | The type of object (always 'environment') |
| updated_at | string | RFC 3339 timestamp when environment was last updated |
| scope | string | The visibility scope for this environment. 'organization' means visible to all accounts. 'account' means visible only to the owning account. |

# 列出工具集

## 响应 [#响应]

### HTTP 200 [#http-200]

Available toolsets

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Items of this page, in the order requested by the call. |
| data[].type | string | Toolset type id as used in an agent's tools entry, for example agent_toolset_20260401. |
| data[].plugin | object | Unit that registers the toolset, with its name and version. |
| data[].description | string | Free-text description; null when none was set. |
| data[].environment | string | Environment in which the toolset's tools run, for example node22. |
| data[].tools | array&lt;object&gt; | Tools offered to the model. |
| next_page | null | Opaque cursor for the next page: pass it unchanged as page to continue. Null when this is the last page. |

# 模型 API

（待译）

Model runs inference and lists model capabilities and prices through /model/v1. Each protocol surface follows its native provider (OpenAI / Anthropic / Google), so experience with that protocol applies. Differences: use catalog model ids unchanged, including creator prefixes, and only their declared supported\_apis without protocol conversion; usage.cost, when present, is the customer charge in USD, not upstream cost; thinking levels map to the selected same-protocol model's effort or token budget, and unsupported disabling is rejected; explicitly unsupported fields return their documented error, ignored fields have no effect, and unknown top-level Chat, Responses, Messages and Embeddings fields pass to the same-protocol upstream. Allow room for reasoning within the completion-token cap before expecting tool arguments or structured output. Verify settled cost with praxis.model.generation.retrieve using X-Praxis-Generation-Id or chat providerMetadata.praxis.generationId; absent cost or id does not mean a free call. Start with `praxis.model.models.list` to choose a model by supported\_apis, capabilities and per-unit prices.

## 基础地址 [#基础地址]

## 接入 [#接入]

## 两家 SDK 怎么配 [#两家-sdk-怎么配]

| SDK           | base URL                                                                               | 认证头                                   | 能用的端点                                    |
| ------------- | -------------------------------------------------------------------------------------- | ------------------------------------- | ---------------------------------------- |
| OpenAI SDK    | <ApiOriginInline text="&#x22;https://api-origin.invalid/model/v1&#x22;" />             | `Authorization: Bearer`               | 对话、生成响应、文本向量、生成图像、模型列表、会话（Conversations） |
| Anthropic SDK | <ApiOriginInline text="&#x22;https://api-origin.invalid/model&#x22;" />（SDK 自己补 `/v1`） | `x-api-key` 或 `Authorization: Bearer` | 发送消息、统计 token                            |

两家用同一把 Key、同一套模型名、同一个账单，换 SDK 不换别的。会话（[创建](/docs/api/native/model/createConversation)、条目、删除）是跨调用的状态容器，形状与 OpenAI 官方 conversations 一致。

## 模型回退与自带 Key [#模型回退与自带-key]

[对话](/docs/api/native/model/createChatCompletion)的请求体可以带 `providerOptions.praxis`：

| 字段               | 作用                                   |
| ---------------- | ------------------------------------ |
| `models`         | 候选模型列表：请求的模型失败时按顺序换下一个               |
| `byok`           | 自带上游 Key（按供应商名给出）；这把 Key 不可用时自动改用平台的 |
| `order` / `only` | 指定供应商的顺序或范围，只在带 `byok` 时可用           |

响应里的 `providerMetadata.praxis` 给出这次调用的 `generationId`、`cost`、`credential`（platform 或 byok）和实际服务的 `model`；拿 `generationId` 可以[查询生成记录](/docs/api/native/model/getGeneration)。其它端点目前不接受 `providerOptions.praxis`，带上会返回 400。

## 端点 [#端点]

| 方法     | 路径                                                                                                       | 说明         | 支持     |
| ------ | -------------------------------------------------------------------------------------------------------- | ---------- | ------ |
| POST   | [`/v1/chat/completions`](/docs/api/native/model/createChatCompletion)                                    | 对话         | ● 支持   |
| POST   | [`/v1/responses`](/docs/api/native/model/createResponse)                                                 | 生成响应       | ● 支持   |
| GET    | [`/v1/responses/{response_id}`](/docs/api/native/model/retrieveResponse)                                 | 读取响应       | ● 支持   |
| DELETE | [`/v1/responses/{response_id}`](/docs/api/native/model/deleteResponse)                                   | 删除响应       | ● 支持   |
| POST   | [`/v1/responses/{response_id}/cancel`](/docs/api/native/model/cancelResponse)                            | 取消响应       | ◐ 部分支持 |
| GET    | [`/v1/responses/{response_id}/input_items`](/docs/api/native/model/listResponseInputItems)               | 列出响应输入项    | ● 支持   |
| POST   | [`/v1/responses/compact`](/docs/api/native/model/compactResponse)                                        | 压缩响应       | ○ 未支持  |
| POST   | [`/v1/responses/input_tokens`](/docs/api/native/model/countResponseInputTokens)                          | 统计输入 token | ○ 未支持  |
| POST   | [`/v1/embeddings`](/docs/api/native/model/createEmbedding)                                               | 文本向量       | ● 支持   |
| POST   | [`/v1/rerank`](/docs/api/native/model/rerank)                                                            | 重排文档       | ● 支持   |
| POST   | [`/v1/audio/speech`](/docs/api/native/model/createAudioSpeech)                                           | 合成语音       | ● 支持   |
| POST   | [`/v1/audio/transcriptions`](/docs/api/native/model/createAudioTranscription)                            | 转写音频       | ● 支持   |
| POST   | [`/v1/images/generations`](/docs/api/native/model/createImage)                                           | 生成图像       | ● 支持   |
| POST   | [`/v1/images/edits`](/docs/api/native/model/editImage)                                                   | 编辑图像       | ● 支持   |
| POST   | [`/v1/ocr`](/docs/api/native/model/createOcr)                                                            | 文档识别       | ● 支持   |
| POST   | [`/v1/videos`](/docs/api/native/model/createVideo)                                                       | 创建视频       | ● 支持   |
| GET    | [`/v1/videos`](/docs/api/native/model/listVideos)                                                        | 列出视频       | ● 支持   |
| GET    | [`/v1/videos/{video_id}`](/docs/api/native/model/retrieveVideo)                                          | 读取视频       | ● 支持   |
| GET    | [`/v1/videos/{video_id}/content`](/docs/api/native/model/downloadVideoContent)                           | 下载视频内容     | ● 支持   |
| DELETE | [`/v1/videos/{video_id}`](/docs/api/native/model/deleteVideo)                                            | 删除视频       | ● 支持   |
| POST   | [`/v1/videos/{video_id}/remix`](/docs/api/native/model/remixVideo)                                       | 混剪视频       | ○ 未支持  |
| POST   | [`/v1/messages`](/docs/api/native/model/createMessage)                                                   | 发送消息       | ● 支持   |
| POST   | [`/v1/messages/count_tokens`](/docs/api/native/model/countTokens)                                        | 统计 token   | ◐ 部分支持 |
| GET    | [`/v1/models`](/docs/api/native/model/listModels)                                                        | 列出模型       | ● 支持   |
| GET    | [`/v1/models/{model}`](/docs/api/native/model/retrieveModel)                                             | 读取模型       | ● 支持   |
| GET    | [`/v1/generation`](/docs/api/native/model/getGeneration)                                                 | 查询生成记录     | ● 支持   |
| POST   | [`/v1/conversations`](/docs/api/native/model/createConversation)                                         | 创建会话       | ● 支持   |
| GET    | [`/v1/conversations/{conversation_id}`](/docs/api/native/model/retrieveConversation)                     | 读取会话       | ● 支持   |
| POST   | [`/v1/conversations/{conversation_id}`](/docs/api/native/model/updateConversation)                       | 更新会话       | ● 支持   |
| POST   | [`/v1/conversations/{conversation_id}/items`](/docs/api/native/model/createConversationItems)            | 创建会话条目     | ● 支持   |
| GET    | [`/v1/conversations/{conversation_id}/items`](/docs/api/native/model/listConversationItems)              | 列出会话条目     | ● 支持   |
| GET    | [`/v1/conversations/{conversation_id}/items/{item_id}`](/docs/api/native/model/retrieveConversationItem) | 读取会话条目     | ● 支持   |
| DELETE | [`/v1/conversations/{conversation_id}/items/{item_id}`](/docs/api/native/model/deleteConversationItem)   | 删除会话条目     | ● 支持   |
| DELETE | [`/v1/conversations/{conversation_id}`](/docs/api/native/model/deleteConversation)                       | 删除会话       | ● 支持   |

## 与官方的差异 [#与官方的差异]

* <a href="/docs/api/native/model/createChatCompletion">对话</a>：未知顶层字段原样转发给同协议上游，由上游决定是否接受；已声明字段的类型与取值范围仍会校验，不合法时返回 400 并点名字段。
* <a href="/docs/api/native/model/createResponse">生成响应</a>：未知顶层字段原样转发给同协议上游，由上游决定是否接受；已声明字段的类型与取值范围仍会校验，不合法时返回 400 并点名字段。
* <a href="/docs/api/native/model/retrieveResponse">读取响应</a>：按 ID 读取一条已保存的响应。如果创建时 store 为 false，我们不会保存这次响应，读取会返回 404 response\_not\_found；超过保留期（默认 30 天）后读取也会返回同样的 404。
* <a href="/docs/api/native/model/deleteResponse">删除响应</a>：按 ID 立即删除一条已保存的响应。如果创建时 store 为 false，我们不会保存这次响应，删除会返回 404 response\_not\_found。
* <a href="/docs/api/native/model/cancelResponse">取消响应</a>：仅对以 background:true 创建、且路由到具备后台生成能力的模型的响应可用：取消是 幂等的，重复调用返回同一个终态响应；我方的取消只能停止我方对上游流的继续读取， 不能保证已发往上游的算力停止计算，用量按实际收到的部分结算。对一个非后台 （同步）响应调用 cancel：如果这个响应 id 不存在（未持久化、已过期或 id 有误）， 返回 404 object\_not\_found；如果响应存在但其来源 provider 没有声明支持 cancel 操作（我们目前没有接入任何为同步响应声明该能力的上游），返回 400 native\_responses\_operation\_unsupported。这两种情况都不是尚未实现的 501 gate。
* <a href="/docs/api/native/model/listResponseInputItems">列出响应输入项</a>：列出一条已保存响应的输入项。支持 limit（1–100，默认 20）、order（asc/desc， 默认 desc，与官方一致）与基于条目 id 的 after 游标分页；has\_more/first\_id/ last\_id 均与实际返回页一致，可据此翻页且不重不漏。每个条目都带服务端签发的 id（message 为 msg\_ 前缀，function\_call/function\_call\_output/reasoning 各自 对应前缀），本次上线前已保存、尚无服务端 id 的旧数据在读取时按确定性规则补 id，不做破坏性迁移，同一游标反复读取保持稳定。以 previous\_response\_id 续接 创建的响应，其输入项列出解析后的完整输入：前序响应链已有的输入与输出条目 再加本轮自己提交的输入；若该祖先响应在我方平台未保存（例如创建时 store 为 false）或已过期删除，则只列出本轮自己提交的输入。如果创建时 store 为 false，我们不会保存这次响应，列出会返回 404 response\_not\_found。
* <a href="/docs/api/native/model/compactResponse">压缩响应</a>：把响应的输入压缩成摘要，依赖 OpenAI Responses 官方的服务端存储（store）语义，我们目前还没有实现；调用会返回 501（message 为 “This platform has not implemented … yet.”，响应头 x-should-retry 为 false），不产生副作用，官方 SDK 不会重试。
* <a href="/docs/api/native/model/countResponseInputTokens">统计输入 token</a>：只统计请求输入会消耗的 token 数、不生成内容，依赖 OpenAI Responses 官方的服务端存储（store）语义，我们目前还没有实现；调用会返回 501（message 为 “This platform has not implemented … yet.”，响应头 x-should-retry 为 false），不产生副作用，官方 SDK 不会重试。
* <a href="/docs/api/native/model/createEmbedding">文本向量</a>：未知顶层字段原样转发给同协议上游，由上游决定是否接受；已声明字段的类型与取值范围仍会校验，不合法时返回 400 并点名字段。
* <a href="/docs/api/native/model/rerank">重排文档</a>：标准请求字段；不能表达的参数返回 input\_not\_representable。
* <a href="/docs/api/native/model/createAudioSpeech">合成语音</a>：melotts 输出 WAV，只支持 input（含 text/prompt 别名）、lang 和默认音频选项；aura-2-en 使用原生 speaker 名称。逐字段限制见参数表。
* <a href="/docs/api/native/model/createAudioTranscription">转写音频</a>：标准请求字段；不能表达的参数返回 input\_not\_representable。
* <a href="/docs/api/native/model/createOcr">文档识别</a>：采用 Mistral OCR 请求与响应形状，仅提供 /model/v1/ocr。model 必填；document 接受 document\_url 或 image\_url（HTTPS 或 base64 data URL），也接受 `{type:"file", file_id:"<上传所得 ID>"}`，直接读取当前租户的 File。file\_id 读取上限为 24 MiB（25,165,824 字节，共享 96 MiB 内存预算按四倍预留）；超过此上限返回 413，并提示改用 HTTPS document\_url（PDF 上限 50 MiB）。PNG/JPEG 仍限 10 MiB，按文件头识别类型；不存在或其他租户的文件统一返回 404。pages 是从 0 开始的页码数组；图片如指定 pages，只能为 `[0]`。文件读取失败不计费，请求日志仅记录 file\_id，不保存文件原文。可选功能依模型而定，不支持的选项返回 400。错误为 problem+json；providerOptions.praxis 不适用于此端点。
* <a href="/docs/api/native/model/createVideo">创建视频</a>：按输出秒数计费；每秒价格见 GET /model/v1/models 的 pricing.video\_second（USD/秒）。
* <a href="/docs/api/native/model/listVideos">列出视频</a>：按输出秒数计费；每秒价格见 GET /model/v1/models 的 pricing.video\_second（USD/秒）。
* <a href="/docs/api/native/model/retrieveVideo">读取视频</a>：按输出秒数计费；每秒价格见 GET /model/v1/models 的 pricing.video\_second（USD/秒）。
* <a href="/docs/api/native/model/downloadVideoContent">下载视频内容</a>：按输出秒数计费；每秒价格见 GET /model/v1/models 的 pricing.video\_second（USD/秒）。
* <a href="/docs/api/native/model/deleteVideo">删除视频</a>：按输出秒数计费；每秒价格见 GET /model/v1/models 的 pricing.video\_second（USD/秒）。
* <a href="/docs/api/native/model/remixVideo">混剪视频</a>：未支持，调用返回 400；不要重试。
* <a href="/docs/api/native/model/createMessage">发送消息</a>：未知顶层字段原样转发给同协议上游，由上游决定是否接受；已声明字段的类型与取值范围仍会校验，不合法时返回 400 并点名字段。
* <a href="/docs/api/native/model/countTokens">统计 token</a>：按模型族校准的估算值（包括中文和工具定义），响应头为 x-praxis-token-count: estimated；不能用作精确用量或计费依据。
* <a href="/docs/api/native/model/listModels">列出模型</a>：OCR 模型的 type 为 ocr，pricing.page 是 USD/页的十进制字符串，为 Praxis 对 Vercel 模型列表形状的扩展；其余四项 token 价格为 0。其它模型不带 pricing.page。
* <a href="/docs/api/native/model/createConversation">创建会话</a>：创建一个会话，可选携带初始 items（一次最多 20 条）与 metadata。会话按租户分区，创建者是唯一能引用它的租户。
* <a href="/docs/api/native/model/retrieveConversation">读取会话</a>：按 ID 读取一个会话。不存在或属于其他租户都返回 404 conversation\_not\_found。
* <a href="/docs/api/native/model/updateConversation">更新会话</a>：更新一个会话的 metadata——整体替换，不与已有 metadata 合并。
* <a href="/docs/api/native/model/createConversationItems">创建会话条目</a>：向一个会话追加 items（一次最多 20 条），返回刚追加的这些 items。
* <a href="/docs/api/native/model/listConversationItems">列出会话条目</a>：按创建顺序列出会话的 items，支持 limit/after/order 分页参数。
* <a href="/docs/api/native/model/retrieveConversationItem">读取会话条目</a>：按 ID 读取会话里的单条 item。
* <a href="/docs/api/native/model/deleteConversationItem">删除会话条目</a>：删除会话里的单条 item，返回该会话对象（不是被删除的 item）。
* <a href="/docs/api/native/model/deleteConversation">删除会话</a>：删除一个会话。删除后该会话与其 items 都不能再被引用（包括作为 Responses create 的 conversation 参数）。

请求与响应字段的权威定义，见每个端点页链接的 OpenAI、Anthropic 或 Mistral 官方文档。OCR 通过 HTTP 调用，不在 OpenAI 或 Anthropic SDK 的端点中。

鉴权、限流、参数校验等平台错误按 problem+json 返回；OCR 的错误也为 problem+json，其它模型调用的错误按该端点所属格式（OpenAI 或 Anthropic）返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 对话

## 响应 [#响应]

### HTTP 200 [#http-200]

Chat completion (application/json) or streamed chunks (text/event-stream)

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the completion. |
| object | string | Object type; always &#96;chat.completion&#96;. |
| created | number | Unix time in seconds at which the completion was created. |
| model | string | Model that produced the completion; with fallback this is the model that finally answered. |
| choices | array&lt;object&gt; | Completion choices; one entry per generated answer. |
| choices[].index | number | Zero-based index of the choice. |
| choices[].message | object | The message the model generated. |
| choices[].finish_reason | string &#124; null | Why generation stopped, for example &#96;stop&#96;, &#96;length&#96; or &#96;tool_calls&#96;; null while a stream is still generating. |
| choices[].logprobs | any &#124; null | Log probabilities of the output tokens, when requested; null otherwise. |
| usage | object | Token usage of the request. |
| usage.prompt_tokens | number | Number of tokens in the prompt. |
| usage.completion_tokens | number | Number of tokens in the completion. |
| usage.total_tokens | number | Prompt plus completion tokens. |
| usage.prompt_tokens_details | object | Breakdown of the prompt tokens. |
| usage.completion_tokens_details | object | Breakdown of the completion tokens. |
| usage.prompt_cache_hit_tokens | number | Prompt tokens served from the cache, as reported by providers that use this DeepSeek-style counter. |
| usage.prompt_cache_miss_tokens | number | Prompt tokens not served from the cache, as reported by providers that use this DeepSeek-style counter. |
| system_fingerprint | string &#124; null | Backend fingerprint; always null on this face. |
| service_tier | string &#124; null | Service tier the provider used; null when not reported. |
| providerMetadata | object | Platform metadata of the call. |
| providerMetadata.praxis | object | Platform metadata of the call: generation id, cost, credential kind and serving model. |

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Optional id of the server-sent event. |
| event | string | Name of the server-sent event. |
| data | object &#124; string | Payload of the server-sent event. |
| data.id | string | Id of the completion; every chunk of one stream carries the same id. |
| data.object | string | Object type; always &#96;chat.completion.chunk&#96;. |
| data.created | number | Unix time in seconds at which the completion was created. |
| data.model | string | Model that produced the completion; with fallback this is the model that finally answered. |
| data.choices | array&lt;object&gt; | Completion choices of the chunk. |
| data.providerMetadata | object | Platform metadata of the call. |

# 生成响应

## 响应 [#响应]

### HTTP 200 [#http-200]

Successful response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| background | boolean &#124; null | Whether the response was started in background mode. |
| completed_at | integer &#124; null | Unix time in seconds at which the response finished; null while it has not finished. |
| created_at | integer | Unix time in seconds at which the response was created. |
| error | object &#124; null | Error information returned from the API |
| error.code | string | Machine-readable error code. |
| error.message | string | Human-readable error message. |
| frequency_penalty | number &#124; null | The frequency penalty that applied to the request, if any. |
| id | string | Unique id of the response; use it as response_id to retrieve, cancel or delete it, or as previous_response_id to continue the conversation. |
| incomplete_details | object &#124; null | Why the response stopped before finishing; null for complete responses. |
| incomplete_details.reason | string | Why the response is incomplete. |
| instructions | string &#124; array&lt;object&gt; &#124; null | Input of the request: a string or an array of input items. |
| max_output_tokens | integer &#124; null | Upper bound on generated tokens that applied to the request; null when none was set. |
| max_tool_calls | integer &#124; null | Upper bound on built-in tool calls that applied to the request; null when none was set. |
| metadata | object &#124; null | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. |
| model | string | Model that produced the response. |
| object | string | Object type; always &#96;response&#96;. |
| output | array&lt;object&gt; | Items the model produced, in order: messages, reasoning, tool calls and tool results. |
| output[].content | array&lt;object&gt; &#124; array &#124; null &#124; string | Content parts of the message: output text or refusal. / Reasoning text parts, when the provider returns them. / Text content of the fetched page. |
| output[].id | string | Id of the message item. / Id of the reasoning item. / Id of the function call item. / Id of the web search call item. / Id of the file search call item. / Id of the image generation call item. / Id of the code interpreter call item. / Id of the computer call item. / Id of the datetime server tool item. / Id of the web search server tool item. / Id of the code interpreter server tool item. / Id of the file search server tool item. / Id of the image generation server tool item. / Id of the browser use server tool item. / Id of the bash server tool item. / Id of the text editor server tool item. / Id of the apply_patch server tool item. / Id of the apply_patch call item. / Id of the shell call item. / Id of the shell call output item. / Id of the shell server tool item. / Id of the web fetch server tool item. / Id of the tool search server tool item. / Id of the memory server tool item. / Id of the MCP server tool item. / Id of the model search server tool item. / Id of the fusion server tool item. / Id of the advisor server tool item. / Id of the subagent server tool item. / Id of the files server tool item. / Id of the custom tool call item. |
| output[].phase | string &#124; null | The phase of an assistant message. Use &#96;commentary&#96; for an intermediate assistant message and &#96;final_answer&#96; for the final assistant message. For follow-up requests with models like &#96;gpt-5.3-codex&#96; and later, preserve and resend phase on all assistant messages. Omitting it can degrade performance. Not used for user messages. |
| output[].role | string | Role of the author; always assistant. |
| output[].status | string | Status of the message item. / Status of the reasoning item. / Status of the function call item. / Status of a web search call. / Status of a web search call. / Status of an image generation call. / Status of the code interpreter call. / Status of the computer call item. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call that can fail. / Status of a tool call. / Status of a tool call. / Lifecycle state of an &#96;apply_patch_call&#96; output item. / Status of a shell call or its output. / Status of a shell call or its output. / Status of a tool call that can fail. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call. / Status of a tool call that can fail. / Status of a tool call that can fail. / Status of a tool call. / Status of the custom tool call item. |
| output[].type | string | Always &#96;message&#96;. Discriminator that marks this object as a OutputMessage in a &#96;type&#96;-tagged union. / Always &#96;reasoning&#96;. Discriminator that marks this object as a OutputItemReasoning in a &#96;type&#96;-tagged union. / Always &#96;function_call&#96;. Discriminator that marks this object as a OutputItemFunctionCall in a &#96;type&#96;-tagged union. / Always &#96;web_search_call&#96;. Discriminator that marks this object as a OutputItemWebSearchCall in a &#96;type&#96;-tagged union. / Always &#96;file_search_call&#96;. Discriminator that marks this object as a OutputItemFileSearchCall in a &#96;type&#96;-tagged union. / Always &#96;image_generation_call&#96;. Discriminator that marks this object as a OutputItemImageGenerationCall in a &#96;type&#96;-tagged union. / Always &#96;code_interpreter_call&#96;. Discriminator that marks this object as a OutputItemCodeInterpreterCall in a &#96;type&#96;-tagged union. / Always &#96;computer_call&#96;. Discriminator that marks this object as a OutputComputerCallItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:datetime&#96;. Discriminator that marks this object as a OutputDatetimeItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:web_search&#96;. Discriminator that marks this object as a OutputWebSearchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:code_interpreter&#96;. Discriminator that marks this object as a OutputCodeInterpreterServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:file_search&#96;. Discriminator that marks this object as a OutputFileSearchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:image_generation&#96;. Discriminator that marks this object as a OutputImageGenerationServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:browser_use&#96;. Discriminator that marks this object as a OutputBrowserUseServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:bash&#96;. Discriminator that marks this object as a OutputBashServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:text_editor&#96;. Discriminator that marks this object as a OutputTextEditorServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:apply_patch&#96;. Discriminator that marks this object as a OutputApplyPatchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;apply_patch_call&#96;. Discriminator that marks this object as a OutputApplyPatchCallItem in a &#96;type&#96;-tagged union. / Always &#96;shell_call&#96;. Discriminator that marks this object as a OutputShellCallItem in a &#96;type&#96;-tagged union. / Always &#96;shell_call_output&#96;. Discriminator that marks this object as a OutputShellCallOutputItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:shell&#96;. Discriminator that marks this object as a OutputShellServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:web_fetch&#96;. Discriminator that marks this object as a OutputWebFetchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:tool_search&#96;. Discriminator that marks this object as a OutputToolSearchServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:memory&#96;. Discriminator that marks this object as a OutputMemoryServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:mcp&#96;. Discriminator that marks this object as a OutputMcpServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:experimental__search_models&#96;. Discriminator that marks this object as a OutputSearchModelsServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:fusion&#96;. Discriminator that marks this object as a OutputFusionServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:advisor&#96;. Discriminator that marks this object as a OutputAdvisorServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:subagent&#96;. Discriminator that marks this object as a OutputSubagentServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;openrouter:files&#96;. Discriminator that marks this object as a OutputFilesServerToolItem in a &#96;type&#96;-tagged union. / Always &#96;custom_tool_call&#96;. Discriminator that marks this object as a OutputCustomToolCallItem in a &#96;type&#96;-tagged union. |
| output[].encrypted_content | string &#124; null | Opaque encrypted reasoning; send it back unchanged to let the model continue its reasoning on the next turn. |
| output[].summary | array&lt;object&gt; | Summary parts of the reasoning. |
| output[].format | string &#124; null | Wire format of the reasoning details, which names the provider family that produced them. |
| output[].signature | string &#124; null | A signature for the reasoning content, used for verification |
| output[].arguments | string &#124; string &#124; null &#124; string &#124; null &#124; string &#124; null &#124; string &#124; string &#124; null | JSON-encoded arguments the model produced for the function. / The raw tool-call arguments string as emitted by the model. / The raw tool-call arguments string as emitted by the model. Echo back unchanged when replaying history; used verbatim to preserve provider prompt-cache prefixes. / The raw tool-call arguments string as emitted by the model. / The JSON arguments submitted to the search tool (e.g. &#123;"query":"Claude"&#125;) / The raw tool-call arguments string as emitted by the model. |
| output[].async | boolean | True when the model called a tool declared with &#96;async: true&#96; and may continue its turn before the output is returned. Return the result in a later request as a &#96;function_call_output&#96; with this &#96;call_id&#96;. |
| output[].call_id | string &#124; string &#124; null &#124; string &#124; string &#124; string &#124; string &#124; string &#124; null &#124; string &#124; string &#124; null &#124; string | Id of the call; the function_call_output item that answers it repeats it as call_id. / Id of the call; the computer_call_output item that answers it repeats it as call_id. / The model-generated tool call id from the originating turn. / Id of the apply_patch tool call. / Id of the call; the apply_patch_call_output item that answers it repeats it as call_id. / Id of the call; the shell_call_output item that answers it repeats it as call_id. / Id of the shell call this output answers. / The model-generated tool call id from the originating turn. / EXPERIMENTAL — subject to change without notice. The &#96;call_id&#96; of the tool call that spawned this subagent. This id will also be included as the &#96;subagent_id&#96; on any &#96;function_call&#96; items created by the subagent. This must be returned in the request so the &#96;function_call&#96; can be matched with the correct subagent. A suspended &#96;in_progress&#96; item is announced once and never re-emitted or terminally closed — completion arrives as a new item with the same &#96;call_id&#96;. / The model-generated tool call id from the originating turn. / Id of the call; the custom_tool_call_output item that answers it repeats it as call_id. |
| output[].name | string | Name of the function being called. / Configured name of the subagent that executed the task (the &#96;name&#96; on its tool entry). Present only for named subagents; omitted for an unnamed (default) subagent. / Name of the custom tool being called. |
| output[].namespace | string | Namespace qualifier for tools registered as part of a namespace tool group (e.g. an MCP server) |
| output[].subagent_id | string | EXPERIMENTAL — subject to change without notice. String id that matches the &#96;call_id&#96; of the &#96;openrouter:subagent&#96; server tool call that spawned the subagent. Present on every &#96;function_call&#96; item the subagent projects; absent on ordinary function calls. |
| output[].subagent_items | array&lt;object&gt; | EXPERIMENTAL — subject to change without notice. The subagent's output items produced on this turn. Treat this as an opaque object; you must replay it in the request so that the subagent can continue execution of the tool with the same context. If a subagent created multiple parallel tool calls, only the first tool call will have this field. The other tool calls will only have &#96;subagent_id&#96;. Present only if the tool call originates from a subagent spawned by the &#96;openrouter:subagent&#96; server tool. |
| output[].action | object &#124; any &#124; object &#124; string &#124; object &#124; object &#124; string | The search action the model took: a search, opening a page, or finding a pattern in a page. / The action the model asks the client to perform on the computer. / The search action performed, matching OpenAI web_search_call.action shape. Includes the query the model issued and optional source URLs returned by the search provider. / The browser action that was performed. / The commands the model asks the client to run. / The commands that were run. / Memory action that was performed. |
| output[].queries | array&lt;string&gt; | Queries the model ran against the vector stores. / Queries that ran against the vector stores. |
| output[].result | string &#124; null &#124; string | Base64-encoded generated image; null while generation has not finished. / The generated image as a base64-encoded string or URL, matching OpenAI image_generation_call format / JSON-serialized result of the file operation. |
| output[].prompt | string | The prompt (possibly rewritten) that the image was generated from. / The prompt the executor sent to the advisor. |
| output[].code | string &#124; null &#124; string | The code the interpreter ran; null while it is still being written. / The code that ran. |
| output[].container_id | string | Id of the container the code ran in. / The canonical container id the command ran under — the &#96;&#123;container_id&#125;&#96; for the Container Files API, reusable as a &#96;container_reference&#96; in later requests. Present on every sandbox-executed call, even when no files changed. / The canonical container id the command ran under — the &#96;&#123;container_id&#125;&#96; for the Container Files API, reusable as a &#96;container_reference&#96; in later requests. Present on every sandbox-executed call, even when no files changed. / The canonical container id the command ran under — the &#96;&#123;container_id&#125;&#96; for the Container Files API, reusable as a &#96;container_reference&#96; in later requests. Present on every sandbox-executed call, even when no files changed. |
| output[].outputs | array &#124; null | Outputs of the run: logs and images; null while the run has not finished. |
| output[].pending_safety_checks | array&lt;object&gt; | Safety checks that must be acknowledged before the action is performed. |
| output[].datetime | string | ISO 8601 datetime string |
| output[].timezone | string | IANA timezone name |
| output[].exitCode | integer | Exit code of the run; 0 means success. / Exit code of the command; 0 means success. |
| output[].language | string | Language of the code that ran. |
| output[].stderr | string | Standard error output of the code. / Standard error output of the command. |
| output[].stdout | string | Standard output of the code. / Standard output of the command. |
| output[].imageB64 | string | Base64-encoded generated image. |
| output[].imageUrl | string | URL of the generated image. |
| output[].revisedPrompt | string | Prompt after the image model rewrote it. |
| output[].screenshotB64 | string | Base64-encoded screenshot taken after the action. |
| output[].command | string | The bash command that ran. / Editor command that ran. |
| output[].error | string | The error message when the sandbox call failed before producing a result (for example, the per-user container limit was reached). Set together with &#96;status: 'failed'&#96;; absent on a successful call. A non-zero &#96;exitCode&#96; is a command failure, not a tool failure. / The error message when the sandbox call failed before producing a result (for example, the per-user container limit was reached). Set together with &#96;status: 'incomplete'&#96; and an empty &#96;output&#96;; absent on a successful call. / The error message when the sandbox call failed before producing a result (for example, the per-user container limit was reached). Set together with &#96;status: 'failed'&#96;; absent on a successful call. &#96;output&#96; is omitted when &#96;error&#96; is set. / The error message if the fetch failed. / Error message when the fusion run did not produce an analysis result. / Error message when the advisor call did not produce advice. Set together with &#96;status: 'failed'&#96; on the terminal item. / Error message when the subagent task did not produce an outcome. Set together with &#96;status: 'failed'&#96; on the terminal item. / Error message when the file operation failed. |
| output[].files | array&lt;object&gt; | Citations for the files the sandbox command created or modified, most-recently-touched first (at most 10). Retrieve them via the Container Files API. |
| output[].filePath | string | Path of the file the command worked on. |
| output[].operation | object &#124; string | The patch operation requested by an &#96;apply_patch_call&#96;. &#96;create_file&#96; and &#96;update_file&#96; carry a V4A diff; &#96;delete_file&#96; omits it. / The file operation performed (list, read, write, or edit). |
| output[].max_output_length | integer &#124; null | Maximum number of characters of output that was kept; null for no limit. |
| output[].output | array&lt;object&gt; | Output of each command, in the order the commands ran. |
| output[].httpStatus | integer | The HTTP status code returned by the upstream URL fetch. |
| output[].title | string | Title of the fetched page. |
| output[].url | string | URL that was fetched. |
| output[].query | string | The tool search query. / The model search query. |
| output[].key | string | Key of the memory entry. |
| output[].value | any | Value of the memory entry; absent for reads that found nothing and for deletes. |
| output[].serverLabel | string | Label of the MCP server. |
| output[].toolName | string | Name of the MCP tool that was called. |
| output[].analysis | object | Structured analysis produced by the fusion analyst model. |
| output[].failed_models | array&lt;object&gt; | Models that were requested as part of the analysis panel but did not produce a response. Present when at least one requested analysis model failed. The fusion result is still usable but was produced from a degraded panel. |
| output[].failure_reason | string | Typed failure reason when the fusion run failed. Possible values include: all_panels_failed, insufficient_credits, rate_limited, invalid_model, judge_not_valid_json, judge_schema_mismatch, judge_upstream_error, judge_empty_completion. The four analysis-stage codes keep their pre-rename &#96;judge_&#96; spelling so existing consumers keep matching. The consumer-cancellation code is &#96;cancelled&#96;. |
| output[].responses | array&lt;object&gt; | Analysis models that produced a response in this fusion run, with each model's full panel content. |
| output[].sources | array&lt;object&gt; | Web pages the analysis panels and analyst retrieved via web search during this fusion run, deduplicated by URL across the whole run. Present when at least one model cited a source. |
| output[].advice | string | The advisor model's response (the advice text returned to the executor). |
| output[].instance_name | string | Provider-safe function name of the specific advisor instance that produced this item (e.g. &#96;openrouter_advisor__1&#96;). Present only when more than one advisor tool is configured; omitted for the default single advisor. Echo this field back unchanged so the advisor's cross-request memory stays namespaced to the correct instance. This identity is positional: it is derived from the index of the advisor entry in the request &#96;tools&#96; array, so clients must keep the order of advisor tool entries stable across requests in a conversation. Reordering or inserting advisor entries shifts these names and causes each advisor's cross-request memory to be attributed to the wrong instance. / Provider-safe function name of the specific subagent instance that produced this item (e.g. &#96;openrouter_subagent__1&#96;). Present only on items from non-default instances — the second and later subagent entries in the request &#96;tools&#96; array. The first (default) instance omits it, even when multiple subagents are configured. When a replayed item echoes this field back, the transcript rehydrates the call under that instance's tool. This identity is positional: it is derived from the index of the subagent entry in the request &#96;tools&#96; array, so keep the order of subagent entries stable across requests in a conversation. |
| output[].model | string | Slug of the advisor model that was consulted. / Slug of the worker model that executed the task. |
| output[].outcome | string | The worker model's result (the outcome text returned to the delegating model). |
| output[].task_description | string | The task description the delegating model sent to the worker. |
| output[].task_name | string | The short task identifier the delegating model supplied. |
| output[].file_id | string | The target file id supplied in the tool-call arguments. |
| output[].filename | string | The target filename supplied in the tool-call arguments. |
| output[].input | string | Free-form input the model produced for the custom tool. |
| output_text | string | Convenience concatenation of all output text of the response. |
| parallel_tool_calls | boolean | Whether the model was allowed to call several tools in one turn. |
| presence_penalty | number &#124; null | The presence penalty that applied to the request, if any. |
| previous_response_id | string &#124; null | Id of the response this one continued; null when it started a new conversation. |
| prompt | object &#124; null | Reference to a stored prompt template with its variables. |
| prompt.id | string | Id of the stored prompt template. |
| prompt.variables | object &#124; null | Values for the template variables, keyed by variable name; a value is a string or an input text, image or file part. |
| prompt_cache_key | string &#124; null | Cache key the request supplied to improve prompt cache hits; null when none was set. |
| prompt_cache_options | object &#124; null | Request-level prompt-cache controls. &#96;mode: "explicit"&#96; disables OpenAI-managed breakpoints so only blocks marked with &#96;prompt_cache_breakpoint&#96; are cached. Only supported by OpenAI GPT-5.6 and newer. |
| prompt_cache_options.mode | string | Prompt cache mode; explicit caches only the blocks marked with prompt_cache_breakpoint. |
| prompt_cache_options.ttl | string &#124; null | Lifetime of cache entries, for example 30m; null leaves the provider default. |
| reasoning | object &#124; null | Reasoning settings that applied: effort, summary verbosity, mode and context. |
| reasoning.context | string &#124; null | Controls which reasoning is available to the model. &#96;auto&#96; uses the model default (same as omitting); &#96;all_turns&#96; includes reasoning from earlier turns passed in input; &#96;current_turn&#96; limits to the current turn only. Only supported by OpenAI GPT-5.6 and newer. |
| reasoning.effort | string &#124; null | How much reasoning the model should spend. |
| reasoning.mode | string &#124; null | Selects the reasoning mode. &#96;standard&#96; is the default; &#96;pro&#96; engages deeper reasoning on models that support it, billed at standard token rates. Only supported by OpenAI GPT-5.6 and newer. |
| reasoning.summary | string &#124; null | How detailed the reasoning summary should be. |
| safety_identifier | string &#124; null | End-user identifier the request supplied for abuse monitoring; null when none was set. |
| service_tier | string &#124; null | Service tier the provider used for the response; null when not reported. |
| status | string | Lifecycle status of the response. |
| store | boolean | Whether the response is stored so it can be retrieved later. |
| temperature | number &#124; null | Sampling temperature that applied to the request, if any. |
| text | object | Text output configuration including format and verbosity |
| text.format | object | Text response format configuration |
| text.verbosity | string &#124; null | How long the answer should be. |
| tool_choice | string &#124; object | How the model picks tools: a mode string or a specific tool. |
| tool_choice.name | string | Name of the function or tool the model must call. |
| tool_choice.type | string | Kind of tool the model must call. / Always &#96;allowed_tools&#96;. Discriminator that marks this object as a ToolChoiceAllowed in a &#96;type&#96;-tagged union. / Kind of tool the model must call. / Kind of tool the model must call. |
| tool_choice.mode | string | auto lets the model pick among the allowed tools or none; required forces a call to one of them. |
| tool_choice.tools | array&lt;object&gt; | The allowed tools, each as a tool reference such as &#123;type: function, name&#125;. |
| tools | array&lt;object&gt; | Tools that were available to the model for this response. |
| tools[].description | string &#124; null &#124; string &#124; string | What the function does and when to use it; the model reads this to decide whether to call it. / What the custom tool does and when to use it. / What the group of tools is for. |
| tools[].name | string | Name of the function; the model uses it in function_call items. / Name of the custom tool. / Name of the namespace that groups the tools. |
| tools[].parameters | object &#124; null | JSON Schema of the function arguments; null when the function takes none. |
| tools[].strict | boolean &#124; null | Whether to enforce strict argument validation against the schema; null leaves the provider default. |
| tools[].type | string | Always &#96;function&#96;. Discriminator that marks this object as a FunctionTool in a &#96;type&#96;-tagged union. / Always &#96;web_search_preview&#96;. Discriminator that marks this object as a Preview_WebSearchServerTool in a &#96;type&#96;-tagged union. / Always &#96;web_search_preview_2025_03_11&#96;. Discriminator that marks this object as a Preview_20250311_WebSearchServerTool in a &#96;type&#96;-tagged union. / Always &#96;web_search&#96;. Discriminator that marks this object as a Legacy_WebSearchServerTool in a &#96;type&#96;-tagged union. / Always &#96;web_search_2025_08_26&#96;. Discriminator that marks this object as a WebSearchServerTool in a &#96;type&#96;-tagged union. / Comparison operator. / Always &#96;computer_use_preview&#96;. Discriminator that marks this object as a ComputerUseServerTool in a &#96;type&#96;-tagged union. / Always &#96;code_interpreter&#96;. Discriminator that marks this object as a CodeInterpreterServerTool in a &#96;type&#96;-tagged union. / Always &#96;mcp&#96;. Discriminator that marks this object as a McpServerTool in a &#96;type&#96;-tagged union. / Always &#96;image_generation&#96;. Discriminator that marks this object as a ImageGenerationServerTool in a &#96;type&#96;-tagged union. / Always &#96;local_shell&#96;. Discriminator that marks this object as a CodexLocalShellTool in a &#96;type&#96;-tagged union. / Always &#96;shell&#96;. Discriminator that marks this object as a ShellServerTool in a &#96;type&#96;-tagged union. / Always &#96;apply_patch&#96;. Discriminator that marks this object as a ApplyPatchServerTool in a &#96;type&#96;-tagged union. / Always &#96;custom&#96;. Discriminator that marks this object as a CustomTool in a &#96;type&#96;-tagged union. / Always &#96;namespace&#96;. Discriminator that marks this object as a NamespaceTool in a &#96;type&#96;-tagged union. |
| tools[].async | boolean | Lets the model keep working after calling this tool instead of waiting for its output. The tool is still executed by the client; return the result in a later request as a &#96;function_call_output&#96; with the original &#96;call_id&#96;. Only honored by providers whose Responses API supports async tools; ignored elsewhere. |
| tools[].defer_loading | boolean | Withhold this tool from the model until &#96;openrouter:tool_search&#96; finds it. Requires the tool search server tool; at least one tool must remain non-deferred. |
| tools[].engine | string | Which search engine to use. "auto" (default) uses native if the provider supports it, otherwise Exa. "native" forces the provider's built-in search. "exa" forces the Exa search API. "firecrawl" uses Firecrawl (requires BYOK). "parallel" uses the Parallel search API. "perplexity" uses the Perplexity Search API (raw ranked results). |
| tools[].filters | object &#124; null | Restricts web search by domain. / Attribute filter applied to the search: a comparison or a compound filter. |
| tools[].max_results | integer | Maximum number of search results to return per search call. Defaults to 5. Applies to Exa, Firecrawl, Parallel, and Perplexity engines; ignored with native provider search. Perplexity supports a maximum of 20; values above 20 are clamped. |
| tools[].max_uses | integer | Maximum number of web searches the model may perform in a single request. Once reached, further search calls return an error result instead of executing. Applies to the Exa, Firecrawl, Parallel, and Perplexity engines. With native provider search, forwarded only to Anthropic (as &#96;max_uses&#96;); other native search providers have no equivalent parameter and ignore it. |
| tools[].mode | string | Engine-native search mode. Exa supports instant, fast, auto (default), deep-lite, deep, and deep-reasoning. Parallel supports turbo, fast, basic (default), and advanced. Modes unsupported by the selected engine are ignored. |
| tools[].search_context_size | string | Size of the search context for web search tools |
| tools[].user_location | object &#124; null | Approximate location of the user, used to bias web search results. / User location information for web search / User location information for web search |
| tools[].max_num_results | integer | Maximum number of results to return, between 1 and 50. |
| tools[].ranking_options | object | Ranking options for the search. |
| tools[].vector_store_ids | array&lt;string&gt; | Ids of the vector stores to search. |
| tools[].display_height | integer | Height of the computer display in pixels. |
| tools[].display_width | integer | Width of the computer display in pixels. |
| tools[].environment | string | Kind of environment that is controlled. |
| tools[].container | string &#124; object | Container for the code to run in: a container id or an automatic container with files. |
| tools[].allowed_tools | array&lt;string&gt; &#124; object &#124; null | Tools of the server the model may use: a list of names or a filter. |
| tools[].authorization | string | OAuth access token for the MCP server. |
| tools[].connector_id | string | Id of a built-in connector; give this or server_url. |
| tools[].headers | object &#124; null | HTTP headers sent to the MCP server; null for none. |
| tools[].require_approval | object &#124; string &#124; null | Whether tool calls need approval before they run: always, never, or a filter per tool. |
| tools[].server_description | string | What the MCP server is for, which helps the model decide when to use it. |
| tools[].server_label | string | Label that names the MCP server in the conversation. |
| tools[].server_url | string | URL of the MCP server; give this or connector_id. |
| tools[].background | string | Background of the generated image. |
| tools[].input_fidelity | string &#124; null | How closely to preserve details of input images; null uses the default. |
| tools[].input_image_mask | object | Mask that marks the region of the input image to edit. |
| tools[].model | string | Image model to use. |
| tools[].moderation | string | Moderation level applied to the generated image. |
| tools[].output_compression | integer | Compression level from 0 to 100 for jpeg and webp output. |
| tools[].output_format | string | File format of the generated image. |
| tools[].partial_images | integer | Number of partial images to stream while generating, from 0 to 3. |
| tools[].quality | string | Quality of the generated image. |
| tools[].size | string | Size of the generated image; auto lets the model choose. |
| tools[].format | object | Format of the tool input: free text or a grammar. |
| tools[].tools | array&lt;object&gt; | Function tools in the namespace. |
| top_logprobs | integer | Number of most likely tokens whose log probabilities were requested per position. |
| top_p | number &#124; null | Nucleus sampling value that applied to the request, if any. |
| truncation | string &#124; null | How to handle input that exceeds the context window. |
| usage | object &#124; null | Token usage information for the response |
| usage.input_tokens | integer | Number of input tokens, cached tokens included. |
| usage.input_tokens_details | object | Breakdown of the input tokens. |
| usage.output_tokens | integer | Number of output tokens, reasoning tokens included. |
| usage.output_tokens_details | object | Breakdown of the output tokens. |
| usage.total_tokens | integer | Input plus output tokens. |
| usage.cost | number &#124; null | Cost of the completion |
| usage.cost_details | object | Breakdown of the upstream inference cost. |
| usage.is_byok | boolean | Whether a request was made using a Bring Your Own Key configuration |
| usage.server_tool_use_details | object &#124; null | Usage for server-side tool execution (e.g., web search) |
| user | string &#124; null | End-user identifier the request supplied; null when none was set. |
| error_type | string | Canonical OpenRouter error type, stable across all API formats |
| openrouter_metadata | object | Routing report: what was requested, how the router chose, and what was attempted. |
| openrouter_metadata.attempt | integer | Number of the attempt that served the request, starting at 1. |
| openrouter_metadata.attempts | array&lt;object&gt; | Every attempt that was made, in order. |
| openrouter_metadata.endpoints | object | Which endpoints were available and which one was chosen. |
| openrouter_metadata.generation_time | integer | Milliseconds measured for the generation, from dispatching the upstream request until its response body ended. Divide the completion token count by this for throughput. Absent when no upstream request was dispatched. |
| openrouter_metadata.is_byok | boolean | Whether the request used a key supplied by the caller. |
| openrouter_metadata.params | object | Router parameters that applied to the request. |
| openrouter_metadata.pipeline | array&lt;object&gt; | Stages the request went through before and after the model call. |
| openrouter_metadata.region | string &#124; null | Region that served the request; null when unknown. |
| openrouter_metadata.requested | string | The model or alias the request asked for. |
| openrouter_metadata.strategy | string | How the router picked the model or provider for this request. |
| openrouter_metadata.summary | string | One-line summary of the routing decision. |

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Optional id of the server-sent event. |
| event | string | Name of the server-sent event. |
| data | object &#124; string | Payload of the server-sent event. |
| data.response | object | Complete non-streaming response from the Responses API |
| data.sequence_number | integer | Position of this event in the stream. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream; it increases with every event, so use it to order events or detect a gap. / Position of this event in the stream. |
| data.type | string | Always &#96;response.created&#96;. Discriminator that marks this object as a CreatedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.in_progress&#96;. Discriminator that marks this object as a InProgressEvent in a &#96;type&#96;-tagged union. / Always &#96;response.completed&#96;. Discriminator that marks this object as a CompletedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.incomplete&#96;. Discriminator that marks this object as a IncompleteEvent in a &#96;type&#96;-tagged union. / Always &#96;response.failed&#96;. Discriminator that marks this object as a FailedEvent in a &#96;type&#96;-tagged union. / Always &#96;error&#96;. Discriminator that marks this object as a BaseErrorEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_item.added&#96;. Discriminator that marks this object as a OutputItemAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_item.done&#96;. Discriminator that marks this object as a OutputItemDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.content_part.added&#96;. Discriminator that marks this object as a BaseContentPartAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.content_part.done&#96;. Discriminator that marks this object as a BaseContentPartDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_text.delta&#96;. Discriminator that marks this object as a BaseTextDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_text.done&#96;. Discriminator that marks this object as a BaseTextDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.refusal.delta&#96;. Discriminator that marks this object as a BaseRefusalDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.refusal.done&#96;. Discriminator that marks this object as a BaseRefusalDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.output_text.annotation.added&#96;. Discriminator that marks this object as a BaseAnnotationAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.function_call_arguments.delta&#96;. Discriminator that marks this object as a BaseFunctionCallArgsDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.function_call_arguments.done&#96;. Discriminator that marks this object as a BaseFunctionCallArgsDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_text.delta&#96;. Discriminator that marks this object as a BaseReasoningDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_text.done&#96;. Discriminator that marks this object as a BaseReasoningDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_summary_part.added&#96;. Discriminator that marks this object as a BaseReasoningSummaryPartAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_summary_part.done&#96;. Discriminator that marks this object as a BaseReasoningSummaryPartDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_summary_text.delta&#96;. Discriminator that marks this object as a BaseReasoningSummaryTextDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.reasoning_summary_text.done&#96;. Discriminator that marks this object as a BaseReasoningSummaryTextDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.image_generation_call.in_progress&#96;. Discriminator that marks this object as a OpenAIResponsesImageGenCallInProgress in a &#96;type&#96;-tagged union. / Always &#96;response.image_generation_call.generating&#96;. Discriminator that marks this object as a OpenAIResponsesImageGenCallGenerating in a &#96;type&#96;-tagged union. / Always &#96;response.image_generation_call.partial_image&#96;. Discriminator that marks this object as a OpenAIResponsesImageGenCallPartialImage in a &#96;type&#96;-tagged union. / Always &#96;response.image_generation_call.completed&#96;. Discriminator that marks this object as a OpenAIResponsesImageGenCallCompleted in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call.in_progress&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallInProgress in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call.interpreting&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallInterpreting in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call.completed&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallCompleted in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call_code.delta&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallCodeDelta in a &#96;type&#96;-tagged union. / Always &#96;response.code_interpreter_call_code.done&#96;. Discriminator that marks this object as a OpenAIResponsesCodeInterpreterCallCodeDone in a &#96;type&#96;-tagged union. / Always &#96;response.web_search_call.in_progress&#96;. Discriminator that marks this object as a OpenAIResponsesWebSearchCallInProgress in a &#96;type&#96;-tagged union. / Always &#96;response.web_search_call.searching&#96;. Discriminator that marks this object as a OpenAIResponsesWebSearchCallSearching in a &#96;type&#96;-tagged union. / Always &#96;response.web_search_call.completed&#96;. Discriminator that marks this object as a OpenAIResponsesSearchCompleted in a &#96;type&#96;-tagged union. / Always &#96;response.custom_tool_call_input.delta&#96;. Discriminator that marks this object as a BaseCustomToolCallInputDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.custom_tool_call_input.done&#96;. Discriminator that marks this object as a BaseCustomToolCallInputDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.apply_patch_call_operation_diff.delta&#96;. Discriminator that marks this object as a ApplyPatchCallOperationDiffDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.apply_patch_call_operation_diff.done&#96;. Discriminator that marks this object as a ApplyPatchCallOperationDiffDoneEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.in_progress&#96;. Discriminator that marks this object as a FusionCallInProgressEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.added&#96;. Discriminator that marks this object as a FusionCallPanelAddedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.delta&#96;. Discriminator that marks this object as a FusionCallPanelDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.reasoning.delta&#96;. Discriminator that marks this object as a FusionCallPanelReasoningDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.completed&#96;. Discriminator that marks this object as a FusionCallPanelCompletedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.panel.failed&#96;. Discriminator that marks this object as a FusionCallPanelFailedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.analysis.in_progress&#96;. Discriminator that marks this object as a FusionCallAnalysisInProgressEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.analysis.completed&#96;. Discriminator that marks this object as a FusionCallAnalysisCompletedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.fusion_call.completed&#96;. Discriminator that marks this object as a FusionCallCompletedEvent in a &#96;type&#96;-tagged union. / Always &#96;response.debug&#96;. Discriminator that marks this object as a DebugEvent in a &#96;type&#96;-tagged union. |
| data.code | string &#124; null &#124; string | Error code; null when the upstream gave none. / The complete code the interpreter runs. |
| data.message | string | Human-readable error message. |
| data.param | string &#124; null | Name of the request parameter the error is about; null when it is not about a parameter. |
| data.item | object | An output item from the response |
| data.output_index | integer | Index of the item in the response output array that this event belongs to. |
| data.content_index | integer | Index of the content part inside the output item that this event belongs to. |
| data.item_id | string | Id of the output item this event belongs to; it equals the id of that item in the response output. |
| data.part | object | The content part as it starts: output text or refusal. / The content part in its final form: output text or refusal. / A reasoning summary part. / A reasoning summary part. |
| data.delta | string | Text fragment to append to the output text of this content part. / Refusal text fragment to append. / Fragment of the JSON-encoded function arguments to append. / Reasoning text fragment to append. / Reasoning summary text fragment to append. / Fragment of the code the interpreter will run, to append. / Fragment of the custom tool call input to append. / Fragment of the patch diff to append. / Text fragment the panel model produced. / Reasoning text fragment the panel model produced. |
| data.logprobs | array&lt;object&gt; | Log probabilities of the tokens in this fragment, when requested. / Log probabilities of the tokens in the complete text, when requested. |
| data.text | string | The complete output text of this content part. / The complete reasoning text of this content part. / The complete reasoning summary text of this part. |
| data.refusal | string | The complete refusal text. |
| data.annotation | object | Annotation attached to output text: a file citation, URL citation or file path. |
| data.annotation_index | integer | Index of the new annotation inside the content part's annotations array. |
| data.arguments | string | The complete JSON-encoded arguments of the function call. |
| data.name | string | Name of the function being called. |
| data.summary_index | integer | Index of the reasoning summary part inside the reasoning item that this event belongs to. |
| data.partial_image_b64 | string | Base64-encoded partial image produced while generation is still running. |
| data.partial_image_index | integer | Zero-based index of this partial image among the partial images of the call. |
| data.input | string | The complete input of the custom tool call. |
| data.diff | string | The complete patch diff. |
| data.model | string | Slug of the panel model that started. / Slug of the panel model that produced the fragment. / Slug of the panel model that produced the fragment. / Slug of the panel model that finished. / Slug of the panel model that failed. |
| data.content | string | The complete answer of the panel model. |
| data.error | string | Error message that explains why the panel model failed. |
| data.status_code | integer | HTTP status code of the failed upstream call, when one is available. |
| data.analyst_model | string | Slug of the model producing the structured analysis. |
| data.judge_model | string | Deprecated alias of &#96;analyst_model&#96;, kept so existing consumers keep working. Always carries the same value. Use &#96;analyst_model&#96;. |
| data.analysis | object | Structured analysis produced by the fusion analyst model. |
| data.debug | object | Debug information. |

# 读取响应

先调用「生成响应」，用返回的 ID 替换 resp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 删除响应

先调用「生成响应」，用返回的 ID 替换 resp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API delete response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 

先调用「生成响应」，用返回的 ID 替换 resp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API cancel response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 列出响应输入项

先调用「生成响应」，用返回的 ID 替换 resp\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API input item list

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API compact response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Native Responses API input token count

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 文本向量

## 响应 [#响应]

### HTTP 200 [#http-200]

Embedding response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | List of embedding objects |
| data[].embedding | array&lt;number&gt; &#124; string | Embedding vector as an array of floats or a base64 string |
| data[].index | integer | Index of the embedding in the input list |
| data[].object | string | Object type of the entry; always &#96;embedding&#96;. |
| id | string | Unique identifier for the embeddings response |
| model | string | The model used for embeddings |
| object | string | Object type; always &#96;list&#96;. |
| usage | object | Token usage statistics |
| usage.cost | number | Cost of the request in credits |
| usage.cost_details | object &#124; null | Breakdown of upstream inference costs |
| usage.is_byok | boolean | Whether a request was made using a Bring Your Own Key configuration |
| usage.prompt_tokens | integer | Number of tokens in the input |
| usage.prompt_tokens_details | object | Per-modality token breakdown. Only present when the input contains 2+ modalities (e.g. text + image) and the upstream provider returns modality-level usage data. Only non-zero modality counts are included. |
| usage.total_tokens | integer | Total number of tokens used |

**text/event-stream — chunk / 事件对象**

○ 未支持

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Optional id of the server-sent event. |
| event | string | Name of the server-sent event. |
| data | string | Payload of the server-sent event. |

# 重排文档

## 响应 [#响应]

### HTTP 200 [#http-200]

Cohere v2 rerank results.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| results | array&lt;object&gt; | Results ordered by relevance, best first. Each entry points back to a document with &#96;index&#96;. |
| results[].index | integer | Zero-based position of the document in the request &#96;documents&#96; array. |
| results[].relevance_score | number | Relevance of the document to the query, from 0 to 1; larger is more relevant. |

# 合成语音

## 响应 [#响应]

### HTTP 200 [#http-200]

Audio bytes in the requested format.

**audio/mpeg**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

**audio/ogg**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

**audio/aac**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

**audio/flac**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

**audio/wav**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

**audio/pcm**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

响应体为音频字节；右侧描述对象仅记录实采的 Content-Type 和字节数。

# 转写音频

## 响应 [#响应]

### HTTP 200 [#http-200]

Transcription in the requested format.

**text/plain**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string |  |

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| text | string | The transcribed text. |
| task | string | Task performed; always &#96;transcribe&#96;. |
| language | string | Language of the audio as detected or as requested. |
| duration | number | Duration of the audio in seconds. |
| segments | array&lt;object&gt; | Segments with timestamps, returned with &#96;verbose_json&#96; on models that support it. |
| segments[].id | integer | Zero-based index of the segment. |
| segments[].start | number | Start time of the segment in seconds. |
| segments[].end | number | End time of the segment in seconds. |
| segments[].text | string | The transcribed text. |
| segments[].temperature | number | Sampling temperature used for the segment. |
| segments[].avg_logprob | number | Average log probability of the tokens of the segment; low values mean low confidence. |
| segments[].compression_ratio | number | Gzip compression ratio of the segment text; high values indicate repetitive output. |
| segments[].no_speech_prob | number | Probability that the segment contains no speech. |

# 生成图像

## 响应 [#响应]

### HTTP 200 [#http-200]

Image generation response

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| created | integer | Unix time in seconds at which the images were created. |
| data | array&lt;object&gt; | Generated images. |
| data[].url | string | URL of the image; present when response_format is &#96;url&#96;. |
| data[].b64_json | string | Base64-encoded image; present when response_format is &#96;b64_json&#96;. |
| data[].revised_prompt | string | Prompt after the image model rewrote it, when the model reports it. |

# 编辑图像

## 响应 [#响应]

### HTTP 200 [#http-200]

Edited images

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| created | number | Unix time in seconds at which the images were created. |
| data | array&lt;object&gt; | Edited images. |
| data[].url | string | URL of the image; present when response_format is &#96;url&#96;. |
| data[].b64_json | string | Base64-encoded image; present when response_format is &#96;b64_json&#96;. |

# 文档识别

## 响应 [#响应]

### HTTP 200 [#http-200]

OCR pages and usage

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| pages | array&lt;object&gt; | Result per processed page, in page order. |
| pages[].index | integer | Zero-based index of the page in the document. |
| pages[].markdown | string | Page content as markdown. |
| pages[].images | array&lt;object&gt; | Images found on the page. |
| pages[].dimensions | object &#124; null | Size of the rendered page; null when unknown. |
| pages[].tables | array&lt;object&gt; | Tables extracted from the page when table_format is set. |
| pages[].hyperlinks | array&lt;string&gt; | Hyperlinks found on the page. |
| pages[].header | string &#124; null | Page header text; null when none was extracted. |
| pages[].footer | string &#124; null | Page footer text; null when none was extracted. |
| pages[].blocks | array&lt;object&gt; &#124; null | Layout blocks of the page, in reading order, when include_blocks is true. |
| pages[].confidence_scores | object &#124; null | Confidence scores of the page; null when not requested. |
| model | string | OCR model that processed the document. |
| usage_info | object | Usage of the request. |
| usage_info.pages_processed | integer | Number of pages that were processed. |
| usage_info.doc_size_bytes | integer &#124; null | Size of the document in bytes; null when unknown. |
| document_annotation | string &#124; null | Document annotation as a JSON string, when document_annotation_format was requested; null otherwise. |

# 创建视频

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the video job; pass it as &#96;video_id&#96; to retrieve, download or delete it. |
| object | string | Object type; always &#96;video&#96;. |
| model | string | Model that generates the video. |
| status | string | Lifecycle of the job. Poll until it is &#96;completed&#96; or &#96;failed&#96;. |
| progress | integer | Progress from 0 to 100. It is 0 until the job completes and 100 once it has. |
| created_at | integer | Unix time in seconds at which the job was created. |
| completed_at | integer &#124; null | Unix time in seconds at which the job completed; null until then. |
| expires_at | integer &#124; null | Unix time in seconds after which the output expires; null because outputs currently have no expiry. |
| seconds | string | Length of the video in seconds, as a string; for a completed job it is the delivered length. |
| size | string | Resolution of the video as &#96;WIDTHxHEIGHT&#96;; null when the provider did not report one. |
| prompt | string &#124; null | Prompt the job was created with. |
| remixed_from_video_id | null | Always null; remix is not supported. |
| error | object &#124; null | Why the job failed; null unless status is &#96;failed&#96;. |
| error.code | string | Machine-readable failure code. |
| error.message | string | Human-readable failure message. |
| polling_url | string | Relative URL to poll for the job state; same as retrieveVideo for this job. |
| unsigned_urls | array&lt;string&gt; | Relative URLs of the finished output; empty until the video is ready. Download them with the same API key. |
| usage | object | Cost of the job; present once a price applies. |
| usage.cost | number | Cost of the job in USD: delivered seconds times the per-second price once completed, 0 while running. |

## 创建、轮询与下载 [#创建轮询与下载]

先[创建视频](/docs/api/native/model/createVideo)，保存返回的 id；再[读取视频](/docs/api/native/model/retrieveVideo)轮询 status，queued / in\_progress 时继续等待，failed 时停止并查看 error；只有 completed 后才[下载视频内容](/docs/api/native/model/downloadVideoContent)。

典型耗时为 10–15 分钟；以下示例最多轮询 30 分钟，超时后可用同一个任务 ID 继续查询。

```bash
# Requires curl and jq. Set PRAXIS_API_KEY and API_BASE (your API origin).
job=$(curl --fail-with-body -sS "$API_BASE/model/v1/videos" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" -H "Content-Type: application/json" \
  -d '{"model":"wan2.7-t2v","prompt":"A cat stretching in the morning sun","seconds":"4","size":"1280x720"}') || exit 1
VIDEO_ID=$(printf '%s' "$job" | jq -er '.id') || exit 1
for attempt in $(seq 1 360); do
  job=$(curl --fail-with-body -sS "$API_BASE/model/v1/videos/$VIDEO_ID" \
    -H "Authorization: Bearer $PRAXIS_API_KEY") || exit 1
  status=$(printf '%s' "$job" | jq -er '.status') || exit 1
  case "$status" in
    completed) break ;;
    failed) printf '%s\n' "$job"; exit 1 ;;
    queued|in_progress) sleep 5 ;;
    *) printf 'Unexpected status: %s\n' "$status"; exit 1 ;;
  esac
done
[ "$status" = completed ] || { printf 'Still processing; resume polling %s\n' "$VIDEO_ID"; exit 1; }
curl --fail-with-body -sS "$API_BASE/model/v1/videos/$VIDEO_ID/content" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" -o video.mp4
```

# 列出视频

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;list&#96;. |
| data | array&lt;object&gt; | Video jobs of the caller, newest first by default. |
| data[].id | string | Id of the video job; pass it as &#96;video_id&#96; to retrieve, download or delete it. |
| data[].object | string | Object type; always &#96;video&#96;. |
| data[].model | string | Model that generates the video. |
| data[].status | string | Lifecycle of the job. Poll until it is &#96;completed&#96; or &#96;failed&#96;. |
| data[].progress | integer | Progress from 0 to 100. It is 0 until the job completes and 100 once it has. |
| data[].created_at | integer | Unix time in seconds at which the job was created. |
| data[].completed_at | integer &#124; null | Unix time in seconds at which the job completed; null until then. |
| data[].expires_at | integer &#124; null | Unix time in seconds after which the output expires; null because outputs currently have no expiry. |
| data[].seconds | string | Length of the video in seconds, as a string; for a completed job it is the delivered length. |
| data[].size | string | Resolution of the video as &#96;WIDTHxHEIGHT&#96;; null when the provider did not report one. |
| data[].prompt | string &#124; null | Prompt the job was created with. |
| data[].remixed_from_video_id | null | Always null; remix is not supported. |
| data[].error | object &#124; null | Why the job failed; null unless status is &#96;failed&#96;. |
| data[].polling_url | string | Relative URL to poll for the job state; same as retrieveVideo for this job. |
| data[].unsigned_urls | array&lt;string&gt; | Relative URLs of the finished output; empty until the video is ready. Download them with the same API key. |
| data[].usage | object | Cost of the job; present once a price applies. |
| has_more | boolean | Whether more jobs exist beyond this page; pass &#96;last_id&#96; as &#96;after&#96; to read them. |
| first_id | string &#124; null | Id of the first job in this page; null for an empty page. |
| last_id | string &#124; null | Id of the last job in this page; null for an empty page. |

先[创建视频](/docs/api/native/model/createVideo)，保存返回的 id；再[读取视频](/docs/api/native/model/retrieveVideo)轮询 status，queued / in\_progress 时继续等待，failed 时停止并查看 error；只有 completed 后才[下载视频内容](/docs/api/native/model/downloadVideoContent)。

# 读取视频

先调用「创建视频」，用返回的 ID 替换 video\_123；下载前须轮询至 completed。

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the video job; pass it as &#96;video_id&#96; to retrieve, download or delete it. |
| object | string | Object type; always &#96;video&#96;. |
| model | string | Model that generates the video. |
| status | string | Lifecycle of the job. Poll until it is &#96;completed&#96; or &#96;failed&#96;. |
| progress | integer | Progress from 0 to 100. It is 0 until the job completes and 100 once it has. |
| created_at | integer | Unix time in seconds at which the job was created. |
| completed_at | integer &#124; null | Unix time in seconds at which the job completed; null until then. |
| expires_at | integer &#124; null | Unix time in seconds after which the output expires; null because outputs currently have no expiry. |
| seconds | string | Length of the video in seconds, as a string; for a completed job it is the delivered length. |
| size | string | Resolution of the video as &#96;WIDTHxHEIGHT&#96;; null when the provider did not report one. |
| prompt | string &#124; null | Prompt the job was created with. |
| remixed_from_video_id | null | Always null; remix is not supported. |
| error | object &#124; null | Why the job failed; null unless status is &#96;failed&#96;. |
| error.code | string | Machine-readable failure code. |
| error.message | string | Human-readable failure message. |
| polling_url | string | Relative URL to poll for the job state; same as retrieveVideo for this job. |
| unsigned_urls | array&lt;string&gt; | Relative URLs of the finished output; empty until the video is ready. Download them with the same API key. |
| usage | object | Cost of the job; present once a price applies. |
| usage.cost | number | Cost of the job in USD: delivered seconds times the per-second price once completed, 0 while running. |

先[创建视频](/docs/api/native/model/createVideo)，保存返回的 id；再[读取视频](/docs/api/native/model/retrieveVideo)轮询 status，queued / in\_progress 时继续等待，failed 时停止并查看 error；只有 completed 后才[下载视频内容](/docs/api/native/model/downloadVideoContent)。

# 下载视频内容

先调用「创建视频」，用返回的 ID 替换 video\_123；下载前须轮询至 completed。

## 响应 [#响应]

### HTTP 200 [#http-200]

Video or thumbnail bytes

**video/mp4**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

**image/jpeg**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

先[创建视频](/docs/api/native/model/createVideo)，保存返回的 id；再[读取视频](/docs/api/native/model/retrieveVideo)轮询 status，queued / in\_progress 时继续等待，failed 时停止并查看 error；只有 completed 后才[下载视频内容](/docs/api/native/model/downloadVideoContent)。

# 删除视频

先调用「创建视频」，用返回的 ID 替换 video\_123；下载前须轮询至 completed。

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the deleted video job. |
| object | string | Object type; always &#96;video.deleted&#96;. |
| deleted | boolean | Always true; the job is no longer readable. |

先[创建视频](/docs/api/native/model/createVideo)，保存返回的 id；再[读取视频](/docs/api/native/model/retrieveVideo)轮询 status，queued / in\_progress 时继续等待，failed 时停止并查看 error；只有 completed 后才[下载视频内容](/docs/api/native/model/downloadVideoContent)。

# 

先调用「创建视频」，用返回的 ID 替换 video\_123；下载前须轮询至 completed。

## 响应 [#响应]

此端点没有声明成功响应。

先[创建视频](/docs/api/native/model/createVideo)，保存返回的 id；再[读取视频](/docs/api/native/model/retrieveVideo)轮询 status，queued / in\_progress 时继续等待，failed 时停止并查看 error；只有 completed 后才[下载视频内容](/docs/api/native/model/downloadVideoContent)。

# 发送消息

## 响应 [#响应]

### HTTP 200 [#http-200]

Message created

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Unique object identifier.  The format and length of IDs may change over time. |
| container | null &#124; object | Information about the container used in the request (for the code execution tool) |
| container.id | string | Identifier for the container used in this request |
| container.expires_at | string | The time at which the container will expire. |
| container.skills | null &#124; array&lt;object&gt; | Skills loaded in the container |
| content | array&lt;object&gt; | Content generated by the model.  This is an array of content blocks, each of which has a &#96;type&#96; that determines its shape.  Example:  &#96;&#96;&#96;json [&#123; "type": "text", "text": "Hi, I'm Claude." &#125;] &#96;&#96;&#96;  If the request input &#96;messages&#96; ended with an &#96;assistant&#96; turn, then the response &#96;content&#96; will continue directly from that last turn. You can use this to constrain the model's output.  For example, if the input &#96;messages&#96; were:  &#96;&#96;&#96;json [   &#123;     "role": "user",     "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"   &#125;,   &#123; "role": "assistant", "content": "The best answer is (" &#125; ] &#96;&#96;&#96;  Then the response &#96;content&#96; might be:  &#96;&#96;&#96;json [&#123; "type": "text", "text": "B)" &#125;] &#96;&#96;&#96; |
| content[].citations | null &#124; array&lt;object&gt; | Citations supporting the text block.  The type of citation returned will depend on the type of document being cited. Citing a PDF results in &#96;page_location&#96;, plain text results in &#96;char_location&#96;, and content document results in &#96;content_block_location&#96;. |
| content[].text | string | The text generated by the model. |
| content[].type | string | Always &#96;text&#96;. Discriminator that marks this object as a TextBlock in a &#96;type&#96;-tagged union. / Always &#96;thinking&#96;. Discriminator that marks this object as a ThinkingBlock in a &#96;type&#96;-tagged union. / Always &#96;redacted_thinking&#96;. Discriminator that marks this object as a RedactedThinkingBlock in a &#96;type&#96;-tagged union. / Always &#96;tool_use&#96;. Discriminator that marks this object as a ToolUseBlock in a &#96;type&#96;-tagged union. / Always &#96;server_tool_use&#96;. Discriminator that marks this object as a ServerToolUseBlock in a &#96;type&#96;-tagged union. / Always &#96;web_search_tool_result&#96;. Discriminator that marks this object as a WebSearchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;web_fetch_tool_result&#96;. Discriminator that marks this object as a WebFetchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;code_execution_tool_result&#96;. Discriminator that marks this object as a CodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;bash_code_execution_tool_result&#96;. Discriminator that marks this object as a BashCodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;text_editor_code_execution_tool_result&#96;. Discriminator that marks this object as a TextEditorCodeExecutionToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;tool_search_tool_result&#96;. Discriminator that marks this object as a ToolSearchToolResultBlock in a &#96;type&#96;-tagged union. / Always &#96;container_upload&#96;. Discriminator that marks this object as a ContainerUploadBlock in a &#96;type&#96;-tagged union. |
| content[].signature | string | A value used to verify that this thinking block was generated by Claude when it is passed back to the API.  This is an opaque field and should not be interpreted or parsed. When passing thinking blocks back to the API (required when using tools with extended thinking), pass them back exactly as received, with this field intact.  See [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) for details. |
| content[].thinking | string | The text of Claude's thinking process for this block. |
| content[].data | string | The contents of this redacted thinking block, returned when portions of the model's thinking were safety-redacted. This field is opaque and encrypted, with no readable content.  Pass &#96;redacted_thinking&#96; blocks back to the API unchanged when continuing a multi-turn conversation.  See [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#redacted-thinking-blocks) for details. |
| content[].id | string | Id of the tool call; send it back as tool_use_id in the tool_result block that answers it. / Id of the server tool call; the matching result block repeats it as tool_use_id. |
| content[].caller | object | Which party invoked the tool: the model directly or a code execution tool. / Which party invoked the server tool: the model directly or a code execution tool. / Which party invoked the search: the model directly or a code execution tool. / Which party invoked the fetch: the model directly or a code execution tool. |
| content[].input | any | Arguments the model chose, as a JSON object that follows the tool's input_schema. / Arguments the model passed to the server tool, as a JSON object. |
| content[].name | string | Name of the tool the model wants to call. / Name of the server tool the model called, such as web_search, web_fetch or code_execution. |
| content[].toolset_name | null &#124; string | For a toolset member tool_use, the toolset family. |
| content[].content | object &#124; array&lt;object&gt; &#124; object &#124; object &#124; object &#124; object &#124; object | Search results (array of web_search_result blocks) or an error object. / The fetched document or an error object. / Result of the code execution: a result block, an encrypted result block, or an error object. / Result of the bash command: a result block or an error object. / Result of the text editor command: a view, create or str_replace result block, or an error object. / Result of the tool search: a search result block that lists tool references, or an error object. |
| content[].tool_use_id | string | Id of the web_search server tool call this result belongs to. / Id of the web_fetch server tool call this result belongs to. / Id of the code_execution server tool call this result belongs to. / Id of the bash_code_execution server tool call this result belongs to. / Id of the text_editor_code_execution server tool call this result belongs to. / Id of the tool search server tool call this result belongs to. |
| content[].file_id | string | Id of the file that was uploaded into the code execution container. |
| model | string | The model that will complete your prompt.  See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. |
| role | string | Conversational role of the generated message.  This will always be &#96;"assistant"&#96;. |
| stop_details | null &#124; object | Structured information about a refusal. |
| stop_details.category | null &#124; string | The policy category that triggered a refusal.  - &#96;cyber&#96; - The request could enable cyber harm, such as malware or exploit   development. Benign cybersecurity work can also trigger this category. - &#96;bio&#96; - The request could enable biological harm, such as dangerous lab   methods. Beneficial life sciences work can also trigger this category. - &#96;frontier_llm&#96; - The request could assist the development of competing AI   models, which is restricted under   [Anthropic's commercial terms](https://www.anthropic.com/legal/commercial-terms).   Benign machine learning work can also trigger this category. - &#96;reasoning_extraction&#96; - The request asks the model to reproduce its internal   reasoning in the response text. To get reasoning in a structured form instead,   use   [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking). - &#96;general_harms&#96; - The request could be related to an area that was determined   as harmful. Benign work might sometimes trigger this category. |
| stop_details.explanation | null &#124; string | Human-readable explanation of the refusal.  This text is not guaranteed to be stable. &#96;null&#96; when no explanation is available for the category. |
| stop_details.type | string | Always &#96;refusal&#96;. Discriminator that marks this object as a RefusalStopDetails in a &#96;type&#96;-tagged union. |
| stop_reason | null &#124; string | The reason that we stopped.  This may be one the following values:  - &#96;"end_turn"&#96;: the model reached a natural stopping point - &#96;"max_tokens"&#96;: we exceeded the requested &#96;max_tokens&#96; or the model's maximum - &#96;"stop_sequence"&#96;: one of your provided custom &#96;stop_sequences&#96; was generated - &#96;"tool_use"&#96;: the model invoked one or more tools - &#96;"pause_turn"&#96;: we paused a long-running turn. You may provide the response   back as-is in a subsequent request to let the model continue. - &#96;"refusal"&#96;: when streaming classifiers intervene to handle potential policy   violations - &#96;"model_context_window_exceeded"&#96;: we exceeded the model's context window  In non-streaming mode this value is always non-null. In streaming mode, it is null in the &#96;message_start&#96; event and non-null otherwise. |
| stop_sequence | null &#124; string | Which custom stop sequence was generated, if any.  This value will be a non-null string if one of your custom stop sequences was generated. |
| type | string | Object type.  For Messages, this is always &#96;"message"&#96;. |
| usage | object | Billing and rate-limit usage.  Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.  Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in &#96;usage&#96; will not match one-to-one with the exact visible content of an API request or response.  For example, &#96;output_tokens&#96; will be non-zero, even for an empty string response from Claude.  Total input tokens in a request is the summation of &#96;input_tokens&#96;, &#96;cache_creation_input_tokens&#96;, and &#96;cache_read_input_tokens&#96;. |
| usage.cache_creation | null &#124; object | Breakdown of cached tokens by TTL |
| usage.cache_creation_input_tokens | null &#124; number | The number of input tokens used to create the cache entry. |
| usage.cache_read_input_tokens | null &#124; number | The number of input tokens read from the cache. |
| usage.inference_geo | null &#124; string | The geographic region where inference was performed for this request. |
| usage.input_tokens | number | The number of input tokens which were used. |
| usage.output_tokens | number | The number of output tokens which were used. |
| usage.output_tokens_details | null &#124; object | Breakdown of output tokens by category.  &#96;output_tokens&#96; remains the inclusive, authoritative total used for billing. This object provides a read-only decomposition for observability — for example, how many of the billed output tokens were spent on internal reasoning that may have been summarized before being returned to you. |
| usage.server_tool_use | null &#124; object | The number of server tool requests. |
| usage.service_tier | null &#124; string | If the request used the priority, standard, or batch tier. |

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Optional id of the server-sent event. |
| event | string | Name of the server-sent event. |
| data | object | 完整 SDK RawMessageStreamEvent union |
| data.delta | object | Final fields of the message sent with message_delta: why generation stopped and the container. / The incremental change to the content block at index. |
| data.type | string | Always &#96;message_delta&#96;. Discriminator that marks this object as a RawMessageDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;content_block_delta&#96;. Discriminator that marks this object as a RawContentBlockDeltaEvent in a &#96;type&#96;-tagged union. / Always &#96;message_start&#96;. Discriminator that marks this object as a RawMessageStartEvent in a &#96;type&#96;-tagged union. / Always &#96;message_stop&#96;. Discriminator that marks this object as a RawMessageStopEvent in a &#96;type&#96;-tagged union. / Always &#96;content_block_start&#96;. Discriminator that marks this object as a RawContentBlockStartEvent in a &#96;type&#96;-tagged union. / Always &#96;content_block_stop&#96;. Discriminator that marks this object as a RawContentBlockStopEvent in a &#96;type&#96;-tagged union. |
| data.usage | object | Billing and rate-limit usage.  Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.  Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in &#96;usage&#96; will not match one-to-one with the exact visible content of an API request or response.  For example, &#96;output_tokens&#96; will be non-zero, even for an empty string response from Claude.  Total input tokens in a request is the summation of &#96;input_tokens&#96;, &#96;cache_creation_input_tokens&#96;, and &#96;cache_read_input_tokens&#96;. |
| data.index | number | Zero-based index of the content block this delta applies to. / Zero-based index of the content block that starts. / Zero-based index of the content block that ends. |
| data.message | object | The complete Message object being started; its content is empty at message_start and filled by the following content_block events. |
| data.content_block | object | The content block as it starts, with empty text or input to be filled by deltas. |

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

Token count

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| input_tokens | number | The total number of tokens across the provided list of messages, system prompt, and tools. |

# 列出模型

## 响应 [#响应]

### HTTP 200 [#http-200]

Model list

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;list&#96;. |
| data | array&lt;object&gt; | Published models, in the order the catalog returns them, filtered by type, supported_api and output_modalities when given. |
| data[].id | string | Model id to pass as &#96;model&#96; in other calls. It can carry a creator prefix such as deepseek/deepseek-v4-pro. |
| data[].object | string | Object type; always &#96;model&#96;. |
| data[].created | number | Unix time in seconds at which the model was first published. |
| data[].owned_by | string | Organization that serves the model on this platform; always &#96;deepractice&#96;. |
| data[].name | string | Display name, prefixed with the vendor when one is known, for example &#96;Vendor: Model&#96;. |
| data[].description | string &#124; null | Free-text description of the model; null when none is published. |
| data[].context_window | number &#124; null | Maximum context length in tokens (input plus output); null when the catalog has no figure. |
| data[].max_tokens | number &#124; null | Maximum number of output tokens the model can produce in one call; null when the catalog has no figure. |
| data[].type | string | Kind of model; it decides which endpoint accepts it. |
| data[].supported_apis | array&lt;string&gt; | Declared protocol IDs in stable lexicographic order; an empty array means no protocol is declared. Use these IDs with supported_api to find models for an operation. |
| data[].tags | array&lt;string&gt; | Capability tags of the model such as &#96;tools&#96;, &#96;vision&#96; or &#96;reasoning&#96;; use them to filter for features. |
| data[].architecture | object | Native modalities of the model. |
| data[].x_praxis | object | Platform extension. input_modalities states, per input format, how the model takes it. |
| data[].pricing | object | Prices in USD per named unit, as decimal strings. A unit that is absent is unpriced, which is not the same as free. |
| data[].released | string | Date (YYYY-MM-DD, UTC) on which the model was first published. |

# 读取模型

## 响应 [#响应]

### HTTP 200 [#http-200]

Model

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Model id to pass as &#96;model&#96; in other calls. It can carry a creator prefix such as deepseek/deepseek-v4-pro. |
| object | string | Object type; always &#96;model&#96;. |
| created | number | Unix time in seconds at which the model was first published. |
| owned_by | string | Organization that serves the model on this platform; always &#96;deepractice&#96;. |
| name | string | Display name, prefixed with the vendor when one is known, for example &#96;Vendor: Model&#96;. |
| description | string &#124; null | Free-text description of the model; null when none is published. |
| context_window | number &#124; null | Maximum context length in tokens (input plus output); null when the catalog has no figure. |
| max_tokens | number &#124; null | Maximum number of output tokens the model can produce in one call; null when the catalog has no figure. |
| type | string | Kind of model; it decides which endpoint accepts it. |
| supported_apis | array&lt;string&gt; | Declared protocol IDs in stable lexicographic order; an empty array means no protocol is declared. Use these IDs with supported_api to find models for an operation. |
| tags | array&lt;string&gt; | Capability tags of the model such as &#96;tools&#96;, &#96;vision&#96; or &#96;reasoning&#96;; use them to filter for features. |
| architecture | object | Native modalities of the model. |
| architecture.modality | string | Native modalities as &#96;input+input-&gt;output+output&#96;, for example &#96;text+image-&gt;text&#96;. |
| architecture.input_modalities | array&lt;string&gt; | Input modalities the model accepts natively, for example text, image, file or audio. |
| architecture.output_modalities | array&lt;string&gt; | Output modalities the model produces, for example text, image, audio, video, embeddings or rerank. |
| architecture.tokenizer | string &#124; null | Tokenizer family; null because the platform does not publish it. |
| architecture.instruct_type | string &#124; null | Instruction template type; null because the platform does not publish it. |
| x_praxis | object | Platform extension. input_modalities states, per input format, how the model takes it. |
| x_praxis.input_modalities | object | Per input format, whether the model takes it natively, through a conversion step, or not at all. Conversion depends on the file-parser plugin settings. |
| pricing | object | Prices in USD per named unit, as decimal strings. A unit that is absent is unpriced, which is not the same as free. |
| pricing.input | string | USD per input token. |
| pricing.output | string | USD per output token. |
| pricing.input_cache_read | string | USD per input token that is read from the prompt cache. |
| pricing.input_cache_write | string | USD per input token that is written to the prompt cache. |
| pricing.image | string | USD per image; present only for a flat registry price. |
| pricing.video_second | string | Praxis extension: USD per second of output video. |
| pricing.audio_input_minute | string | Praxis extension: USD per minute of input audio. |
| pricing.audio_output_minute | string | Praxis extension: USD per minute of output audio. |
| pricing.input_character | string | Praxis extension: USD per input character. |
| pricing.page | string | Praxis extension: USD per page, present only for OCR models; not a Vercel AI Gateway pricing field. |
| released | string | Date (YYYY-MM-DD, UTC) on which the model was first published. |

# 查询生成记录

先调用「对话」，从响应头 X-Praxis-Generation-Id 取得 id，替换 gen\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Generation record

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Generation id that was queried. |
| model | string | Model that served the generation. |
| cost | number &#124; null | Cost charged for the generation in USD; null when not yet priced. |
| usage | object | Token usage of the generation. |
| usage.prompt_tokens | number | Number of prompt tokens. |
| usage.completion_tokens | number | Number of tokens in the completion. |
| usage.total_tokens | number | Prompt plus completion tokens. |
| usage.cached_input_tokens | number | Prompt tokens served from the prompt cache; null when not reported. |
| latency_ms | number &#124; null | Latency of the generation in milliseconds; null when not recorded. |
| created | number | Unix time in seconds at which the generation was recorded. |

# 创建会话

## 响应 [#响应]

### HTTP 200 [#http-200]

The created conversation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the conversation, such as &#96;conv_...&#96;; use it as &#96;conversation_id&#96; in conversation calls and as &#96;conversation&#96; in createResponse. |
| object | string | Object type; always &#96;conversation&#96;. |
| created_at | integer | Unix time in seconds at which the conversation was created. |
| metadata | object | Up to 16 string key/value pairs; keys at most 64 characters and values at most 512. |

# 读取会话

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The conversation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the conversation, such as &#96;conv_...&#96;; use it as &#96;conversation_id&#96; in conversation calls and as &#96;conversation&#96; in createResponse. |
| object | string | Object type; always &#96;conversation&#96;. |
| created_at | integer | Unix time in seconds at which the conversation was created. |
| metadata | object | Up to 16 string key/value pairs; keys at most 64 characters and values at most 512. |

# 更新会话

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The updated conversation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the conversation, such as &#96;conv_...&#96;; use it as &#96;conversation_id&#96; in conversation calls and as &#96;conversation&#96; in createResponse. |
| object | string | Object type; always &#96;conversation&#96;. |
| created_at | integer | Unix time in seconds at which the conversation was created. |
| metadata | object | Up to 16 string key/value pairs; keys at most 64 characters and values at most 512. |

# 创建会话条目

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The items just added

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;list&#96;. |
| data | array&lt;object&gt; | Items of the conversation, in the order the list requested. |
| first_id | string | Id of the first item of this page; null for an empty page. |
| last_id | string | Id of the last item of this page; null for an empty page. |
| has_more | boolean | Whether more items exist beyond this page; pass &#96;last_id&#96; as &#96;after&#96; to read them. |

# 列出会话条目

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The conversation's items

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;list&#96;. |
| data | array&lt;object&gt; | Items of the conversation, in the order the list requested. |
| first_id | string | Id of the first item of this page; null for an empty page. |
| last_id | string | Id of the last item of this page; null for an empty page. |
| has_more | boolean | Whether more items exist beyond this page; pass &#96;last_id&#96; as &#96;after&#96; to read them. |

# 读取会话条目

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。 条目 ID 取自「添加对话条目」或「列出对话条目」，替换 item\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The item

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | object |  |

# 删除会话条目

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。 条目 ID 取自「添加对话条目」或「列出对话条目」，替换 item\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The conversation, with the item removed

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the conversation, such as &#96;conv_...&#96;; use it as &#96;conversation_id&#96; in conversation calls and as &#96;conversation&#96; in createResponse. |
| object | string | Object type; always &#96;conversation&#96;. |
| created_at | integer | Unix time in seconds at which the conversation was created. |
| metadata | object | Up to 16 string key/value pairs; keys at most 64 characters and values at most 512. |

# 删除会话

先调用「创建对话」拿到 conv\_ 开头的 ID，替换 conv\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Deletion confirmation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id of the deleted conversation. |
| object | string | Object type; always &#96;conversation.deleted&#96;. |
| deleted | boolean | Always true; neither the conversation nor its items can be referenced again. |

# 沙箱 API

（待译）

Sandbox runs isolated environments for commands, files and HTTP services through /sandbox/v1, with an SDK-compatible face at /e2b. Concepts and behavior follow E2B (templates, sandboxes, envd files and commands, timeouts and pause/resume), so E2B experience applies. Differences: templateID resolves to your ready Environment or a public Base and must be supplied explicitly; light sandboxes are own-face only, preserve disk rather than memory on pause and provide a limited shell, line terminals and no metrics; port URLs use the returned sandboxID and domain, not an E2B hostname; network.httpsPorts is rejected; persistent sandboxes can resume on traffic even when autoResume is false. Files and command execution use the envd data plane; the sandbox management methods do not execute commands or write files. Start with `praxis.sandbox.templates.list` to choose an available template.

## 基础地址 [#基础地址]

## 接入 [#接入]

## HTTP 与 SDK 接入 [#http-与-sdk-接入]

用 HTTP 直接调用 `/sandbox/v1`，请求携带 `X-API-Key`。官方 E2B SDK 请使用 [E2B 兼容接口](/docs/api/compatible/e2b)，不能只修改 API 地址来调用这里的接口。

HTTP 基础地址：<ApiOriginInline text="https://api-origin.invalid/sandbox/v1" />。

## 端点 [#端点]

| 方法     | 路径                                                                                                            | 说明      | 支持   |
| ------ | ------------------------------------------------------------------------------------------------------------- | ------- | ---- |
| POST   | [`/v1/sandboxes`](/docs/api/native/sandbox/createSandbox)                                                     | 创建沙箱    | ● 支持 |
| POST   | [`/v1/sandboxes/{sandboxID}/upgrade`](/docs/api/native/sandbox/upgradeSandbox)                                | 升级为完整沙箱 | ● 支持 |
| GET    | [`/v1/sandboxes`](/docs/api/native/sandbox/listSandboxes)                                                     | 列出沙箱    | ● 支持 |
| GET    | [`/v1/sandboxes/{sandboxID}`](/docs/api/native/sandbox/getSandbox)                                            | 读取沙箱    | ● 支持 |
| PATCH  | [`/v1/sandboxes/{sandboxID}`](/docs/api/native/sandbox/renameSandbox)                                         | 重命名沙箱   | ● 支持 |
| GET    | [`/v1/sandboxes/{sandboxID}/metrics`](/docs/api/native/sandbox/getSandboxMetrics)                             | 沙箱指标    | ● 支持 |
| POST   | [`/v1/sandboxes/{sandboxID}/timeout`](/docs/api/native/sandbox/setSandboxTimeout)                             | 设置超时    | ● 支持 |
| POST   | [`/v1/sandboxes/{sandboxID}/pause`](/docs/api/native/sandbox/pauseSandbox)                                    | 暂停沙箱    | ● 支持 |
| POST   | [`/v1/sandboxes/{sandboxID}/connect`](/docs/api/native/sandbox/connectSandbox)                                | 连接沙箱    | ● 支持 |
| DELETE | [`/v1/sandboxes/{sandboxID}`](/docs/api/native/sandbox/killSandbox)                                           | 终止沙箱    | ● 支持 |
| GET    | [`/v1/templates`](/docs/api/native/sandbox/listTemplates)                                                     | 列出模板    | ● 支持 |
| POST   | [`/v1/volumes`](/docs/api/native/sandbox/createVolume)                                                        | 创建卷     | ● 支持 |
| GET    | [`/v1/volumes`](/docs/api/native/sandbox/listVolumes)                                                         | 列出卷     | ● 支持 |
| GET    | [`/v1/volumes/{volumeID}`](/docs/api/native/sandbox/getVolume)                                                | 读取卷     | ● 支持 |
| DELETE | [`/v1/volumes/{volumeID}`](/docs/api/native/sandbox/deleteVolume)                                             | 删除卷     | ● 支持 |
| POST   | [`/v1/sandboxes/{sandboxID}/fork`](/docs/api/native/sandbox/forkSandbox)                                      | 复制沙箱    | ● 支持 |
| POST   | [`/v1/sandboxes/{sandboxID}/snapshots`](/docs/api/native/sandbox/createSnapshot)                              | 创建快照    | ● 支持 |
| GET    | [`/v1/snapshots`](/docs/api/native/sandbox/listSnapshots)                                                     | 列出快照    | ● 支持 |
| DELETE | [`/v1/snapshots/{snapshotID}`](/docs/api/native/sandbox/deleteSnapshot)                                       | 删除快照    | ● 支持 |
| PUT    | [`/v1/sandboxes/{sandboxID}/network`](/docs/api/native/sandbox/updateSandboxNetwork)                          | 更新网络策略  | ● 支持 |
| GET    | [`/v1/sandboxes/{sandboxID}/logs`](/docs/api/native/sandbox/getSandboxLogs)                                   | 读取沙箱日志  | ● 支持 |
| POST   | [`/v1/sandboxes/{sandboxID}/extend`](/docs/api/native/sandbox/extendSandbox)                                  | 延长沙箱    | ● 支持 |
| GET    | [`/v1/sandboxes/{sandboxID}/processes`](/docs/api/native/sandbox/listObservedProcesses)                       | 列出进程    | ● 支持 |
| GET    | [`/v1/sandboxes/{sandboxID}/processes/{processID}/output`](/docs/api/native/sandbox/getObservedProcessOutput) | 读取输出    | ● 支持 |

## 与官方的差异 [#与官方的差异]

* 快照使用本平台 snap\_ 开头的 ID，可作为创建沙箱的 templateID。旧供应商句柄不再接受。暂停的沙箱用「连接沙箱」恢复运行。
* 仅提供本页声明的端点，webhooks 等未采纳的端点返回 404。
* <a href="/docs/api/native/sandbox/createSandbox">创建沙箱</a>：平台暂未提供 E2B 默认的 base 模板：不带模板参数的 Sandbox.create() 会返回 404，请显式指定模板（可用模板见「列出模板」）。

参数与字段的权威定义以 [E2B 官方文档](https://docs.e2b.dev/api-reference)为准。

错误按 E2B 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 创建沙箱

## 响应 [#响应]

### HTTP 201 [#http-201]

The sandbox was created successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

# 升级为完整沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Upgraded sandbox detail with a replacement access token

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| alias | string | Alias of the template |
| sandboxID | string | Identifier of the sandbox |
| clientID | string | Identifier of the client |
| startedAt | string | Time when the sandbox was started |
| endAt | string | Time when the sandbox will expire |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| allowInternetAccess | boolean | Whether internet access was explicitly enabled or disabled for the sandbox. Null means it was not explicitly set. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |
| cpuCount | integer | CPU cores for the sandbox |
| memoryMB | integer | Memory for the sandbox in MiB |
| diskSizeMB | integer | Disk size for the sandbox in MiB |
| metadata | any | Your own string key/value pairs stored with the sandbox; usable as a filter in listSandboxes. |
| state | string | State of the sandbox |
| network | object | Network policy of the sandbox: public access, egress allow and deny lists and proxy. |
| network.allowPublicTraffic | boolean | Specify if the sandbox URLs should be accessible only with authentication. |
| network.allowOut | array&lt;string&gt; | List of allowed destinations for egress traffic. Each entry can be a CIDR block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com", "*.example.com"). Allowed entries always take precedence over denied entries. |
| network.denyOut | array&lt;string&gt; | List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules. |
| network.egressProxy | object | SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through the proxy after allow/deny filtering; the sandbox is unaware. Domain-matched flows use remote DNS (ATYP=domain). |
| network.maskRequestHost | string | Specify host mask which will be used for all sandbox requests |
| network.httpsPorts | array&lt;integer&gt; | Unlike E2B, network.httpsPorts is rejected; omit it and serve plaintext HTTP inside the sandbox. The public port URL still uses HTTPS. The upstream field denotes HTTPS-speaking internal ports, permits self-signed certificates and excludes envd port 49983. |
| network.rules | object | Per-domain transform rules applied to matching outbound HTTPS requests. Keys may be exact DNS names (for example, "api.example.com") or a leading wildcard (for example, "*.example.com"), and are normalized to lowercase on write. Wildcards match subdomains at any depth but not the apex domain; a bare "*" is invalid. Exact rules take precedence, followed by the longest matching wildcard suffix, and matching rule sets are not merged. Broad wildcards such as "*.com" are allowed and may expose transformed credentials to every matching destination the sandbox contacts. Rules do not grant network access; configure allowOut separately to permit the destination.  |
| lifecycle | object | Sandbox lifecycle policy returned by sandbox info. |
| lifecycle.autoResume | boolean | Whether the sandbox can auto-resume. |
| lifecycle.onTimeout | string | Action taken when the sandbox times out. |
| volumeMounts | array&lt;object&gt; | Volumes mounted into the sandbox. |
| volumeMounts[].name | string | Name of the volume |
| volumeMounts[].path | string | Path of the volume |

# 列出沙箱

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned all running sandboxes

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].templateID | string | Identifier of the template from which is the sandbox created |
| [].alias | string | Alias of the template |
| [].sandboxID | string | Identifier of the sandbox |
| [].clientID | string | Identifier of the client |
| [].startedAt | string | Time when the sandbox was started |
| [].endAt | string | Time when the sandbox will expire |
| [].cpuCount | integer | CPU cores for the sandbox |
| [].memoryMB | integer | Memory for the sandbox in MiB |
| [].diskSizeMB | integer | Disk size for the sandbox in MiB |
| [].metadata | any | Your own string key/value pairs stored with the sandbox; usable as a filter in listSandboxes. |
| [].state | string | State of the sandbox |
| [].envdVersion | string | Version of the envd running in the sandbox |
| [].volumeMounts | array&lt;object&gt; | Volumes mounted into the sandbox. |
| [].volumeMounts[].name | string | Name of the volume |
| [].volumeMounts[].path | string | Path of the volume |

# 读取沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned the sandbox

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| alias | string | Alias of the template |
| sandboxID | string | Identifier of the sandbox |
| clientID | string | Identifier of the client |
| startedAt | string | Time when the sandbox was started |
| endAt | string | Time when the sandbox will expire |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| allowInternetAccess | boolean | Whether internet access was explicitly enabled or disabled for the sandbox. Null means it was not explicitly set. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |
| cpuCount | integer | CPU cores for the sandbox |
| memoryMB | integer | Memory for the sandbox in MiB |
| diskSizeMB | integer | Disk size for the sandbox in MiB |
| metadata | any | Your own string key/value pairs stored with the sandbox; usable as a filter in listSandboxes. |
| state | string | State of the sandbox |
| network | object | Network policy of the sandbox: public access, egress allow and deny lists and proxy. |
| network.allowPublicTraffic | boolean | Specify if the sandbox URLs should be accessible only with authentication. |
| network.allowOut | array&lt;string&gt; | List of allowed destinations for egress traffic. Each entry can be a CIDR block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com", "*.example.com"). Allowed entries always take precedence over denied entries. |
| network.denyOut | array&lt;string&gt; | List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules. |
| network.egressProxy | object | SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through the proxy after allow/deny filtering; the sandbox is unaware. Domain-matched flows use remote DNS (ATYP=domain). |
| network.maskRequestHost | string | Specify host mask which will be used for all sandbox requests |
| network.httpsPorts | array&lt;integer&gt; | Unlike E2B, network.httpsPorts is rejected; omit it and serve plaintext HTTP inside the sandbox. The public port URL still uses HTTPS. The upstream field denotes HTTPS-speaking internal ports, permits self-signed certificates and excludes envd port 49983. |
| network.rules | object | Per-domain transform rules applied to matching outbound HTTPS requests. Keys may be exact DNS names (for example, "api.example.com") or a leading wildcard (for example, "*.example.com"), and are normalized to lowercase on write. Wildcards match subdomains at any depth but not the apex domain; a bare "*" is invalid. Exact rules take precedence, followed by the longest matching wildcard suffix, and matching rule sets are not merged. Broad wildcards such as "*.com" are allowed and may expose transformed credentials to every matching destination the sandbox contacts. Rules do not grant network access; configure allowOut separately to permit the destination.  |
| lifecycle | object | Sandbox lifecycle policy returned by sandbox info. |
| lifecycle.autoResume | boolean | Whether the sandbox can auto-resume. |
| lifecycle.onTimeout | string | Action taken when the sandbox times out. |
| volumeMounts | array&lt;object&gt; | Volumes mounted into the sandbox. |
| volumeMounts[].name | string | Name of the volume |
| volumeMounts[].path | string | Path of the volume |

# 重命名沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Updated sandbox detail

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| alias | string | Alias of the template |
| sandboxID | string | Identifier of the sandbox |
| clientID | string | Identifier of the client |
| startedAt | string | Time when the sandbox was started |
| endAt | string | Time when the sandbox will expire |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| allowInternetAccess | boolean | Whether internet access was explicitly enabled or disabled for the sandbox. Null means it was not explicitly set. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |
| cpuCount | integer | CPU cores for the sandbox |
| memoryMB | integer | Memory for the sandbox in MiB |
| diskSizeMB | integer | Disk size for the sandbox in MiB |
| metadata | any | Your own string key/value pairs stored with the sandbox; usable as a filter in listSandboxes. |
| state | string | State of the sandbox |
| network | object | Network policy of the sandbox: public access, egress allow and deny lists and proxy. |
| network.allowPublicTraffic | boolean | Specify if the sandbox URLs should be accessible only with authentication. |
| network.allowOut | array&lt;string&gt; | List of allowed destinations for egress traffic. Each entry can be a CIDR block (e.g. "8.8.8.8/32"), a bare IP address (e.g. "8.8.8.8"), or a domain name (e.g. "example.com", "*.example.com"). Allowed entries always take precedence over denied entries. |
| network.denyOut | array&lt;string&gt; | List of denied CIDR blocks or IP addresses for egress traffic. Domain names are not supported for deny rules. |
| network.egressProxy | object | SOCKS5 proxy for sandbox egress. Outbound TCP is tunneled through the proxy after allow/deny filtering; the sandbox is unaware. Domain-matched flows use remote DNS (ATYP=domain). |
| network.maskRequestHost | string | Specify host mask which will be used for all sandbox requests |
| network.httpsPorts | array&lt;integer&gt; | Unlike E2B, network.httpsPorts is rejected; omit it and serve plaintext HTTP inside the sandbox. The public port URL still uses HTTPS. The upstream field denotes HTTPS-speaking internal ports, permits self-signed certificates and excludes envd port 49983. |
| network.rules | object | Per-domain transform rules applied to matching outbound HTTPS requests. Keys may be exact DNS names (for example, "api.example.com") or a leading wildcard (for example, "*.example.com"), and are normalized to lowercase on write. Wildcards match subdomains at any depth but not the apex domain; a bare "*" is invalid. Exact rules take precedence, followed by the longest matching wildcard suffix, and matching rule sets are not merged. Broad wildcards such as "*.com" are allowed and may expose transformed credentials to every matching destination the sandbox contacts. Rules do not grant network access; configure allowOut separately to permit the destination.  |
| lifecycle | object | Sandbox lifecycle policy returned by sandbox info. |
| lifecycle.autoResume | boolean | Whether the sandbox can auto-resume. |
| lifecycle.onTimeout | string | Action taken when the sandbox times out. |
| volumeMounts | array&lt;object&gt; | Volumes mounted into the sandbox. |
| volumeMounts[].name | string | Name of the volume |
| volumeMounts[].path | string | Path of the volume |
| name | string | Current name of the sandbox. |

# 沙箱指标

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned the sandbox metrics

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].timestamp | string | Timestamp of the metric entry |
| [].timestampUnix | integer | Timestamp of the metric entry in Unix time (seconds since epoch) |
| [].cpuCount | integer | Number of CPU cores |
| [].cpuUsedPct | number | CPU usage percentage |
| [].memUsed | integer | Memory used in bytes |
| [].memTotal | integer | Total memory in bytes |
| [].memCache | integer | Cached memory (page cache) in bytes |
| [].diskUsed | integer | Disk used in bytes |
| [].diskTotal | integer | Total disk space in bytes |

# 设置超时

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 204 [#http-204]

Successfully set the sandbox timeout

未声明响应体。

# 暂停沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 204 [#http-204]

The sandbox was paused successfully and can be resumed

未声明响应体。

# 连接沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

The sandbox was already running

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

### HTTP 201 [#http-201]

The sandbox was resumed successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| templateID | string | Identifier of the template from which is the sandbox created |
| sandboxID | string | Identifier of the sandbox |
| alias | string | Alias of the template |
| clientID | string | Identifier of the client |
| envdVersion | string | Version of the envd running in the sandbox |
| envdAccessToken | string | Access token used for envd communication |
| trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |

# 终止沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 204 [#http-204]

The sandbox was killed successfully

未声明响应体。

# 列出模板

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned all templates

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].templateID | string | Identifier of the template |
| [].buildID | string | Identifier of the last successful build for given template |
| [].cpuCount | integer | CPU cores for the sandbox |
| [].memoryMB | integer | Memory for the sandbox in MiB |
| [].diskSizeMB | integer | Disk size for the sandbox in MiB |
| [].public | boolean | Whether the template is public or only accessible by the team |
| [].aliases | array&lt;string&gt; | Aliases of the template |
| [].names | array&lt;string&gt; | Names of the template (namespace/alias format when namespaced) |
| [].createdAt | string | Time when the template was created |
| [].updatedAt | string | Time when the template was last updated |
| [].createdBy | object | User who created the template; null for templates created by the platform. |
| [].createdBy.id | string | Identifier of the user |
| [].createdBy.email | string | Email of the user |
| [].lastSpawnedAt | string | Time when the template was last used |
| [].spawnCount | integer | Number of times the template was used |
| [].buildCount | integer | Number of times the template was built |
| [].envdVersion | string | Version of the envd running in the sandbox |
| [].buildStatus | string | Status of the template build |

# 创建卷

## 响应 [#响应]

### HTTP 201 [#http-201]

Successfully created a new team volume

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| volumeID | string | ID of the volume |
| name | string | Name of the volume |
| token | string | Auth token to use for interacting with volume content |
| domain | string | Domain to use as the destination for volume content requests, replacing the default &#96;api.&lt;E2B_DOMAIN&gt;&#96;. Only returned when the team is connected to a custom (BYOC) cluster; absent otherwise, in which case the default domain is used.  |

自有入口在响应对象（列表为每行）追加 `createdAt`：创建时间，ISO 8601 UTC 字符串。

网关自动设置 `X-Praxis-Face: own-v1`，客户端无需传入；`/e2b` 兼容入口会剥除该头，保留厂商响应形状。

# 列出卷

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully listed all team volumes

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].volumeID | string | ID of the volume |
| [].name | string | Name of the volume |

自有入口在响应对象（列表为每行）追加 `createdAt`：创建时间，ISO 8601 UTC 字符串。

网关自动设置 `X-Praxis-Face: own-v1`，客户端无需传入；`/e2b` 兼容入口会剥除该头，保留厂商响应形状。

# 读取卷

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully retrieved a team volume

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| volumeID | string | ID of the volume |
| name | string | Name of the volume |
| token | string | Auth token to use for interacting with volume content |
| domain | string | Domain to use as the destination for volume content requests, replacing the default &#96;api.&lt;E2B_DOMAIN&gt;&#96;. Only returned when the team is connected to a custom (BYOC) cluster; absent otherwise, in which case the default domain is used.  |

自有入口在响应对象（列表为每行）追加 `createdAt`：创建时间，ISO 8601 UTC 字符串。

网关自动设置 `X-Praxis-Face: own-v1`，客户端无需传入；`/e2b` 兼容入口会剥除该头，保留厂商响应形状。

# 删除卷

## 响应 [#响应]

### HTTP 204 [#http-204]

Successfully deleted a team volume

未声明响应体。

# 复制沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 201 [#http-201]

The sandbox was snapshotted and the forks were attempted; each entry reports one fork's outcome

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].sandbox | object | Sandbox created from a template. |
| [].sandbox.templateID | string | Identifier of the template from which is the sandbox created |
| [].sandbox.sandboxID | string | Identifier of the sandbox |
| [].sandbox.alias | string | Alias of the template |
| [].sandbox.clientID | string | Identifier of the client |
| [].sandbox.envdVersion | string | Version of the envd running in the sandbox |
| [].sandbox.envdAccessToken | string | Access token used for envd communication |
| [].sandbox.trafficAccessToken | string | Token required for accessing sandbox via proxy. |
| [].sandbox.domain | string | Domain returned for sandbox traffic. Build an HTTP service URL as https://&lt;port&gt;-&lt;sandboxID&gt;.&lt;domain&gt; using the returned values, without replacing or stripping the sandboxID suffix. |
| [].error | object | Error body: numeric code, machine-readable error_code and a message. |
| [].error.code | integer | Error code |
| [].error.error_code | string | Machine-readable semantic error code. Not a closed set; initial values: sandbox_capacity_unavailable, sandbox_placement_timeout, sandbox_no_compatible_node, sandbox_create_failed, internal_server_error. |
| [].error.message | string | Human-readable description of the error. |

# 创建快照

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 201 [#http-201]

Snapshot created successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| snapshotID | string | Identifier of the snapshot template including the tag. Uses namespace/alias when a name was provided (e.g. team-slug/my-snapshot:default), otherwise falls back to the raw template ID (e.g. abc123:default). |
| names | array&lt;string&gt; | Full names of the snapshot template including team namespace and tag (e.g. team-slug/my-snapshot:v2) |

自有入口在响应对象（列表为每行）追加 `createdAt`：创建时间，ISO 8601 UTC 字符串。

快照还包括 `sourceSandboxID`（string，来源沙箱公开 ID）与 `sourceSandboxName`（string 或 null）。名称无法取得时返回 null，界面可回退显示 ID。

网关自动设置 `X-Praxis-Face: own-v1`，客户端无需传入；`/e2b` 兼容入口会剥除该头，保留厂商响应形状。

向 `POST /sandbox/v1/sandboxes/{sandboxID}/snapshots` 发送 JSON body `{"name":"my-snapshot"}` 即可命名；名称会持久保存，并通过 `names` 返回。

# 列出快照

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned snapshots

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].snapshotID | string | Identifier of the snapshot template including the tag. Uses namespace/alias when a name was provided (e.g. team-slug/my-snapshot:default), otherwise falls back to the raw template ID (e.g. abc123:default). |
| [].names | array&lt;string&gt; | Full names of the snapshot template including team namespace and tag (e.g. team-slug/my-snapshot:v2) |

自有入口在响应对象（列表为每行）追加 `createdAt`：创建时间，ISO 8601 UTC 字符串。

快照还包括 `sourceSandboxID`（string，来源沙箱公开 ID）与 `sourceSandboxName`（string 或 null）。名称无法取得时返回 null，界面可回退显示 ID。

网关自动设置 `X-Praxis-Face: own-v1`，客户端无需传入；`/e2b` 兼容入口会剥除该头，保留厂商响应形状。

# 删除快照

## 响应 [#响应]

### HTTP 204 [#http-204]

The template was deleted successfully

未声明响应体。

# 更新网络策略

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 204 [#http-204]

Successfully updated the sandbox network configuration

未声明响应体。

# 读取沙箱日志

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Successfully returned the sandbox logs

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| logs | array&lt;object&gt; | Sandbox logs structured |
| logs[].timestamp | string | Timestamp of the log entry |
| logs[].message | string | Log message content |
| logs[].level | string | State of the sandbox |
| logs[].fields | object | Structured key/value fields attached to the log line. |

# 延长沙箱

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Authoritative extended deadline

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| endAt | string | New expiry time of the sandbox, UTC. |

# 列出进程

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Bounded observation with explicit completeness

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| processes | array&lt;object&gt; | Processes of the sandbox: running ones and retained observations of exited ones, newest first. |
| processes[].processId | string | Id of the process: &#96;obs-&lt;n&gt;&#96; for a process whose start was observed, &#96;live-&lt;pid&gt;&#96; for one that was only seen running. |
| processes[].pid | integer | Operating-system process id inside the sandbox. |
| processes[].tag | string | Tag the process was started with; absent when none. |
| processes[].config | object | Command the process was started with. |
| processes[].pty | boolean | Whether the process runs in a pseudo-terminal; present for observed processes. |
| processes[].startedAt | string | Time at which the process start was observed, UTC. |
| processes[].exitedAt | string | Time at which the process exit was observed, UTC; absent until an exit was witnessed. |
| processes[].exitCode | integer | Exit code; present only when the exit was witnessed. |
| processes[].state | string | Current state of the process. |
| processes[].observed | boolean | Whether the platform watched this process start. False for a process that was only seen running. |
| processes[].observationGap | boolean | True when observation was interrupted, so output or the exit may be missing; the state can then be unknown. |
| processes[].outputTruncated | boolean | True when old output chunks were dropped to stay within the retention limits. |

# 读取输出

先调用「创建沙箱」，用返回的 sandboxID 替换 sbx\_123。

## 响应 [#响应]

### HTTP 200 [#http-200]

Bounded observation with explicit completeness

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| chunks | array&lt;object&gt; | Retained output chunks of the process, oldest first. |
| chunks[].seq | integer | Sequence number of the chunk; it increases with time and orders chunks. |
| chunks[].stream | string | Which stream the chunk came from. |
| chunks[].data | string | Output bytes of the chunk, base64 encoded. |
| chunks[].timestamp | number | Time at which the chunk was recorded, in Unix milliseconds. |
| complete | boolean | True when the output is whole: the exit was witnessed, no gap occurred and nothing was truncated. |
| gap | boolean | True when observation was interrupted, so chunks or the exit may be missing. |
| truncated | boolean | True when old chunks were dropped to stay within the retention limits. |
| exitCode | integer &#124; null | Exit code of the process; null until an exit was witnessed. |

# 搜索 API

## 基础地址 [#基础地址]

## 接入 [#接入]

## 端点 [#端点]

| 方法   | 路径                                               | 说明     | 支持   |
| ---- | ------------------------------------------------ | ------ | ---- |
| POST | [`/v1/search`](/docs/api/native/search/search)   | 搜索     | ● 支持 |
| POST | [`/v1/extract`](/docs/api/native/search/extract) | 提取网页内容 | ● 支持 |
| POST | [`/v1/crawl`](/docs/api/native/search/crawl)     | 站内爬取   | ● 支持 |
| POST | [`/v1/map`](/docs/api/native/search/map)         | 站点地图   | ● 支持 |

## 与官方的差异 [#与官方的差异]

* <a href="/docs/api/native/search/crawl">站内爬取</a>：调用前要求账户余额大于 0；按本次调用实际消耗的 credits 计费，每 credit $0.01；上游未返回用量时，按本次请求可能消耗的上限计费。
* <a href="/docs/api/native/search/map">站点地图</a>：调用前要求账户余额大于 0；按本次调用实际消耗的 credits 计费，每 credit $0.01；上游未返回用量时，按本次请求可能消耗的上限计费。

参数与字段的权威定义以 [Tavily 官方文档](https://docs.tavily.com/documentation/api-reference)为准。

错误按 Tavily 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 搜索

## 响应 [#响应]

### HTTP 200 [#http-200]

Search results returned successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| query | string | The search query that was executed. |
| answer | string | A short answer to the user's query, generated by an LLM. Included in the response only if &#96;include_answer&#96; is requested (i.e., set to &#96;true&#96;, &#96;basic&#96;, or &#96;advanced&#96;) |
| images | array&lt;object&gt; | A list of query-related images from image search. If &#96;include_image_descriptions&#96; is true, each item will have &#96;url&#96; and &#96;description&#96;. Note: per-result images are also returned inside each result object's &#96;images&#96; field. |
| images[].url | string | URL of the image. |
| images[].description | string | Description of the image, when the search was asked to describe images. |
| results | array&lt;object&gt; | A list of sorted search results, ranked by relevancy. |
| results[].title | string | The title of the search result. |
| results[].url | string | The URL of the search result. |
| results[].content | string | A short description of the search result. |
| results[].score | number | The relevance score of the search result. |
| results[].raw_content | string | The cleaned and parsed HTML content of the search result. Only if &#96;include_raw_content&#96; is true. |
| results[].published_date | string | Tavily's best estimate of when the source was published or last updated. Can be later than the original publish date. &#96;null&#96; if no date could be detected. Only returned when &#96;include_published_date&#96; is &#96;true&#96; (automatically enabled when &#96;topic&#96; is &#96;news&#96;). |
| results[].favicon | string | The favicon URL for the result. |
| results[].images | array&lt;object&gt; | A list of images extracted from this search result. Only included when &#96;include_images&#96; is &#96;true&#96;. If &#96;include_image_descriptions&#96; is &#96;true&#96;, each item will have &#96;url&#96; and &#96;description&#96;. |
| results[].id | string | Unique identifier for this result |
| auto_parameters | object | A dictionary of the selected auto_parameters, only shown when &#96;auto_parameters&#96; is true. |
| response_time | number | Time in seconds it took to complete the request. |
| usage | object | Credit usage details for the request. |
| request_id | string | A unique request identifier you can share with customer support to help resolve issues with specific requests. |

# 提取网页内容

## 响应 [#响应]

### HTTP 200 [#http-200]

Extraction completed. Check results and failed\_results for each URL. HTTP 200 can have an empty results array when all valid URLs fail during extraction; output order is not guaranteed.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| results | array&lt;object&gt; | A list of extracted content from the provided URLs. |
| results[].url | string | The URL from which the content was extracted. |
| results[].raw_content | string | The full content extracted from the page. When &#96;query&#96; is provided, contains the top-ranked chunks joined by &#96;[...]&#96; separator. |
| results[].images | array&lt;string&gt; | This is only available if &#96;include_images&#96; is set to &#96;true&#96;. A list of image URLs extracted from the page. |
| results[].favicon | string | The favicon URL for the result. |
| failed_results | array&lt;object&gt; | A list of URLs that could not be processed. |
| failed_results[].url | string | The URL that failed to be processed. |
| failed_results[].error | string | An error message describing why the URL couldn't be processed. |
| response_time | number | Time in seconds it took to complete the request. |
| usage | object | Credit usage details for the request. |
| request_id | string | A unique request identifier you can share with customer support to help resolve issues with specific requests. |

# 站内爬取

## 响应 [#响应]

### HTTP 200 [#http-200]

Crawl results returned successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| base_url | string | The base URL that was crawled. |
| results | array&lt;object&gt; | A list of extracted content from the crawled URLs. |
| results[].url | string | The URL that was crawled. |
| results[].raw_content | string | The full content extracted from the page. When &#96;query&#96; is provided, contains the top-ranked chunks joined by &#96;[...]&#96; separator. |
| results[].favicon | string | The favicon URL for the result. |
| response_time | number | Time in seconds it took to complete the request. |
| usage | object | Credit usage details for the request. |
| request_id | string | A unique request identifier you can share with customer support to help resolve issues with specific requests. |

# 站点地图

## 响应 [#响应]

### HTTP 200 [#http-200]

Map results returned successfully

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| base_url | string | The base URL that was mapped. |
| results | array&lt;string&gt; | A list of URLs that were discovered during the mapping. |
| response_time | number | Time in seconds it took to complete the request. |
| usage | object | Credit usage details for the request. |
| request_id | string | A unique request identifier you can share with customer support to help resolve issues with specific requests. |

# 自动化 API

（待译）

Praxis Automation runs TypeScript scripts and YAML workflows with reusable Actions, triggers and inspectable run results. This is a Praxis-native API. Differences: choose your own namespace without registration, while praxis is read-only; Actions use ns/name at their current revision, while published scripts and workflows use ns/name\@version or @tag; drafts can run directly as source without publishing; schedule and webhook triggers require a published target. Start with `praxis.automation.runs.create` to test source or execute a published target.

管理动作、发布脚本与工作流、查看运行并接收入站 webhook。

`https://api.deepraxis.ai/automation/v1`

## 鉴权 [#鉴权]

使用 `Authorization: Bearer $PRAXIS_API_KEY`。入站 webhook 使用创建或轮换时返回的 secret URL，无需 API Key。

## TypeScript SDK [#typescript-sdk]

SDK 尚未发布到 npm。从本地源码安装，再用 Bun 运行示例；将命令中的路径替换为本地 SDK 目录。

```bash
bun add /absolute/path/to/packages/sdk/typescript
bun example.ts
```

示例使用 develop。curl 请求体带变量时需安装 jq。资源示例名称以 `sample-` 开头；创建前换成尚未占用的名称。动作、脚本和工作流使用 `docs-samples` 命名空间，完成后归档；触发器完成后删除。

## 动作 [#动作]

- [列出动作](/docs/api/native/automation/listActions)
- [创建动作](/docs/api/native/automation/createAction)
- [读取动作](/docs/api/native/automation/getAction)
- [更新动作](/docs/api/native/automation/updateAction)
- [列出动作修订](/docs/api/native/automation/listActionRevisions)
- [读取动作修订](/docs/api/native/automation/getActionRevision)
- [回滚动作](/docs/api/native/automation/rollbackAction)
- [列出动作调用](/docs/api/native/automation/listActionInvocations)
- [列出动作引用方](/docs/api/native/automation/listActionDependents)
- [归档动作](/docs/api/native/automation/archiveAction)
- [恢复动作](/docs/api/native/automation/restoreAction)

## 脚本 [#脚本]

- [列出脚本](/docs/api/native/automation/listScripts)
- [创建脚本](/docs/api/native/automation/createScript)
- [读取脚本](/docs/api/native/automation/getScript)
- [更新脚本草稿](/docs/api/native/automation/updateScript)
- [归档脚本](/docs/api/native/automation/archiveScript)
- [恢复脚本](/docs/api/native/automation/restoreScript)
- [发布脚本版本](/docs/api/native/automation/publishScriptVersion)
- [列出脚本版本](/docs/api/native/automation/listScriptVersions)
- [读取脚本版本](/docs/api/native/automation/getScriptVersion)
- [弃用脚本版本](/docs/api/native/automation/deprecateScriptVersion)
- [列出脚本标签](/docs/api/native/automation/listScriptTags)
- [设置脚本标签](/docs/api/native/automation/setScriptTag)
- [删除脚本标签](/docs/api/native/automation/deleteScriptTag)

## 工作流 [#工作流]

- [列出工作流](/docs/api/native/automation/listWorkflows)
- [创建工作流](/docs/api/native/automation/createWorkflow)
- [读取工作流](/docs/api/native/automation/getWorkflow)
- [更新工作流草稿](/docs/api/native/automation/updateWorkflow)
- [归档工作流](/docs/api/native/automation/archiveWorkflow)
- [恢复工作流](/docs/api/native/automation/restoreWorkflow)
- [发布工作流版本](/docs/api/native/automation/publishWorkflowVersion)
- [列出工作流版本](/docs/api/native/automation/listWorkflowVersions)
- [读取工作流版本](/docs/api/native/automation/getWorkflowVersion)
- [弃用工作流版本](/docs/api/native/automation/deprecateWorkflowVersion)
- [列出工作流标签](/docs/api/native/automation/listWorkflowTags)
- [设置工作流标签](/docs/api/native/automation/setWorkflowTag)
- [删除工作流标签](/docs/api/native/automation/deleteWorkflowTag)

## 定义工具 [#定义工具]

- [校验定义](/docs/api/native/automation/validateDefinition)
- [解析运行目标](/docs/api/native/automation/resolveTarget)
- [搜索自动化定义](/docs/api/native/automation/searchTargets)

## 运行 [#运行]

- [创建运行](/docs/api/native/automation/createRun)
- [列出运行](/docs/api/native/automation/listRuns)
- [读取运行](/docs/api/native/automation/getRun)
- [取消运行](/docs/api/native/automation/cancelRun)
- [重新运行](/docs/api/native/automation/rerunRun)
- [暂停运行](/docs/api/native/automation/suspendRun)
- [恢复运行](/docs/api/native/automation/resumeRun)
- [列出等待点](/docs/api/native/automation/listRunWaits)
- [列出运行调用](/docs/api/native/automation/listRunCalls)
- [列出运行产物](/docs/api/native/automation/listRunArtifacts)
- [完成等待点](/docs/api/native/automation/completeRunWait)
- [列出运行步骤](/docs/api/native/automation/listRunTasks)
- [读取运行事件](/docs/api/native/automation/listRunEvents)
- [读取运行日志](/docs/api/native/automation/listRunLogs)
- [读取运行源码](/docs/api/native/automation/getRunSource)

## 触发器与入站 webhook [#触发器与入站-webhook]

- [列出触发器](/docs/api/native/automation/listTriggers)
- [创建触发器](/docs/api/native/automation/createTrigger)
- [读取触发器](/docs/api/native/automation/getTrigger)
- [更新触发器](/docs/api/native/automation/updateTrigger)
- [删除触发器](/docs/api/native/automation/deleteTrigger)
- [暂停触发器](/docs/api/native/automation/pauseTrigger)
- [恢复触发器](/docs/api/native/automation/resumeTrigger)
- [立即触发](/docs/api/native/automation/fireTrigger)
- [轮换回调地址](/docs/api/native/automation/rotateTriggerWebhook)
- [列出触发历史](/docs/api/native/automation/listTriggerFirings)
- [预览触发时间](/docs/api/native/automation/previewTriggerSchedule)
- [接收入站回调](/docs/api/native/automation/receiveWebhook)

# 列出动作

筛选可见动作并读取修订摘要。可按名称或说明筛选，包含近七天统计；不含实现源码，默认排除已归档动作。

`GET /automation/v1/actions`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 20。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: q | `string` | 可选；不区分大小写，按名称或说明的字面子串匹配；% 与 _ 无通配含义。 |
| query: namespace | `string[]` | 可选；仅返回指定命名空间的定义，名称按小写匹配。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: scope | `"platform"` / `"own"[]` | 可选；platform 仅平台定义，own 仅租户自建定义；省略返回两者。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: archived | `boolean` | 可选；true 仅已归档，false 仅未归档；默认 false。 |
| query: implementation | `"code"` / `"container"` / `"shell"[]` | 可选；按实现类型筛选：code、container 或 shell；省略不过滤。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: labels | `object` | 可选；按标签过滤，使用 labels[k]=v；同键逗号多值取任一，不同键同时满足。 |
| query: created_at[gte] | `string` | 可选；创建时间下界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |
| query: created_at[lte] | `string` | 可选；创建时间上界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/actions" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  --get \
  --data-urlencode "namespace=docs-samples" \
  --data-urlencode "limit=1"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.list({
  "query": {
    "namespace": [
      "docs-samples"
    ],
    "limit": 1
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的动作（含当前修订摘要与近七天统计），按 created_at 倒序、id 倒序排列。 |
| data[].id | `string` | 必填 / 必有；动作 ID，前缀 act_；日常调用使用 namespace 与 name，而不是 id。 |
| data[].namespace | `string` | 必填 / 必有；动作命名空间；平台动作为 praxis，裸名引用解析到 praxis。 |
| data[].name | `string` | 必填 / 必有；动作名，与 namespace 一起唯一标识动作；小写字母、数字、点、下划线、连字符，最长 64 字符。 |
| data[].description | `string` | 必填 / 必有；动作说明，最多 1000 字符。 |
| data[].labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| data[].owner | `string` | 必填 / 必有；动作所属租户，由网关注入；按不透明字符串处理。 |
| data[].builtin | `boolean` | 必填 / 必有；true 表示平台内置动作（命名空间 praxis）；用户创建的动作为 false。 |
| data[].stats_7d | `object` | 必填 / 必有；近七天统计；平台动作按调用方租户隔离，只反映当前调用方的调用，不是平台全局统计。 不接受额外字段。 |
| data[].stats_7d.calls | `number` | 必填 / 必有；近七天内对该动作的调用次数，按小时汇总。 |
| data[].stats_7d.failures | `number` | 必填 / 必有；近七天内失败的调用次数。 |
| data[].stats_7d.p50_ms | `null` / `number` | 必填 / 必有；耗时中位数的近似上界，单位毫秒；正耗时向上归入 2 的幂分桶（9 ms → 16 ms），0 独立一桶；无有效耗时样本时为 null。 |
| data[].dependents | `object` | 必填 / 必有；引用该动作的脚本与工作流数量，口径为最新版本加草稿。 不接受额外字段。 |
| data[].dependents.scripts | `number` | 必填 / 必有；引用该动作的脚本数量。 |
| data[].dependents.workflows | `number` | 必填 / 必有；引用该动作的工作流数量。 |
| data[].archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不能复用。 |
| data[].created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| data[].updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |
| data[].current_revision | `object` | 必填 / 必有；列表使用的修订摘要：只含契约与运行位置，不含实现源码。 不接受额外字段。 |
| data[].current_revision.id | `string` | 必填 / 必有；修订 ID，前缀 actr_。 |
| data[].current_revision.implementation | `object` | 必填 / 必有；动作列表只返回 &#123;kind, host&#125;，不含源码；动作详情返回完整 implementation。 不接受额外字段。 |
| data[].current_revision.implementation.kind | `"code"` / `"container"` / `"shell"` | 必填 / 必有；动作实现方式。code 为源码实现（目前仅 language=ts 可用）；container 为容器镜像加命令，暂未开放；shell 为 shell 脚本，暂未开放。 |
| data[].current_revision.implementation.host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| data[].current_revision.host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| data[].current_revision.input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| data[].current_revision.input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| data[].current_revision.input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].current_revision.output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| data[].current_revision.output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| data[].current_revision.output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].current_revision.created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "act_00mv67loz4fe4f27bdf89346c885b3a28b2038c091",
      "owner": "tnt_3a9759864ccb4e00",
      "namespace": "docs-samples",
      "name": "sample-action-1791867412840-b05e8a",
      "description": "",
      "labels": {},
      "builtin": false,
      "archived_at": null,
      "created_at": "2026-10-13T04:57:09.039Z",
      "updated_at": "2026-10-13T04:57:09.039Z",
      "current_revision": {
        "id": "actr_00mv67loz3e46938b8ecf54e57b8f31297df016a1c",
        "implementation": {
          "kind": "code",
          "host": "isolate"
        },
        "host": "isolate",
        "input_schema": {
          "type": "object",
          "properties": {
            "n": {
              "type": "number"
            }
          },
          "required": [
            "n"
          ],
          "additionalProperties": false
        },
        "output_schema": {
          "type": "object",
          "properties": {
            "answer": {
              "type": "number"
            }
          },
          "required": [
            "answer"
          ],
          "additionalProperties": false
        },
        "created_at": "2026-10-13T04:57:09.039Z"
      },
      "stats_7d": {
        "calls": 0,
        "failures": 0,
        "p50_ms": null
      },
      "dependents": {
        "scripts": 0,
        "workflows": 0
      }
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 创建动作

创建动作定义和首个修订，名称折叠为小写；同租户重名返回 NAME_TAKEN，praxis 命名空间只读。

`POST /automation/v1/actions`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| namespace | `string` | 必填 / 必有；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 pattern: "^[a-zA-Z0-9][a-zA-Z0-9._-]&#123;0,63&#125;$" |
| name | `string` | 必填 / 必有；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 pattern: "^[a-zA-Z0-9][a-zA-Z0-9._-]&#123;0,63&#125;$" |
| description | `string` | 可选；说明，最多 1000 个字符。 maxLength: 1000 |
| input_schema | `object` | 必填 / 必有；输入 JSON Schema；更新时只能放宽已接受的输入。 |
| input_schema.*（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；输出 JSON Schema；更新时只能收紧输出约束。 |
| output_schema.*（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| errors | `object[]` | 可选；声明的错误类型与说明；更新时不能删除已有错误。 |
| errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| annotations | `object` | 可选；read_only 与 idempotent 为布尔值，缺省均为 false。 不接受额外字段。 |
| annotations.read_only | `boolean` | 可选；true 表示动作不修改外部状态，只读取数据。默认 false。 |
| annotations.idempotent | `boolean` | 可选；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。默认 false。 |
| timeout_ms | `number` | 可选；正整数毫秒；当前 code 默认且最多 30000，container/shell 暂未开放。 |
| implementation | `object` / `object` / `object` | 必填 / 必有；实现：code 使用 language=ts 与 source；container（image、command）和 shell（script）暂未开放，创建或更新时返回 OPERATION_NOT_SUPPORTED。 |
| implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码。 |
| implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放，返回 OPERATION_NOT_SUPPORTED）。 |
| implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放，返回 OPERATION_NOT_SUPPORTED）。 |
| implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| labels | `object` | 可选；最多 50 个标签；键为 1–40 个字符，值最多 500 个字符。 |
| message | `string` | 可选；本次修订的说明。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/actions" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "namespace": "docs-samples",
  "name": "sample-action",
  "input_schema": {
    "type": "object",
    "properties": {
      "n": {
        "type": "number"
      }
    },
    "required": [
      "n"
    ],
    "additionalProperties": false
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "answer": {
        "type": "number"
      }
    },
    "required": [
      "answer"
    ],
    "additionalProperties": false
  },
  "implementation": {
    "kind": "code",
    "language": "ts",
    "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
  }
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.create({
  "body": {
    "namespace": "docs-samples",
    "name": "sample-action",
    "input_schema": {
      "type": "object",
      "properties": {
        "n": {
          "type": "number"
        }
      },
      "required": [
        "n"
      ],
      "additionalProperties": false
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "number"
        }
      },
      "required": [
        "answer"
      ],
      "additionalProperties": false
    },
    "implementation": {
      "kind": "code",
      "language": "ts",
      "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
    }
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；动作 ID，前缀 act_；日常调用使用 namespace 与 name，而不是 id。 |
| namespace | `string` | 必填 / 必有；动作命名空间；平台动作为 praxis，裸名引用解析到 praxis。 |
| name | `string` | 必填 / 必有；动作名，与 namespace 一起唯一标识动作；小写字母、数字、点、下划线、连字符，最长 64 字符。 |
| description | `string` | 必填 / 必有；动作说明，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；动作所属租户，由网关注入；按不透明字符串处理。 |
| builtin | `boolean` | 必填 / 必有；true 表示平台内置动作（命名空间 praxis）；用户创建的动作为 false。 |
| current_revision | `object` | 必填 / 必有；动作的一个不可变修订：契约、实现和运行参数的快照。每次更新兼容的内容变化都会产生新修订。 不接受额外字段。 |
| current_revision.id | `string` | 必填 / 必有；修订 ID，前缀 actr_；仅用于展示与回滚（rollback 的 revision），不能被脚本直接引用。 |
| current_revision.digest | `string` | 必填 / 必有；契约与实现的内容摘要；内容相同的更新不会产生新修订。 |
| current_revision.input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.errors | `object[]` | 必填 / 必有；动作声明的可能错误列表，每项含 type、code、description。 |
| current_revision.errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| current_revision.errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| current_revision.errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| current_revision.annotations | `object` | 必填 / 必有；动作行为声明 &#123;read_only, idempotent&#125;；创建时未给出的键默认为 false。 不接受额外字段。 |
| current_revision.annotations.read_only | `boolean` | 必填 / 必有；true 表示动作不修改外部状态，只读取数据。 |
| current_revision.annotations.idempotent | `boolean` | 必填 / 必有；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。 |
| current_revision.timeout_ms | `number` | 必填 / 必有；单次执行的超时毫秒数；创建时未给出，code 实现默认 30000，容器或 shell 实现默认 600000。 |
| current_revision.implementation | `object` / `object` / `object` | 必填 / 必有；code 使用 language=ts 与 source。container 和 shell 暂未开放，创建时返回 OPERATION_NOT_SUPPORTED。 |
| current_revision.implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| current_revision.implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| current_revision.implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码；内置动作为空。 |
| current_revision.implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放）。 |
| current_revision.implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| current_revision.implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| current_revision.implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放）。 |
| current_revision.implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| current_revision.host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| current_revision.platform_apis | `string[]` | 必填 / 必有；从代码推导出的平台 API 集合，同时是该动作运行令牌的权限范围（最小权限）。 |
| current_revision.created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| current_revision.created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| current_revision.created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| current_revision.message | `null` / `string` | 必填 / 必有；创建该修订时附带的说明；未提供为 null。 |
| current_revision.created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |
| stats_7d | `object` | 必填 / 必有；近七天统计；平台动作按调用方租户隔离，只反映当前调用方的调用，不是平台全局统计。 不接受额外字段。 |
| stats_7d.calls | `number` | 必填 / 必有；近七天内对该动作的调用次数，按小时汇总。 |
| stats_7d.failures | `number` | 必填 / 必有；近七天内失败的调用次数。 |
| stats_7d.p50_ms | `null` / `number` | 必填 / 必有；耗时中位数的近似上界，单位毫秒；正耗时向上归入 2 的幂分桶（9 ms → 16 ms），0 独立一桶；无有效耗时样本时为 null。 |
| dependents | `object` | 必填 / 必有；引用该动作的脚本与工作流数量，口径为最新版本加草稿。 不接受额外字段。 |
| dependents.scripts | `number` | 必填 / 必有；引用该动作的脚本数量。 |
| dependents.workflows | `number` | 必填 / 必有；引用该动作的工作流数量。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不能复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "act_00mv67loz4fe4f27bdf89346c885b3a28b2038c091",
  "owner": "tnt_3a9759864ccb4e00",
  "namespace": "docs-samples",
  "name": "sample-action-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "builtin": false,
  "current_revision": {
    "input_schema": {
      "type": "object",
      "properties": {
        "n": {
          "type": "number"
        }
      },
      "required": [
        "n"
      ],
      "additionalProperties": false
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "number"
        }
      },
      "required": [
        "answer"
      ],
      "additionalProperties": false
    },
    "errors": [],
    "annotations": {
      "read_only": false,
      "idempotent": false
    },
    "timeout_ms": 30000,
    "implementation": {
      "kind": "code",
      "language": "ts",
      "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
    },
    "host": "isolate",
    "platform_apis": [],
    "id": "actr_00mv67loz3e46938b8ecf54e57b8f31297df016a1c",
    "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
    "created_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    },
    "message": null,
    "created_at": "2026-10-13T04:57:09.039Z"
  },
  "stats_7d": {
    "calls": 0,
    "failures": 0,
    "p50_ms": null
  },
  "dependents": {
    "scripts": 0,
    "workflows": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:09.039Z",
  "updated_at": "2026-10-13T04:57:09.039Z"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 NAME_TAKEN：名称已被同一租户占用。 |
| 413 | PAYLOAD_TOO_LARGE：请求内容超过本操作允许的大小。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取动作

读取动作及当前修订的完整实现；响应 ETag 是当前修订 ID，可用于更新时的 If-Match。

`GET /automation/v1/actions/{ns}/{name}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.retrieve({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| ETag | `string` | Current resource revision for conditional updates. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；动作 ID，前缀 act_；日常调用使用 namespace 与 name，而不是 id。 |
| namespace | `string` | 必填 / 必有；动作命名空间；平台动作为 praxis，裸名引用解析到 praxis。 |
| name | `string` | 必填 / 必有；动作名，与 namespace 一起唯一标识动作；小写字母、数字、点、下划线、连字符，最长 64 字符。 |
| description | `string` | 必填 / 必有；动作说明，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；动作所属租户，由网关注入；按不透明字符串处理。 |
| builtin | `boolean` | 必填 / 必有；true 表示平台内置动作（命名空间 praxis）；用户创建的动作为 false。 |
| current_revision | `object` | 必填 / 必有；动作的一个不可变修订：契约、实现和运行参数的快照。每次更新兼容的内容变化都会产生新修订。 不接受额外字段。 |
| current_revision.id | `string` | 必填 / 必有；修订 ID，前缀 actr_；仅用于展示与回滚（rollback 的 revision），不能被脚本直接引用。 |
| current_revision.digest | `string` | 必填 / 必有；契约与实现的内容摘要；内容相同的更新不会产生新修订。 |
| current_revision.input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.errors | `object[]` | 必填 / 必有；动作声明的可能错误列表，每项含 type、code、description。 |
| current_revision.errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| current_revision.errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| current_revision.errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| current_revision.annotations | `object` | 必填 / 必有；动作行为声明 &#123;read_only, idempotent&#125;；创建时未给出的键默认为 false。 不接受额外字段。 |
| current_revision.annotations.read_only | `boolean` | 必填 / 必有；true 表示动作不修改外部状态，只读取数据。 |
| current_revision.annotations.idempotent | `boolean` | 必填 / 必有；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。 |
| current_revision.timeout_ms | `number` | 必填 / 必有；单次执行的超时毫秒数；创建时未给出，code 实现默认 30000，容器或 shell 实现默认 600000。 |
| current_revision.implementation | `object` / `object` / `object` | 必填 / 必有；code 使用 language=ts 与 source。container 和 shell 暂未开放，创建时返回 OPERATION_NOT_SUPPORTED。 |
| current_revision.implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| current_revision.implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| current_revision.implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码；内置动作为空。 |
| current_revision.implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放）。 |
| current_revision.implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| current_revision.implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| current_revision.implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放）。 |
| current_revision.implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| current_revision.host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| current_revision.platform_apis | `string[]` | 必填 / 必有；从代码推导出的平台 API 集合，同时是该动作运行令牌的权限范围（最小权限）。 |
| current_revision.created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| current_revision.created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| current_revision.created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| current_revision.message | `null` / `string` | 必填 / 必有；创建该修订时附带的说明；未提供为 null。 |
| current_revision.created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |
| stats_7d | `object` | 必填 / 必有；近七天统计；平台动作按调用方租户隔离，只反映当前调用方的调用，不是平台全局统计。 不接受额外字段。 |
| stats_7d.calls | `number` | 必填 / 必有；近七天内对该动作的调用次数，按小时汇总。 |
| stats_7d.failures | `number` | 必填 / 必有；近七天内失败的调用次数。 |
| stats_7d.p50_ms | `null` / `number` | 必填 / 必有；耗时中位数的近似上界，单位毫秒；正耗时向上归入 2 的幂分桶（9 ms → 16 ms），0 独立一桶；无有效耗时样本时为 null。 |
| dependents | `object` | 必填 / 必有；引用该动作的脚本与工作流数量，口径为最新版本加草稿。 不接受额外字段。 |
| dependents.scripts | `number` | 必填 / 必有；引用该动作的脚本数量。 |
| dependents.workflows | `number` | 必填 / 必有；引用该动作的工作流数量。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不能复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "act_00mv67loz4fe4f27bdf89346c885b3a28b2038c091",
  "owner": "tnt_3a9759864ccb4e00",
  "namespace": "docs-samples",
  "name": "sample-action-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "builtin": false,
  "archived_at": null,
  "created_at": "2026-10-13T04:57:09.039Z",
  "updated_at": "2026-10-13T04:57:09.039Z",
  "current_revision": {
    "id": "actr_00mv67loz3e46938b8ecf54e57b8f31297df016a1c",
    "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
    "input_schema": {
      "type": "object",
      "properties": {
        "n": {
          "type": "number"
        }
      },
      "required": [
        "n"
      ],
      "additionalProperties": false
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "number"
        }
      },
      "required": [
        "answer"
      ],
      "additionalProperties": false
    },
    "errors": [],
    "annotations": {
      "read_only": false,
      "idempotent": false
    },
    "timeout_ms": 30000,
    "implementation": {
      "kind": "code",
      "language": "ts",
      "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
    },
    "host": "isolate",
    "platform_apis": [],
    "created_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    },
    "message": null,
    "created_at": "2026-10-13T04:57:09.039Z"
  },
  "stats_7d": {
    "calls": 0,
    "failures": 0,
    "p50_ms": null
  },
  "dependents": {
    "scripts": 0,
    "workflows": 0
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 更新动作

检查当前和最近五个历史修订的兼容性后更新。输入放宽、输出收紧为兼容，包括长度、条目数、属性数、type（integer/number）与 multipleOf（输入新因子可整除旧因子，输出相反）。dry_run=true 仅返回 CompatResult，可不带 If-Match；带了仍校验，* 匹配任何当前存在的表示。正常更新必须带 If-Match，返回 ActionDef 与 ETag；预检不返回 ETag。省略的可选字段保持原值仅适用于 description、labels；errors 默认 []，annotations 未提供的键默认 false，timeout_ms 默认 30000，message 默认 null。 正常更新不兼容时返回 422 SCHEMA_INCOMPATIBLE 与 issues；内容未变则保留现有修订。

`PUT /automation/v1/actions/{ns}/{name}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| query: dry_run | `boolean` | 可选；true 仅检查兼容性，不落库，可省略 If-Match；省略或 false 正常更新。 |
| header: If-Match | `string` | 可选；正常更新必填；dry_run=true 可省略，提供时仍校验。* 匹配任何当前存在的表示；也可提供当前修订 ETag。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| description | `string` | 可选；说明，最多 1000 个字符。 maxLength: 1000 |
| labels | `object` | 可选；最多 50 个标签；键为 1–40 个字符，值最多 500 个字符。 |
| input_schema | `object` | 必填 / 必有；输入 JSON Schema；更新时只能放宽已接受的输入。 |
| input_schema.*（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；输出 JSON Schema；更新时只能收紧输出约束。 |
| output_schema.*（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| errors | `object[]` | 可选；声明的错误类型与说明；更新时不能删除已有错误。 |
| errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| annotations | `object` | 可选；read_only 与 idempotent 为布尔值，缺省均为 false。 不接受额外字段。 |
| annotations.read_only | `boolean` | 可选；true 表示动作不修改外部状态，只读取数据。默认 false。 |
| annotations.idempotent | `boolean` | 可选；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。默认 false。 |
| timeout_ms | `number` | 可选；正整数毫秒；当前 code 默认且最多 30000，container/shell 暂未开放。 |
| implementation | `object` / `object` / `object` | 必填 / 必有；实现：code 使用 language=ts 与 source；container（image、command）和 shell（script）暂未开放，创建或更新时返回 OPERATION_NOT_SUPPORTED。 |
| implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码。 |
| implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放，返回 OPERATION_NOT_SUPPORTED）。 |
| implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放，返回 OPERATION_NOT_SUPPORTED）。 |
| implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| message | `string` | 可选；本次修订的说明。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |
| ETAG | [最新 GET 响应头 ETag（保留引号）](/docs/api/native/automation/getAction) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
: "${ETAG:?Set ETAG}"
curl --fail-with-body -X PUT "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "If-Match: ${ETAG}" \
  -H "Content-Type: application/json" \
  --data '{
  "input_schema": {
    "type": "object",
    "properties": {
      "n": {
        "type": "number"
      }
    },
    "required": [
      "n"
    ],
    "additionalProperties": false
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "answer": {
        "type": "number"
      }
    },
    "required": [
      "answer"
    ],
    "additionalProperties": false
  },
  "implementation": {
    "kind": "code",
    "language": "ts",
    "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
  },
  "message": "Sample revision"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.update({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME")
  },
  "headers": {
    "If-Match": env("ETAG")
  },
  "body": {
    "input_schema": {
      "type": "object",
      "properties": {
        "n": {
          "type": "number"
        }
      },
      "required": [
        "n"
      ],
      "additionalProperties": false
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "number"
        }
      },
      "required": [
        "answer"
      ],
      "additionalProperties": false
    },
    "implementation": {
      "kind": "code",
      "language": "ts",
      "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
    },
    "message": "Sample revision"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| ETag | `string` | Current revision returned only for normal updates; absent for dry_run=true. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| （分支1).id | `string` | 必填 / 必有；动作 ID，前缀 act_；日常调用使用 namespace 与 name，而不是 id。 |
| （分支1).namespace | `string` | 必填 / 必有；动作命名空间；平台动作为 praxis，裸名引用解析到 praxis。 |
| （分支1).name | `string` | 必填 / 必有；动作名，与 namespace 一起唯一标识动作；小写字母、数字、点、下划线、连字符，最长 64 字符。 |
| （分支1).description | `string` | 必填 / 必有；动作说明，最多 1000 字符。 |
| （分支1).labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| （分支1).owner | `string` | 必填 / 必有；动作所属租户，由网关注入；按不透明字符串处理。 |
| （分支1).builtin | `boolean` | 必填 / 必有；true 表示平台内置动作（命名空间 praxis）；用户创建的动作为 false。 |
| （分支1).current_revision | `object` | 必填 / 必有；动作的一个不可变修订：契约、实现和运行参数的快照。每次更新兼容的内容变化都会产生新修订。 不接受额外字段。 |
| （分支1).current_revision.id | `string` | 必填 / 必有；修订 ID，前缀 actr_；仅用于展示与回滚（rollback 的 revision），不能被脚本直接引用。 |
| （分支1).current_revision.digest | `string` | 必填 / 必有；契约与实现的内容摘要；内容相同的更新不会产生新修订。 |
| （分支1).current_revision.input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| （分支1).current_revision.input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| （分支1).current_revision.input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).current_revision.output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| （分支1).current_revision.output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| （分支1).current_revision.output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).current_revision.errors | `object[]` | 必填 / 必有；动作声明的可能错误列表，每项含 type、code、description。 |
| （分支1).current_revision.errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| （分支1).current_revision.errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| （分支1).current_revision.errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| （分支1).current_revision.annotations | `object` | 必填 / 必有；动作行为声明 &#123;read_only, idempotent&#125;；创建时未给出的键默认为 false。 不接受额外字段。 |
| （分支1).current_revision.annotations.read_only | `boolean` | 必填 / 必有；true 表示动作不修改外部状态，只读取数据。 |
| （分支1).current_revision.annotations.idempotent | `boolean` | 必填 / 必有；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。 |
| （分支1).current_revision.timeout_ms | `number` | 必填 / 必有；单次执行的超时毫秒数；创建时未给出，code 实现默认 30000，容器或 shell 实现默认 600000。 |
| （分支1).current_revision.implementation | `object` / `object` / `object` | 必填 / 必有；code 使用 language=ts 与 source。container 和 shell 暂未开放，创建时返回 OPERATION_NOT_SUPPORTED。 |
| （分支1).current_revision.implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| （分支1).current_revision.implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| （分支1).current_revision.implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码；内置动作为空。 |
| （分支1).current_revision.implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放）。 |
| （分支1).current_revision.implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| （分支1).current_revision.implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| （分支1).current_revision.implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放）。 |
| （分支1).current_revision.implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| （分支1).current_revision.host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| （分支1).current_revision.platform_apis | `string[]` | 必填 / 必有；从代码推导出的平台 API 集合，同时是该动作运行令牌的权限范围（最小权限）。 |
| （分支1).current_revision.created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| （分支1).current_revision.created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| （分支1).current_revision.created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| （分支1).current_revision.message | `null` / `string` | 必填 / 必有；创建该修订时附带的说明；未提供为 null。 |
| （分支1).current_revision.created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |
| （分支1).stats_7d | `object` | 必填 / 必有；近七天统计；平台动作按调用方租户隔离，只反映当前调用方的调用，不是平台全局统计。 不接受额外字段。 |
| （分支1).stats_7d.calls | `number` | 必填 / 必有；近七天内对该动作的调用次数，按小时汇总。 |
| （分支1).stats_7d.failures | `number` | 必填 / 必有；近七天内失败的调用次数。 |
| （分支1).stats_7d.p50_ms | `null` / `number` | 必填 / 必有；耗时中位数的近似上界，单位毫秒；正耗时向上归入 2 的幂分桶（9 ms → 16 ms），0 独立一桶；无有效耗时样本时为 null。 |
| （分支1).dependents | `object` | 必填 / 必有；引用该动作的脚本与工作流数量，口径为最新版本加草稿。 不接受额外字段。 |
| （分支1).dependents.scripts | `number` | 必填 / 必有；引用该动作的脚本数量。 |
| （分支1).dependents.workflows | `number` | 必填 / 必有；引用该动作的工作流数量。 |
| （分支1).archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不能复用。 |
| （分支1).created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| （分支1).updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |
| （分支2)（分支1).compatible | `true` | 必填 / 必有；固定为 true：新契约与当前及最近五个历史修订兼容。 |
| （分支2)（分支2).compatible | `false` | 必填 / 必有；固定为 false：新契约至少在一处与历史修订不兼容。 |
| （分支2)（分支2).issues | `object[]` | 必填 / 必有；全部不兼容之处，每项含 pointer 与 reason。 |
| （分支2)（分支2).issues[].pointer | `string` | 必填 / 必有；不兼容位置的 JSON Pointer（RFC 6901），相对于动作的 input_schema 或 output_schema。 |
| （分支2)（分支2).issues[].reason | `string` | 必填 / 必有；该位置为何与历史修订不兼容（输入应放宽、输出应收紧）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "act_00mv67loz4fe4f27bdf89346c885b3a28b2038c091",
  "owner": "tnt_3a9759864ccb4e00",
  "namespace": "docs-samples",
  "name": "sample-action-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "builtin": false,
  "archived_at": null,
  "created_at": "2026-10-13T04:57:09.039Z",
  "updated_at": "2026-10-13T04:57:12.709Z",
  "current_revision": {
    "input_schema": {
      "type": "object",
      "properties": {
        "n": {
          "type": "number"
        }
      },
      "required": [
        "n"
      ],
      "additionalProperties": false
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "number"
        }
      },
      "required": [
        "answer"
      ],
      "additionalProperties": false
    },
    "errors": [],
    "annotations": {
      "read_only": false,
      "idempotent": false
    },
    "timeout_ms": 30000,
    "implementation": {
      "kind": "code",
      "language": "ts",
      "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
    },
    "host": "isolate",
    "platform_apis": [],
    "id": "actr_00mv67lrt1370820a9daaa4fd3882332e4899a4c9e",
    "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
    "created_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    },
    "message": "Sample revision",
    "created_at": "2026-10-13T04:57:12.709Z"
  },
  "stats_7d": {
    "calls": 0,
    "failures": 0,
    "p50_ms": null
  },
  "dependents": {
    "scripts": 0,
    "workflows": 0
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 413 | PAYLOAD_TOO_LARGE：请求内容超过本操作允许的大小。 |
| 422 | SCHEMA_INCOMPATIBLE：新动作契约与历史修订不兼容。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出动作修订

按创建时间倒序列出修订。结果包含当前标记及通过兼容门回滚的可行性和原因。 默认不带源码；仅 expand=source 带完整源码，其它值返回 400。详情接口保持全文。

`GET /automation/v1/actions/{ns}/{name}/revisions`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 20。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: expand | `"source"` | 可选；仅接受 source；默认不带源码，其它值返回 400。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}/revisions" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.revisions.list({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的动作修订（默认不含实现源码，expand=source 才带），按 created_at 倒序、id 倒序排列。 |
| data[].current | `boolean` | 必填 / 必有；true 表示这是动作当前生效的修订。 |
| data[].rollback | `object` | 必填 / 必有；回滚到该修订是否可行，由服务端对当前修订做兼容判定。 不接受额外字段。 |
| data[].rollback.allowed | `boolean` | 必填 / 必有；true 表示可以回滚到此修订；false 时 issues 说明原因。 |
| data[].rollback.issues | `object[]` | 必填 / 必有；回滚会产生的不兼容项，每项含 pointer 与 reason；allowed 为 true 时为空数组。 |
| data[].rollback.issues[].pointer | `string` | 必填 / 必有；不兼容位置的 JSON Pointer（RFC 6901），相对于动作的 input_schema 或 output_schema。 |
| data[].rollback.issues[].reason | `string` | 必填 / 必有；该位置为何与历史修订不兼容（输入应放宽、输出应收紧）。 |
| data[].id | `string` | 必填 / 必有；修订 ID，前缀 actr_；仅用于展示与回滚（rollback 的 revision），不能被脚本直接引用。 |
| data[].digest | `string` | 必填 / 必有；契约与实现的内容摘要；内容相同的更新不会产生新修订。 |
| data[].input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| data[].input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| data[].input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| data[].output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| data[].output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].errors | `object[]` | 必填 / 必有；动作声明的可能错误列表，每项含 type、code、description。 |
| data[].errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| data[].errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| data[].errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| data[].annotations | `object` | 必填 / 必有；动作行为声明 &#123;read_only, idempotent&#125;；创建时未给出的键默认为 false。 不接受额外字段。 |
| data[].annotations.read_only | `boolean` | 必填 / 必有；true 表示动作不修改外部状态，只读取数据。 |
| data[].annotations.idempotent | `boolean` | 必填 / 必有；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。 |
| data[].timeout_ms | `number` | 必填 / 必有；单次执行的超时毫秒数；创建时未给出，code 实现默认 30000，容器或 shell 实现默认 600000。 |
| data[].implementation | `object` / `object` / `object` / `object` | 必填 / 必有；实现信息：完整实现，或仅含 kind；列表不返回源码，需源码用 expand=source 或读取单个修订。 |
| data[].implementation（分支1)（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| data[].implementation（分支1)（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| data[].implementation（分支1)（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码；内置动作为空。 |
| data[].implementation（分支1)（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放）。 |
| data[].implementation（分支1)（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| data[].implementation（分支1)（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| data[].implementation（分支1)（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放）。 |
| data[].implementation（分支1)（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| data[].implementation（分支2).kind | `"code"` / `"container"` / `"shell"` | 必填 / 必有；动作实现方式。code 为源码实现（目前仅 language=ts 可用）；container 为容器镜像加命令，暂未开放；shell 为 shell 脚本，暂未开放。 |
| data[].host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| data[].platform_apis | `string[]` | 必填 / 必有；从代码推导出的平台 API 集合，同时是该动作运行令牌的权限范围（最小权限）。 |
| data[].created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| data[].created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[].message | `null` / `string` | 必填 / 必有；创建该修订时附带的说明；未提供为 null。 |
| data[].created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "actr_00mv67lrt1370820a9daaa4fd3882332e4899a4c9e",
      "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
      "input_schema": {
        "type": "object",
        "properties": {
          "n": {
            "type": "number"
          }
        },
        "required": [
          "n"
        ],
        "additionalProperties": false
      },
      "output_schema": {
        "type": "object",
        "properties": {
          "answer": {
            "type": "number"
          }
        },
        "required": [
          "answer"
        ],
        "additionalProperties": false
      },
      "errors": [],
      "annotations": {
        "read_only": false,
        "idempotent": false
      },
      "timeout_ms": 30000,
      "host": "isolate",
      "platform_apis": [],
      "created_by": {
        "type": "api_key",
        "id": "key_3e00b8984967"
      },
      "message": "Sample revision",
      "created_at": "2026-10-13T04:57:12.709Z",
      "current": true,
      "rollback": {
        "allowed": true,
        "issues": []
      },
      "implementation": {
        "kind": "code"
      }
    },
    {
      "id": "actr_00mv67loz3e46938b8ecf54e57b8f31297df016a1c",
      "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
      "input_schema": {
        "type": "object",
        "properties": {
          "n": {
            "type": "number"
          }
        },
        "required": [
          "n"
        ],
        "additionalProperties": false
      },
      "output_schema": {
        "type": "object",
        "properties": {
          "answer": {
            "type": "number"
          }
        },
        "required": [
          "answer"
        ],
        "additionalProperties": false
      },
      "errors": [],
      "annotations": {
        "read_only": false,
        "idempotent": false
      },
      "timeout_ms": 30000,
      "host": "isolate",
      "platform_apis": [],
      "created_by": {
        "type": "api_key",
        "id": "key_3e00b8984967"
      },
      "message": null,
      "created_at": "2026-10-13T04:57:09.039Z",
      "current": false,
      "rollback": {
        "allowed": true,
        "issues": []
      },
      "implementation": {
        "kind": "code"
      }
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取动作修订

读取指定修订的完整实现及回滚兼容判定；修订不存在时返回 VERSION_NOT_FOUND。 详情始终返回完整源码。

`GET /automation/v1/actions/{ns}/{name}/revisions/{revision}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: revision | `string` | 必填；动作修订 ID（actr_）；查询参数用于筛选调用记录。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |
| REVISION_ID | [已有动作修订 id](/docs/api/native/automation/listActionRevisions) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
: "${REVISION_ID:?Set REVISION_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}/revisions/${REVISION_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.revisions.retrieve({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME"),
    "revision": env("REVISION_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| current | `boolean` | 必填 / 必有；true 表示这是动作当前生效的修订。 |
| rollback | `object` | 必填 / 必有；回滚到该修订是否可行，由服务端对当前修订做兼容判定。 不接受额外字段。 |
| rollback.allowed | `boolean` | 必填 / 必有；true 表示可以回滚到此修订；false 时 issues 说明原因。 |
| rollback.issues | `object[]` | 必填 / 必有；回滚会产生的不兼容项，每项含 pointer 与 reason；allowed 为 true 时为空数组。 |
| rollback.issues[].pointer | `string` | 必填 / 必有；不兼容位置的 JSON Pointer（RFC 6901），相对于动作的 input_schema 或 output_schema。 |
| rollback.issues[].reason | `string` | 必填 / 必有；该位置为何与历史修订不兼容（输入应放宽、输出应收紧）。 |
| id | `string` | 必填 / 必有；修订 ID，前缀 actr_；仅用于展示与回滚（rollback 的 revision），不能被脚本直接引用。 |
| digest | `string` | 必填 / 必有；契约与实现的内容摘要；内容相同的更新不会产生新修订。 |
| input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| errors | `object[]` | 必填 / 必有；动作声明的可能错误列表，每项含 type、code、description。 |
| errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| annotations | `object` | 必填 / 必有；动作行为声明 &#123;read_only, idempotent&#125;；创建时未给出的键默认为 false。 不接受额外字段。 |
| annotations.read_only | `boolean` | 必填 / 必有；true 表示动作不修改外部状态，只读取数据。 |
| annotations.idempotent | `boolean` | 必填 / 必有；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。 |
| timeout_ms | `number` | 必填 / 必有；单次执行的超时毫秒数；创建时未给出，code 实现默认 30000，容器或 shell 实现默认 600000。 |
| implementation | `object` / `object` / `object` | 必填 / 必有；code 使用 language=ts 与 source。container 和 shell 暂未开放，创建时返回 OPERATION_NOT_SUPPORTED。 |
| implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码；内置动作为空。 |
| implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放）。 |
| implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放）。 |
| implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| platform_apis | `string[]` | 必填 / 必有；从代码推导出的平台 API 集合，同时是该动作运行令牌的权限范围（最小权限）。 |
| created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| message | `null` / `string` | 必填 / 必有；创建该修订时附带的说明；未提供为 null。 |
| created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "actr_00mv67loz3e46938b8ecf54e57b8f31297df016a1c",
  "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
  "input_schema": {
    "type": "object",
    "properties": {
      "n": {
        "type": "number"
      }
    },
    "required": [
      "n"
    ],
    "additionalProperties": false
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "answer": {
        "type": "number"
      }
    },
    "required": [
      "answer"
    ],
    "additionalProperties": false
  },
  "errors": [],
  "annotations": {
    "read_only": false,
    "idempotent": false
  },
  "timeout_ms": 30000,
  "implementation": {
    "kind": "code",
    "language": "ts",
    "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
  },
  "host": "isolate",
  "platform_apis": [],
  "created_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "message": null,
  "created_at": "2026-10-13T04:57:09.039Z",
  "current": false,
  "rollback": {
    "allowed": true,
    "issues": []
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 回滚动作

用历史内容创建通过兼容检查的新修订。检查覆盖当前及最近五个历史修订；不会把当前指针直接退回旧 ID。可选 If-Match 可指定当前修订或 *；* 匹配任何当前存在的表示。

`POST /automation/v1/actions/{ns}/{name}/rollback`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| header: If-Match | `string` | 可选；可选当前修订或 *；提供时执行条件校验，* 匹配任何当前存在的表示。 |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| revision | `string` | 必填 / 必有；要回滚到的历史修订 ID（actr_）；回滚会创建新修订。 |
| message | `string` | 可选；本次修订的说明。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |
| REVISION_ID | [已有动作修订 id](/docs/api/native/automation/listActionRevisions) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
: "${REVISION_ID:?Set REVISION_ID}"
BODY=$(jq -n --arg REVISION_ID "$REVISION_ID" '{
  "revision": $REVISION_ID
}')
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}/rollback" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data "$BODY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.rollback({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME")
  },
  "body": {
    "revision": env("REVISION_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |
| ETag | `string` | Current revision ID after rollback. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；动作 ID，前缀 act_；日常调用使用 namespace 与 name，而不是 id。 |
| namespace | `string` | 必填 / 必有；动作命名空间；平台动作为 praxis，裸名引用解析到 praxis。 |
| name | `string` | 必填 / 必有；动作名，与 namespace 一起唯一标识动作；小写字母、数字、点、下划线、连字符，最长 64 字符。 |
| description | `string` | 必填 / 必有；动作说明，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；动作所属租户，由网关注入；按不透明字符串处理。 |
| builtin | `boolean` | 必填 / 必有；true 表示平台内置动作（命名空间 praxis）；用户创建的动作为 false。 |
| current_revision | `object` | 必填 / 必有；动作的一个不可变修订：契约、实现和运行参数的快照。每次更新兼容的内容变化都会产生新修订。 不接受额外字段。 |
| current_revision.id | `string` | 必填 / 必有；修订 ID，前缀 actr_；仅用于展示与回滚（rollback 的 revision），不能被脚本直接引用。 |
| current_revision.digest | `string` | 必填 / 必有；契约与实现的内容摘要；内容相同的更新不会产生新修订。 |
| current_revision.input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.errors | `object[]` | 必填 / 必有；动作声明的可能错误列表，每项含 type、code、description。 |
| current_revision.errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| current_revision.errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| current_revision.errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| current_revision.annotations | `object` | 必填 / 必有；动作行为声明 &#123;read_only, idempotent&#125;；创建时未给出的键默认为 false。 不接受额外字段。 |
| current_revision.annotations.read_only | `boolean` | 必填 / 必有；true 表示动作不修改外部状态，只读取数据。 |
| current_revision.annotations.idempotent | `boolean` | 必填 / 必有；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。 |
| current_revision.timeout_ms | `number` | 必填 / 必有；单次执行的超时毫秒数；创建时未给出，code 实现默认 30000，容器或 shell 实现默认 600000。 |
| current_revision.implementation | `object` / `object` / `object` | 必填 / 必有；code 使用 language=ts 与 source。container 和 shell 暂未开放，创建时返回 OPERATION_NOT_SUPPORTED。 |
| current_revision.implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| current_revision.implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| current_revision.implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码；内置动作为空。 |
| current_revision.implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放）。 |
| current_revision.implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| current_revision.implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| current_revision.implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放）。 |
| current_revision.implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| current_revision.host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| current_revision.platform_apis | `string[]` | 必填 / 必有；从代码推导出的平台 API 集合，同时是该动作运行令牌的权限范围（最小权限）。 |
| current_revision.created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| current_revision.created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| current_revision.created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| current_revision.message | `null` / `string` | 必填 / 必有；创建该修订时附带的说明；未提供为 null。 |
| current_revision.created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |
| stats_7d | `object` | 必填 / 必有；近七天统计；平台动作按调用方租户隔离，只反映当前调用方的调用，不是平台全局统计。 不接受额外字段。 |
| stats_7d.calls | `number` | 必填 / 必有；近七天内对该动作的调用次数，按小时汇总。 |
| stats_7d.failures | `number` | 必填 / 必有；近七天内失败的调用次数。 |
| stats_7d.p50_ms | `null` / `number` | 必填 / 必有；耗时中位数的近似上界，单位毫秒；正耗时向上归入 2 的幂分桶（9 ms → 16 ms），0 独立一桶；无有效耗时样本时为 null。 |
| dependents | `object` | 必填 / 必有；引用该动作的脚本与工作流数量，口径为最新版本加草稿。 不接受额外字段。 |
| dependents.scripts | `number` | 必填 / 必有；引用该动作的脚本数量。 |
| dependents.workflows | `number` | 必填 / 必有；引用该动作的工作流数量。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不能复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "act_00mv67loz4fe4f27bdf89346c885b3a28b2038c091",
  "owner": "tnt_3a9759864ccb4e00",
  "namespace": "docs-samples",
  "name": "sample-action-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "builtin": false,
  "archived_at": null,
  "created_at": "2026-10-13T04:57:09.039Z",
  "updated_at": "2026-10-13T04:57:15.629Z",
  "current_revision": {
    "input_schema": {
      "type": "object",
      "properties": {
        "n": {
          "type": "number"
        }
      },
      "required": [
        "n"
      ],
      "additionalProperties": false
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "number"
        }
      },
      "required": [
        "answer"
      ],
      "additionalProperties": false
    },
    "errors": [],
    "annotations": {
      "read_only": false,
      "idempotent": false
    },
    "timeout_ms": 30000,
    "implementation": {
      "kind": "code",
      "language": "ts",
      "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
    },
    "host": "isolate",
    "platform_apis": [],
    "id": "actr_00mv67lu25f7f28dd81a924c698b9d2557056a7b62",
    "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
    "created_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    },
    "message": "回滚到 actr_00mv67loz3e46938b8ecf54e57b8f31297df016a1c",
    "created_at": "2026-10-13T04:57:15.629Z"
  },
  "stats_7d": {
    "calls": 0,
    "failures": 0,
    "p50_ms": null
  },
  "dependents": {
    "scripts": 0,
    "workflows": 0
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 413 | PAYLOAD_TOO_LARGE：请求内容超过本操作允许的大小。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 SCHEMA_INCOMPATIBLE：新动作契约与历史修订不兼容。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出动作调用

列出该动作的调用记录，可按状态、修订、调用方编排和时间筛选；结果包含所属运行与调用位置。

`GET /automation/v1/actions/{ns}/{name}/invocations`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 20。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"[]` | 可选；逗号分隔的状态，可选 running、completed、faulted、cancelled；省略不过滤。 |
| query: revision | `string` | 可选；动作修订 ID（actr_）；查询参数用于筛选调用记录。 |
| query: caller | `string` | 可选；调用方脚本或工作流的精确名称，格式 ns/name。 |
| query: run_kind | `"script"` / `"workflow"` | 可选；调用方运行类型：script 或 workflow。 |
| query: created_at[gte] | `string` | 可选；创建时间下界（包含），RFC 3339 且带时区，如 2026-10-01T00:00:00Z。 format: "date-time" |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}/invocations" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.invocations.list({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的动作调用记录，按 created_at 倒序、id 倒序排列。 |
| data[].id | `string` | 必填 / 必有；调用标识，无独立 inv_ 前缀：脚本为 run_id:seq（运行 ID 与调用序号）；工作流为任务执行键加尝试次数。请按不透明字符串保存。 |
| data[].created_at | `string` | 必填 / 必有；调用记录的创建时间（RFC 3339 UTC）。 |
| data[].started_at | `null` / `string` | 必填 / 必有；动作开始执行的时间；尚未开始为 null。 |
| data[].ended_at | `null` / `string` | 必填 / 必有；动作结束的时间；仍在执行为 null。 |
| data[].status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` | 必填 / 必有；调用状态。running 执行中；completed 已正常返回；faulted 失败，error 给出原因；cancelled 因运行被取消而中止。 |
| data[].duration_ms | `null` / `number` | 必填 / 必有；执行耗时毫秒数；未结束为 null。 |
| data[].revision | `string` | 必填 / 必有；本次执行使用的动作修订 ID（actr_ 前缀）。 |
| data[].run | `object` | 必填 / 必有；发起这次调用的运行：&#123;id, kind, definition, number, source_digest&#125;。 不接受额外字段。 |
| data[].run.id | `string` | 必填 / 必有；发起调用的运行 ID（run_ 前缀），可用于读取该运行。 |
| data[].run.kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data[].run.definition | `null` / `object` | 必填 / 必有；该运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| data[].run.definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| data[].run.definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| data[].run.number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的序号；临时运行为 null。 |
| data[].run.source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要；由已发布定义启动的运行为 null。 |
| data[].site | `object` / `object` | 必填 / 必有；调用发生的位置：脚本中的一次调用（kind=call，带 seq），或工作流的一个步骤（kind=task，带 reference 与 iteration）。 |
| data[].site（分支1).kind | `"call"` | 必填 / 必有；固定为 call：来自脚本中的调用。 |
| data[].site（分支1).seq | `number` | 必填 / 必有；该调用在脚本运行中的序号，与 Call.seq 对应。 |
| data[].site（分支2).kind | `"task"` | 必填 / 必有；固定为 task：来自工作流步骤。 |
| data[].site（分支2).reference | `string` | 必填 / 必有；工作流文档内该步骤的 JSON Pointer，与 Task.reference 对应。 |
| data[].site（分支2).iteration | `number[]` | 必填 / 必有；外层 for 循环的当前迭代下标，由外到内；不在循环中为空数组。 |
| data[].error | `null` / `object` | 必填 / 必有；失败时的 &#123;code, message&#125;；成功或仍在执行为 null。 |
| data[].error（分支2).code | `string` | 必填 / 必有；错误码，例如动作声明的 code 或平台错误码。 |
| data[].error（分支2).message | `string` | 必填 / 必有；错误说明文字。 |
| data[].result_preview | `null` / `string` | 必填 / 必有；返回值的单行预览，由服务端截断；未结束或失败为 null。 |
| data[].request_id | `string` / `null` | 必填 / 必有；下游响应的 X-Request-Id；响应未提供该头时为 null，可用于追查失败调用。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出动作引用方

列出引用该动作的编排。检查范围为脚本和工作流的草稿及最新版本。

`GET /automation/v1/actions/{ns}/{name}/dependents`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 20。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}/dependents" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.dependents.list({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的引用方（脚本与工作流，口径为最新版本加草稿），按 created_at 倒序、id 倒序排列。 |
| data[].kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data[].namespace | `string` | 必填 / 必有；引用方的命名空间。 |
| data[].name | `string` | 必填 / 必有；引用方的名字。 |
| data[].at | `string` | 必填 / 必有；引用所在的草稿或最新版本号：draft 表示草稿，其余值为该编排最新发布的版本号。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 归档动作

归档后保留名称和历史，默认列表不再显示；响应包含 dependents_count，便于判断对引用方的影响。

`POST /automation/v1/actions/{ns}/{name}/archive`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

### application/json [#applicationjson]

不接受额外字段。
object

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}/archive" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.archive({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；动作 ID，前缀 act_；日常调用使用 namespace 与 name，而不是 id。 |
| namespace | `string` | 必填 / 必有；动作命名空间；平台动作为 praxis，裸名引用解析到 praxis。 |
| name | `string` | 必填 / 必有；动作名，与 namespace 一起唯一标识动作；小写字母、数字、点、下划线、连字符，最长 64 字符。 |
| description | `string` | 必填 / 必有；动作说明，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；动作所属租户，由网关注入；按不透明字符串处理。 |
| builtin | `boolean` | 必填 / 必有；true 表示平台内置动作（命名空间 praxis）；用户创建的动作为 false。 |
| current_revision | `object` | 必填 / 必有；动作的一个不可变修订：契约、实现和运行参数的快照。每次更新兼容的内容变化都会产生新修订。 不接受额外字段。 |
| current_revision.id | `string` | 必填 / 必有；修订 ID，前缀 actr_；仅用于展示与回滚（rollback 的 revision），不能被脚本直接引用。 |
| current_revision.digest | `string` | 必填 / 必有；契约与实现的内容摘要；内容相同的更新不会产生新修订。 |
| current_revision.input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.errors | `object[]` | 必填 / 必有；动作声明的可能错误列表，每项含 type、code、description。 |
| current_revision.errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| current_revision.errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| current_revision.errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| current_revision.annotations | `object` | 必填 / 必有；动作行为声明 &#123;read_only, idempotent&#125;；创建时未给出的键默认为 false。 不接受额外字段。 |
| current_revision.annotations.read_only | `boolean` | 必填 / 必有；true 表示动作不修改外部状态，只读取数据。 |
| current_revision.annotations.idempotent | `boolean` | 必填 / 必有；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。 |
| current_revision.timeout_ms | `number` | 必填 / 必有；单次执行的超时毫秒数；创建时未给出，code 实现默认 30000，容器或 shell 实现默认 600000。 |
| current_revision.implementation | `object` / `object` / `object` | 必填 / 必有；code 使用 language=ts 与 source。container 和 shell 暂未开放，创建时返回 OPERATION_NOT_SUPPORTED。 |
| current_revision.implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| current_revision.implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| current_revision.implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码；内置动作为空。 |
| current_revision.implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放）。 |
| current_revision.implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| current_revision.implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| current_revision.implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放）。 |
| current_revision.implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| current_revision.host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| current_revision.platform_apis | `string[]` | 必填 / 必有；从代码推导出的平台 API 集合，同时是该动作运行令牌的权限范围（最小权限）。 |
| current_revision.created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| current_revision.created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| current_revision.created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| current_revision.message | `null` / `string` | 必填 / 必有；创建该修订时附带的说明；未提供为 null。 |
| current_revision.created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |
| stats_7d | `object` | 必填 / 必有；近七天统计；平台动作按调用方租户隔离，只反映当前调用方的调用，不是平台全局统计。 不接受额外字段。 |
| stats_7d.calls | `number` | 必填 / 必有；近七天内对该动作的调用次数，按小时汇总。 |
| stats_7d.failures | `number` | 必填 / 必有；近七天内失败的调用次数。 |
| stats_7d.p50_ms | `null` / `number` | 必填 / 必有；耗时中位数的近似上界，单位毫秒；正耗时向上归入 2 的幂分桶（9 ms → 16 ms），0 独立一桶；无有效耗时样本时为 null。 |
| dependents | `object` | 必填 / 必有；引用该动作的脚本与工作流数量，口径为最新版本加草稿。 不接受额外字段。 |
| dependents.scripts | `number` | 必填 / 必有；引用该动作的脚本数量。 |
| dependents.workflows | `number` | 必填 / 必有；引用该动作的工作流数量。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不能复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |
| dependents_count | `integer` | 必填 / 必有；归档时仍引用该动作的脚本与工作流数量之和（dependents.scripts 加 dependents.workflows）。 minimum: 0 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "act_00mv67loz4fe4f27bdf89346c885b3a28b2038c091",
  "owner": "tnt_3a9759864ccb4e00",
  "namespace": "docs-samples",
  "name": "sample-action-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "builtin": false,
  "archived_at": "2026-10-13T04:57:17.830Z",
  "created_at": "2026-10-13T04:57:09.039Z",
  "updated_at": "2026-10-13T04:57:17.830Z",
  "current_revision": {
    "id": "actr_00mv67lu25f7f28dd81a924c698b9d2557056a7b62",
    "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
    "input_schema": {
      "type": "object",
      "properties": {
        "n": {
          "type": "number"
        }
      },
      "required": [
        "n"
      ],
      "additionalProperties": false
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "number"
        }
      },
      "required": [
        "answer"
      ],
      "additionalProperties": false
    },
    "errors": [],
    "annotations": {
      "read_only": false,
      "idempotent": false
    },
    "timeout_ms": 30000,
    "implementation": {
      "kind": "code",
      "language": "ts",
      "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
    },
    "host": "isolate",
    "platform_apis": [],
    "created_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    },
    "message": "回滚到 actr_00mv67loz3e46938b8ecf54e57b8f31297df016a1c",
    "created_at": "2026-10-13T04:57:15.629Z"
  },
  "stats_7d": {
    "calls": 0,
    "failures": 0,
    "p50_ms": null
  },
  "dependents": {
    "scripts": 0,
    "workflows": 0
  },
  "dependents_count": 0
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 恢复动作

恢复已归档动作，保留当前修订。恢复后重新出现在默认列表。

`POST /automation/v1/actions/{ns}/{name}/restore`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

### application/json [#applicationjson]

不接受额外字段。
object

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| ACTION_NAME | [创建动作返回的 name](/docs/api/native/automation/createAction) |

```bash
: "${ACTION_NAME:?Set ACTION_NAME}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/actions/docs-samples/${ACTION_NAME}/restore" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.actions.restore({
  "path": {
    "ns": "docs-samples",
    "name": env("ACTION_NAME")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；动作 ID，前缀 act_；日常调用使用 namespace 与 name，而不是 id。 |
| namespace | `string` | 必填 / 必有；动作命名空间；平台动作为 praxis，裸名引用解析到 praxis。 |
| name | `string` | 必填 / 必有；动作名，与 namespace 一起唯一标识动作；小写字母、数字、点、下划线、连字符，最长 64 字符。 |
| description | `string` | 必填 / 必有；动作说明，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；动作所属租户，由网关注入；按不透明字符串处理。 |
| builtin | `boolean` | 必填 / 必有；true 表示平台内置动作（命名空间 praxis）；用户创建的动作为 false。 |
| current_revision | `object` | 必填 / 必有；动作的一个不可变修订：契约、实现和运行参数的快照。每次更新兼容的内容变化都会产生新修订。 不接受额外字段。 |
| current_revision.id | `string` | 必填 / 必有；修订 ID，前缀 actr_；仅用于展示与回滚（rollback 的 revision），不能被脚本直接引用。 |
| current_revision.digest | `string` | 必填 / 必有；契约与实现的内容摘要；内容相同的更新不会产生新修订。 |
| current_revision.input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.output_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| current_revision.output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| current_revision.output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| current_revision.errors | `object[]` | 必填 / 必有；动作声明的可能错误列表，每项含 type、code、description。 |
| current_revision.errors[].type | `string` | 必填 / 必有；错误类型：稳定的 URI，或 Open Workflow 标准类型（如 validation、timeout、communication、runtime）。 |
| current_revision.errors[].code | `string` | 可选；可选的稳定错误码，供调用方按码分支处理。 |
| current_revision.errors[].description | `string` | 必填 / 必有；该错误的含义与触发条件，面向调用方阅读。 |
| current_revision.annotations | `object` | 必填 / 必有；动作行为声明 &#123;read_only, idempotent&#125;；创建时未给出的键默认为 false。 不接受额外字段。 |
| current_revision.annotations.read_only | `boolean` | 必填 / 必有；true 表示动作不修改外部状态，只读取数据。 |
| current_revision.annotations.idempotent | `boolean` | 必填 / 必有；true 表示同一输入重复调用与调用一次效果相同；此类动作的重试使用同一幂等键（run_id 加步骤路径，不含尝试次数）。 |
| current_revision.timeout_ms | `number` | 必填 / 必有；单次执行的超时毫秒数；创建时未给出，code 实现默认 30000，容器或 shell 实现默认 600000。 |
| current_revision.implementation | `object` / `object` / `object` | 必填 / 必有；code 使用 language=ts 与 source。container 和 shell 暂未开放，创建时返回 OPERATION_NOT_SUPPORTED。 |
| current_revision.implementation（分支1).kind | `"code"` | 必填 / 必有；固定为 code：以源码实现。 |
| current_revision.implementation（分支1).language | `"ts"` | 必填 / 必有；源码语言，目前只支持 ts（TypeScript）。 |
| current_revision.implementation（分支1).source | `string` | 必填 / 必有；动作的完整 TypeScript 源码；内置动作为空。 |
| current_revision.implementation（分支2).kind | `"container"` | 必填 / 必有；固定为 container：以容器镜像实现（暂未开放）。 |
| current_revision.implementation（分支2).image | `string` | 必填 / 必有；容器镜像引用。 |
| current_revision.implementation（分支2).command | `string[]` | 必填 / 必有；在容器中执行的命令及参数列表。 |
| current_revision.implementation（分支3).kind | `"shell"` | 必填 / 必有；固定为 shell：以 shell 脚本实现（暂未开放）。 |
| current_revision.implementation（分支3).script | `string` | 必填 / 必有；要执行的 shell 脚本全文。 |
| current_revision.host | `"builtin"` / `"isolate"` / `"sandbox"` | 必填 / 必有；动作运行位置，发布时计算。builtin 为平台内置动作；isolate 为在隔离的 Worker isolate 中运行用户代码；sandbox 为在沙箱中运行（container 与 shell 实现）。 |
| current_revision.platform_apis | `string[]` | 必填 / 必有；从代码推导出的平台 API 集合，同时是该动作运行令牌的权限范围（最小权限）。 |
| current_revision.created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| current_revision.created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| current_revision.created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| current_revision.message | `null` / `string` | 必填 / 必有；创建该修订时附带的说明；未提供为 null。 |
| current_revision.created_at | `string` | 必填 / 必有；该修订的创建时间（RFC 3339 UTC）。 |
| stats_7d | `object` | 必填 / 必有；近七天统计；平台动作按调用方租户隔离，只反映当前调用方的调用，不是平台全局统计。 不接受额外字段。 |
| stats_7d.calls | `number` | 必填 / 必有；近七天内对该动作的调用次数，按小时汇总。 |
| stats_7d.failures | `number` | 必填 / 必有；近七天内失败的调用次数。 |
| stats_7d.p50_ms | `null` / `number` | 必填 / 必有；耗时中位数的近似上界，单位毫秒；正耗时向上归入 2 的幂分桶（9 ms → 16 ms），0 独立一桶；无有效耗时样本时为 null。 |
| dependents | `object` | 必填 / 必有；引用该动作的脚本与工作流数量，口径为最新版本加草稿。 不接受额外字段。 |
| dependents.scripts | `number` | 必填 / 必有；引用该动作的脚本数量。 |
| dependents.workflows | `number` | 必填 / 必有；引用该动作的工作流数量。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不能复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "act_00mv67loz4fe4f27bdf89346c885b3a28b2038c091",
  "owner": "tnt_3a9759864ccb4e00",
  "namespace": "docs-samples",
  "name": "sample-action-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "builtin": false,
  "archived_at": null,
  "created_at": "2026-10-13T04:57:09.039Z",
  "updated_at": "2026-10-13T04:57:18.573Z",
  "current_revision": {
    "id": "actr_00mv67lu25f7f28dd81a924c698b9d2557056a7b62",
    "digest": "e35c209873c60486ca8da455878062cb7ea572a6147ce3ca03e0693b4769fa45",
    "input_schema": {
      "type": "object",
      "properties": {
        "n": {
          "type": "number"
        }
      },
      "required": [
        "n"
      ],
      "additionalProperties": false
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "number"
        }
      },
      "required": [
        "answer"
      ],
      "additionalProperties": false
    },
    "errors": [],
    "annotations": {
      "read_only": false,
      "idempotent": false
    },
    "timeout_ms": 30000,
    "implementation": {
      "kind": "code",
      "language": "ts",
      "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
    },
    "host": "isolate",
    "platform_apis": [],
    "created_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    },
    "message": "回滚到 actr_00mv67loz3e46938b8ecf54e57b8f31297df016a1c",
    "created_at": "2026-10-13T04:57:15.629Z"
  },
  "stats_7d": {
    "calls": 0,
    "failures": 0,
    "p50_ms": null
  },
  "dependents": {
    "scripts": 0,
    "workflows": 0
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | ACTION_NOT_FOUND：动作不存在或当前租户不可见；同名脚本/工作流存在时，hint 指向相应接口。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出脚本

列出可见脚本的摘要、最新版本、标签及近七天统计；默认排除已归档条目。

`GET /automation/v1/scripts`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 25。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: q | `string` | 可选；不区分大小写，按名称或说明的字面子串匹配；% 与 _ 无通配含义。 |
| query: namespace | `string[]` | 可选；仅返回指定命名空间的定义，名称按小写匹配。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: scope | `"platform"` / `"own"[]` | 可选；platform 仅平台定义，own 仅租户自建定义；省略返回两者。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: archived | `boolean` | 可选；true 仅已归档，false 仅未归档；默认 false。 |
| query: labels | `object` | 可选；按标签过滤，使用 labels[k]=v；同键逗号多值取任一，不同键同时满足。 |
| query: created_at[gte] | `string` | 可选；创建时间下界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |
| query: created_at[lte] | `string` | 可选；创建时间上界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/scripts" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  --get \
  --data-urlencode "namespace=docs-samples" \
  --data-urlencode "limit=1"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.list({
  "query": {
    "namespace": [
      "docs-samples"
    ],
    "limit": 1
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的脚本摘要，按 created_at 倒序、id 倒序排列。 |
| data[].id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| data[].kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data[].namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| data[].name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| data[].description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| data[].labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| data[].owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| data[].latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| data[].latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| data[].latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| data[].dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| data[].draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| data[].latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| data[].latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| data[].latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| data[].latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| data[].latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| data[].latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| data[].latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| data[].latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| data[].latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| data[].latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| data[].latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| data[].latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| data[].latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| data[].latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| data[].latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| data[].latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| data[].latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| data[].latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| data[].latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| data[].stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| data[].stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| data[].stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| data[].archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| data[].created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| data[].updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "scr_00mv67lwvh08624c70ef824a0d8b14b0315c88452e",
      "owner": "tnt_3a9759864ccb4e00",
      "kind": "script",
      "namespace": "docs-samples",
      "name": "sample-scripts-1791867412840-b05e8a",
      "description": "",
      "labels": {},
      "latest_version": null,
      "dist_tags": {},
      "draft_changed": true,
      "latest_run": null,
      "stats_7d": {
        "runs": 0,
        "failures": 0
      },
      "archived_at": null,
      "created_at": "2026-10-13T04:57:19.277Z",
      "updated_at": "2026-10-13T04:57:19.277Z"
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 创建脚本

创建脚本及可编辑草稿，不会发布或启动运行；脚本与工作流共用名称空间，同租户重名返回 NAME_TAKEN。

`POST /automation/v1/scripts`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| namespace | `string` | 必填 / 必有；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 pattern: "^[a-zA-Z0-9][a-zA-Z0-9._-]&#123;0,63&#125;$" |
| name | `string` | 必填 / 必有；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 pattern: "^[a-zA-Z0-9][a-zA-Z0-9._-]&#123;0,63&#125;$" |
| description | `string` | 可选；说明，最多 1000 个字符。 maxLength: 1000 |
| draft | `string` | 可选；可编辑源码；脚本为 TypeScript，工作流为 YAML。创建时省略为空字符串。 |
| labels | `object` | 可选；最多 50 个标签；键为 1–40 个字符，值最多 500 个字符。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/scripts" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "namespace": "docs-samples",
  "name": "sample-scripts",
  "draft": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.create({
  "body": {
    "namespace": "docs-samples",
    "name": "sample-scripts",
    "draft": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| draft | `object` | 必填 / 必有；脚本或工作流的可编辑草稿；发布版本时以草稿或某次运行的源码为准。 不接受额外字段。 |
| draft.source | `string` | 必填 / 必有；草稿源码：脚本为 TypeScript，工作流为 YAML。 |
| draft.revision | `string` | 必填 / 必有；草稿修订标识（ETag），发布时作为 expected_draft_revision，更新草稿时作为 If-Match；与当前不一致返回 412。 |
| draft.updated_at | `string` | 必填 / 必有；草稿最近一次修改的时间（RFC 3339 UTC）。 |
| draft.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| draft.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| draft.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "scr_00mv67lwvh08624c70ef824a0d8b14b0315c88452e",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "script",
  "namespace": "docs-samples",
  "name": "sample-scripts-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "latest_version": null,
  "dist_tags": {},
  "draft_changed": true,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:19.277Z",
  "updated_at": "2026-10-13T04:57:19.277Z",
  "draft": {
    "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });",
    "revision": "draft_00mv67lwvh333793ba7d9e47cb89b5fd8b43fb4fa3",
    "updated_at": "2026-10-13T04:57:19.277Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 NAME_TAKEN：名称已被同一租户占用。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取脚本

读取脚本详情及草稿源码；ETag 是草稿修订，可作为修改请求的 If-Match。

`GET /automation/v1/scripts/{ns}/{name}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.retrieve({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| ETag | `string` | Current resource revision for conditional updates. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| draft | `object` | 必填 / 必有；脚本或工作流的可编辑草稿；发布版本时以草稿或某次运行的源码为准。 不接受额外字段。 |
| draft.source | `string` | 必填 / 必有；草稿源码：脚本为 TypeScript，工作流为 YAML。 |
| draft.revision | `string` | 必填 / 必有；草稿修订标识（ETag），发布时作为 expected_draft_revision，更新草稿时作为 If-Match；与当前不一致返回 412。 |
| draft.updated_at | `string` | 必填 / 必有；草稿最近一次修改的时间（RFC 3339 UTC）。 |
| draft.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| draft.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| draft.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "scr_00mv67lwvh08624c70ef824a0d8b14b0315c88452e",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "script",
  "namespace": "docs-samples",
  "name": "sample-scripts-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "latest_version": null,
  "dist_tags": {},
  "draft_changed": true,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:19.277Z",
  "updated_at": "2026-10-13T04:57:19.277Z",
  "draft": {
    "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });",
    "revision": "draft_00mv67lwvh333793ba7d9e47cb89b5fd8b43fb4fa3",
    "updated_at": "2026-10-13T04:57:19.277Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 更新脚本草稿

修改说明、标签或草稿，必须携带与当前草稿匹配的 If-Match；即使只改元数据也会生成新的草稿修订。

`PATCH /automation/v1/scripts/{ns}/{name}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| header: If-Match | `string` | 必填；当前资源的 ETag，可直接使用对象里的 draft.revision 或 etag 字段值：裸值、带双引号或弱校验写法 W/"…" 均接受（RFC 7232 弱比较）；缺失返回 400，修订不匹配返回 412。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| description | `string` | 可选；说明，最多 1000 个字符。 maxLength: 1000 |
| labels | `object` | 可选；最多 50 个标签；键为 1–40 个字符，值最多 500 个字符。 |
| draft | `string` | 可选；可编辑源码；脚本为 TypeScript，工作流为 YAML。创建时省略为空字符串。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |
| ETAG | [最新 GET 响应头 ETag（保留引号）](/docs/api/native/automation/getScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
: "${ETAG:?Set ETAG}"
curl --fail-with-body -X PATCH "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "If-Match: ${ETAG}" \
  -H "Content-Type: application/json" \
  --data '{
  "description": "Sample definition",
  "draft": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.update({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME")
  },
  "headers": {
    "If-Match": env("ETAG")
  },
  "body": {
    "description": "Sample definition",
    "draft": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| draft | `object` | 必填 / 必有；脚本或工作流的可编辑草稿；发布版本时以草稿或某次运行的源码为准。 不接受额外字段。 |
| draft.source | `string` | 必填 / 必有；草稿源码：脚本为 TypeScript，工作流为 YAML。 |
| draft.revision | `string` | 必填 / 必有；草稿修订标识（ETag），发布时作为 expected_draft_revision，更新草稿时作为 If-Match；与当前不一致返回 412。 |
| draft.updated_at | `string` | 必填 / 必有；草稿最近一次修改的时间（RFC 3339 UTC）。 |
| draft.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| draft.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| draft.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "scr_00mv67lwvh08624c70ef824a0d8b14b0315c88452e",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "script",
  "namespace": "docs-samples",
  "name": "sample-scripts-1791867412840-b05e8a",
  "description": "Sample definition",
  "labels": {},
  "latest_version": null,
  "dist_tags": {},
  "draft_changed": true,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:19.277Z",
  "updated_at": "2026-10-13T04:57:21.691Z",
  "draft": {
    "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });",
    "revision": "draft_00mv67lwvh333793ba7d9e47cb89b5fd8b43fb4fa3",
    "updated_at": "2026-10-13T04:57:19.277Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 归档脚本

归档后保留名称、版本和草稿；默认列表隐藏该条目，新的目标解析和运行请求拒绝已归档目标。

`POST /automation/v1/scripts/{ns}/{name}/archive`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

### application/json [#applicationjson]

不接受额外字段。
object

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/archive" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.archive({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "scr_00mv67lwvh08624c70ef824a0d8b14b0315c88452e",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "script",
  "namespace": "docs-samples",
  "name": "sample-scripts-1791867412840-b05e8a",
  "description": "Sample definition",
  "labels": {},
  "latest_version": {
    "version": "1.0.0",
    "published_at": "2026-10-13T04:57:22.398Z"
  },
  "dist_tags": {
    "latest": "1.0.0"
  },
  "draft_changed": false,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": "2026-10-13T04:57:27.639Z",
  "created_at": "2026-10-13T04:57:19.277Z",
  "updated_at": "2026-10-13T04:57:27.639Z"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 恢复脚本

恢复已归档定义，保留版本和标签。名称无需重新分配。

`POST /automation/v1/scripts/{ns}/{name}/restore`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

### application/json [#applicationjson]

不接受额外字段。
object

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/restore" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.restore({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "scr_00mv67lwvh08624c70ef824a0d8b14b0315c88452e",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "script",
  "namespace": "docs-samples",
  "name": "sample-scripts-1791867412840-b05e8a",
  "description": "Sample definition",
  "labels": {},
  "latest_version": {
    "version": "1.0.0",
    "published_at": "2026-10-13T04:57:22.398Z"
  },
  "dist_tags": {
    "latest": "1.0.0"
  },
  "draft_changed": false,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:19.277Z",
  "updated_at": "2026-10-13T04:57:28.559Z"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 发布脚本版本

从草稿或临时运行源码发布版本，校验定义并锁定依赖。草稿须匹配 expected_draft_revision；临时运行由 from_run 与 expected_source_sha256 指定。版本相同且内容相同返回已有版本，内容不同返回 VERSION_EXISTS；预发布版本必须显式带 tag（不能是 latest，tag 只能含 URL 安全字符且不能是版本号或范围，违规返回 TAG_REQUIRED 或 TAG_INVALID，hint 给出完整规则），校验不通过返回 DEFINITION_INVALID。稳定版本仅高于已有最高稳定版本时自动移动 latest；工作流成为 latest 时同步定义中的定时触发器。 发布会去掉版本号的 +build 元数据。

`POST /automation/v1/scripts/{ns}/{name}/versions`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

### application/json [#applicationjson]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| （分支1).version | `string` | 必填 / 必有；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 |
| （分支1).expected_draft_revision | `string` | 必填 / 必有；发布的草稿修订，必须匹配当前草稿；与 from_run 发布方式二选一。 |
| （分支1).tag | `string` | 可选；发布标签。预发布版本（如 1.3.0-beta.1）必须带 tag 且不能是 latest；tag 只能由 URL 安全字符组成（字母、数字及 - _ . ! ~ * ' ( )），不含空格和 / ? #，首尾无空白；不能是版本号或版本范围（如 1.2.3、^1、1.x、*）；beta、next、debug 等其余名称均可。违规返回 TAG_INVALID 或 TAG_REQUIRED，hint 给出完整规则。 |
| （分支2).version | `string` | 必填 / 必有；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 |
| （分支2).from_run | `string` | 必填 / 必有；提供源码快照的临时运行 ID；已发布目标的运行当前没有可用于此入口的快照。须同时给出 expected_source_sha256，不能同时给 expected_draft_revision。 |
| （分支2).expected_source_sha256 | `string` | 必填 / 必有；运行源码的 SHA-256 摘要，必须与快照匹配。 |
| （分支2).tag | `string` | 可选；发布标签。预发布版本（如 1.3.0-beta.1）必须带 tag 且不能是 latest；tag 只能由 URL 安全字符组成（字母、数字及 - _ . ! ~ * ' ( )），不含空格和 / ? #，首尾无空白；不能是版本号或版本范围（如 1.2.3、^1、1.x、*）；beta、next、debug 等其余名称均可。违规返回 TAG_INVALID 或 TAG_REQUIRED，hint 给出完整规则。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |
| DRAFT_REVISION | [当前 draft.revision](/docs/api/native/automation/getScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
: "${DRAFT_REVISION:?Set DRAFT_REVISION}"
BODY=$(jq -n --arg DRAFT_REVISION "$DRAFT_REVISION" '{
  "version": "1.0.0",
  "expected_draft_revision": $DRAFT_REVISION
}')
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/versions" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data "$BODY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.versions.publish({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME")
  },
  "body": {
    "version": "1.0.0",
    "expected_draft_revision": env("DRAFT_REVISION")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；版本 ID，脚本前缀 scv_，工作流前缀 wfv_。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| version | `string` | 必填 / 必有；版本号（semver，已去掉 +build 元数据）。 |
| digest | `string` | 必填 / 必有；源码与契约的内容摘要。 |
| source | `string` | 必填 / 必有；该版本的完整源码。版本列表默认不返回，需要时加 expand=source。 |
| input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| references | `object[]` | 必填 / 必有；该版本依赖的动作、平台 API、脚本与工作流。脚本和工作流依赖在发布时锁定到精确版本。 |
| references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| outline | `null` / `object[]` | 必填 / 必有；工作流的步骤大纲（OutlineNode 数组），由解析器静态生成；脚本为 null。 |
| outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| sdk_version | `null` / `string` | 必填 / 必有；发布脚本所用的 SDK 版本；工作流为 null。 |
| published_at | `string` | 必填 / 必有；发布时间（RFC 3339 UTC）。 |
| published_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| published_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| published_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| deprecated | `null` / `string` | 必填 / 必有；弃用说明；未弃用为 null。弃用的版本仍可运行，但按范围或标签解析时优先选用未弃用的版本。 |
| deprecated_at | `null` / `string` | 必填 / 必有；弃用时间（RFC 3339 UTC）；未弃用为 null。 |
| deprecated_by | `null` / `object` | 必填 / 必有；执行弃用的主体；未弃用为 null。 |
| deprecated_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| deprecated_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "scv_00mv67lza679fc5498438040079f0c5684208c4915",
  "kind": "script",
  "version": "1.0.0",
  "digest": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d",
  "input_schema": {
    "type": "object",
    "properties": {
      "n": {
        "type": "number"
      }
    },
    "required": [
      "n"
    ]
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "answer": {
        "type": "number"
      }
    },
    "required": [
      "answer"
    ]
  },
  "references": [],
  "outline": null,
  "sdk_version": "0.1.0",
  "published_at": "2026-10-13T04:57:22.398Z",
  "published_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "deprecated": null,
  "deprecated_at": null,
  "deprecated_by": null,
  "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 TAG_REQUIRED：预发布版本必须显式指定发布标签（例如 beta，不能是 latest）；响应 hint 列出完整规则。 TAG_INVALID：标签无效：预发布版本不能打 latest；tag 只能含 URL 安全字符（不含空格和 / ? #）；不能是版本号或范围；latest 不能删除。响应 hint 列出完整规则。 DEFINITION_INVALID：源码未通过定义校验。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 VERSION_EXISTS：版本号已存在且源码内容不同。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 DEFINITION_IDENTITY_MISMATCH：源码声明或运行语言与发布目标不一致。 NO_MATCHING_VERSION：没有满足标签、版本或范围的已发布版本。 CYCLE_DETECTED：发布后依赖会形成环（A 依赖 B、B 又依赖 A）；detail 给出环路径。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出脚本版本

按语义版本倒序分页列出不可变的 schema 和锁定依赖。默认不带源码；仅 expand=source 带完整源码，其它值返回 400。详情接口保持全文。

`GET /automation/v1/scripts/{ns}/{name}/versions`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 25。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: expand | `"source"` | 可选；仅接受 source；默认不带源码，其它值返回 400。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/versions" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.versions.list({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的脚本版本（默认不含源码，expand=source 才带），按 semver 降序排列。 |
| data[].id | `string` | 必填 / 必有；版本 ID，脚本前缀 scv_，工作流前缀 wfv_。 |
| data[].kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data[].version | `string` | 必填 / 必有；版本号（semver，已去掉 +build 元数据）。 |
| data[].digest | `string` | 必填 / 必有；源码与契约的内容摘要。 |
| data[].source | `string` | 可选；该版本的完整源码。版本列表默认不返回，需要时加 expand=source。 |
| data[].input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| data[].input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| data[].input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].output_schema | `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| data[].output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| data[].output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].references | `object[]` | 必填 / 必有；该版本依赖的动作、平台 API、脚本与工作流。脚本和工作流依赖在发布时锁定到精确版本。 |
| data[].references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| data[].references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| data[].references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| data[].references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| data[].outline | `null` / `object[]` | 必填 / 必有；工作流的步骤大纲（OutlineNode 数组），由解析器静态生成；脚本为 null。 |
| data[].outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| data[].outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| data[].outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| data[].outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| data[].outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| data[].outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| data[].outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| data[].outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| data[].outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| data[].outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| data[].outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| data[].outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| data[].outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| data[].outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| data[].sdk_version | `null` / `string` | 必填 / 必有；发布脚本所用的 SDK 版本；工作流为 null。 |
| data[].published_at | `string` | 必填 / 必有；发布时间（RFC 3339 UTC）。 |
| data[].published_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| data[].published_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].published_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[].deprecated | `null` / `string` | 必填 / 必有；弃用说明；未弃用为 null。弃用的版本仍可运行，但按范围或标签解析时优先选用未弃用的版本。 |
| data[].deprecated_at | `null` / `string` | 必填 / 必有；弃用时间（RFC 3339 UTC）；未弃用为 null。 |
| data[].deprecated_by | `null` / `object` | 必填 / 必有；执行弃用的主体；未弃用为 null。 |
| data[].deprecated_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].deprecated_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "scv_00mv67lza679fc5498438040079f0c5684208c4915",
      "kind": "script",
      "version": "1.0.0",
      "digest": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d",
      "input_schema": {
        "type": "object",
        "properties": {
          "n": {
            "type": "number"
          }
        },
        "required": [
          "n"
        ]
      },
      "output_schema": {
        "type": "object",
        "properties": {
          "answer": {
            "type": "number"
          }
        },
        "required": [
          "answer"
        ]
      },
      "references": [],
      "outline": null,
      "sdk_version": "0.1.0",
      "published_at": "2026-10-13T04:57:22.398Z",
      "published_by": {
        "type": "api_key",
        "id": "key_3e00b8984967"
      },
      "deprecated": null,
      "deprecated_at": null,
      "deprecated_by": null
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取脚本版本

读取精确版本的源码、输入输出契约及弃用说明；版本缺失返回 VERSION_NOT_FOUND。 详情始终返回完整源码。 version 接受精确版本或 dist-tag；range 返回 400，hint 提示改用 /resolve。

`GET /automation/v1/scripts/{ns}/{name}/versions/{version}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: version | `string` | 必填；精确版本或 dist-tag；不接受 range（400，带 hint）。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/versions/1.0.0" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.versions.retrieve({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME"),
    "version": "1.0.0"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；版本 ID，脚本前缀 scv_，工作流前缀 wfv_。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| version | `string` | 必填 / 必有；版本号（semver，已去掉 +build 元数据）。 |
| digest | `string` | 必填 / 必有；源码与契约的内容摘要。 |
| source | `string` | 必填 / 必有；该版本的完整源码。版本列表默认不返回，需要时加 expand=source。 |
| input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| references | `object[]` | 必填 / 必有；该版本依赖的动作、平台 API、脚本与工作流。脚本和工作流依赖在发布时锁定到精确版本。 |
| references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| outline | `null` / `object[]` | 必填 / 必有；工作流的步骤大纲（OutlineNode 数组），由解析器静态生成；脚本为 null。 |
| outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| sdk_version | `null` / `string` | 必填 / 必有；发布脚本所用的 SDK 版本；工作流为 null。 |
| published_at | `string` | 必填 / 必有；发布时间（RFC 3339 UTC）。 |
| published_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| published_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| published_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| deprecated | `null` / `string` | 必填 / 必有；弃用说明；未弃用为 null。弃用的版本仍可运行，但按范围或标签解析时优先选用未弃用的版本。 |
| deprecated_at | `null` / `string` | 必填 / 必有；弃用时间（RFC 3339 UTC）；未弃用为 null。 |
| deprecated_by | `null` / `object` | 必填 / 必有；执行弃用的主体；未弃用为 null。 |
| deprecated_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| deprecated_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "scv_00mv67lza679fc5498438040079f0c5684208c4915",
  "kind": "script",
  "version": "1.0.0",
  "digest": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d",
  "input_schema": {
    "type": "object",
    "properties": {
      "n": {
        "type": "number"
      }
    },
    "required": [
      "n"
    ]
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "answer": {
        "type": "number"
      }
    },
    "required": [
      "answer"
    ]
  },
  "references": [],
  "outline": null,
  "sdk_version": "0.1.0",
  "published_at": "2026-10-13T04:57:22.398Z",
  "published_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "deprecated": null,
  "deprecated_at": null,
  "deprecated_by": null,
  "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 弃用脚本版本

记录版本弃用说明；message 为空字符串时取消弃用，版本源码不变。

`POST /automation/v1/scripts/{ns}/{name}/versions/{version}/deprecate`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: version | `string` | 必填；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| message | `string` | 必填 / 必有；弃用说明；空字符串取消弃用。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/versions/1.0.0/deprecate" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "message": ""
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.versions.deprecate({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME"),
    "version": "1.0.0"
  },
  "body": {
    "message": ""
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；版本 ID，脚本前缀 scv_，工作流前缀 wfv_。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| version | `string` | 必填 / 必有；版本号（semver，已去掉 +build 元数据）。 |
| digest | `string` | 必填 / 必有；源码与契约的内容摘要。 |
| source | `string` | 必填 / 必有；该版本的完整源码。版本列表默认不返回，需要时加 expand=source。 |
| input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| references | `object[]` | 必填 / 必有；该版本依赖的动作、平台 API、脚本与工作流。脚本和工作流依赖在发布时锁定到精确版本。 |
| references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| outline | `null` / `object[]` | 必填 / 必有；工作流的步骤大纲（OutlineNode 数组），由解析器静态生成；脚本为 null。 |
| outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| sdk_version | `null` / `string` | 必填 / 必有；发布脚本所用的 SDK 版本；工作流为 null。 |
| published_at | `string` | 必填 / 必有；发布时间（RFC 3339 UTC）。 |
| published_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| published_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| published_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| deprecated | `null` / `string` | 必填 / 必有；弃用说明；未弃用为 null。弃用的版本仍可运行，但按范围或标签解析时优先选用未弃用的版本。 |
| deprecated_at | `null` / `string` | 必填 / 必有；弃用时间（RFC 3339 UTC）；未弃用为 null。 |
| deprecated_by | `null` / `object` | 必填 / 必有；执行弃用的主体；未弃用为 null。 |
| deprecated_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| deprecated_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "scv_00mv67lza679fc5498438040079f0c5684208c4915",
  "kind": "script",
  "version": "1.0.0",
  "digest": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d",
  "input_schema": {
    "type": "object",
    "properties": {
      "n": {
        "type": "number"
      }
    },
    "required": [
      "n"
    ]
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "answer": {
        "type": "number"
      }
    },
    "required": [
      "answer"
    ]
  },
  "references": [],
  "outline": null,
  "sdk_version": "0.1.0",
  "published_at": "2026-10-13T04:57:22.398Z",
  "published_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "deprecated": null,
  "deprecated_at": null,
  "deprecated_by": null,
  "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出脚本标签

读取发布标签指向的精确版本。同时返回更新时间和更新者。

`GET /automation/v1/scripts/{ns}/{name}/dist-tags`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/dist-tags" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.distTags.list({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| .*.version | `string` | 必填 / 必有；标签当前指向的精确版本号。 |
| .*.updated_at | `string` | 必填 / 必有；标签最近一次移动的时间（RFC 3339 UTC）。 |
| .*.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| .*.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| .*.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "latest": {
    "version": "1.0.0",
    "updated_at": "2026-10-13T04:57:22.398Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 设置脚本标签

将发布标签指向已有精确版本，标签不能是版本号或版本范围；移动 latest 可用于回滚，工作流会同步定时触发器。

`PUT /automation/v1/scripts/{ns}/{name}/dist-tags/{tag}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: tag | `string` | 必填；发布标签。预发布版本（如 1.3.0-beta.1）必须带 tag 且不能是 latest；tag 只能由 URL 安全字符组成（字母、数字及 - _ . ! ~ * ' ( )），不含空格和 / ? #，首尾无空白；不能是版本号或版本范围（如 1.2.3、^1、1.x、*）；beta、next、debug 等其余名称均可。违规返回 TAG_INVALID 或 TAG_REQUIRED，hint 给出完整规则。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| version | `string` | 必填 / 必有；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X PUT "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/dist-tags/sample" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "version": "1.0.0"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.distTags.set({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME"),
    "tag": "sample"
  },
  "body": {
    "version": "1.0.0"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| .*.version | `string` | 必填 / 必有；标签当前指向的精确版本号。 |
| .*.updated_at | `string` | 必填 / 必有；标签最近一次移动的时间（RFC 3339 UTC）。 |
| .*.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| .*.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| .*.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "latest": {
    "version": "1.0.0",
    "updated_at": "2026-10-13T04:57:22.398Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  },
  "sample": {
    "version": "1.0.0",
    "updated_at": "2026-10-13T04:57:26.232Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 TAG_INVALID：标签无效：预发布版本不能打 latest；tag 只能含 URL 安全字符（不含空格和 / ? #）；不能是版本号或范围；latest 不能删除。响应 hint 列出完整规则。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 删除脚本标签

删除发布标签但保留版本；latest 不可删除，标签不能是版本号或范围，不存在的合法标签可重复删除。

`DELETE /automation/v1/scripts/{ns}/{name}/dist-tags/{tag}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: tag | `string` | 必填；发布标签。预发布版本（如 1.3.0-beta.1）必须带 tag 且不能是 latest；tag 只能由 URL 安全字符组成（字母、数字及 - _ . ! ~ * ' ( )），不含空格和 / ? #，首尾无空白；不能是版本号或版本范围（如 1.2.3、^1、1.x、*）；beta、next、debug 等其余名称均可。违规返回 TAG_INVALID 或 TAG_REQUIRED，hint 给出完整规则。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| SCRIPT_NAME | [创建脚本返回的 name](/docs/api/native/automation/createScript) |

```bash
: "${SCRIPT_NAME:?Set SCRIPT_NAME}"
curl --fail-with-body -X DELETE "https://api.deepraxis.ai/automation/v1/scripts/docs-samples/${SCRIPT_NAME}/dist-tags/sample" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.scripts.distTags.delete({
  "path": {
    "ns": "docs-samples",
    "name": env("SCRIPT_NAME"),
    "tag": "sample"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| .*.version | `string` | 必填 / 必有；标签当前指向的精确版本号。 |
| .*.updated_at | `string` | 必填 / 必有；标签最近一次移动的时间（RFC 3339 UTC）。 |
| .*.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| .*.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| .*.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "latest": {
    "version": "1.0.0",
    "updated_at": "2026-10-13T04:57:22.398Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 TAG_INVALID：标签无效：预发布版本不能打 latest；tag 只能含 URL 安全字符（不含空格和 / ? #）；不能是版本号或范围；latest 不能删除。响应 hint 列出完整规则。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出工作流

列出可见工作流的摘要、最新版本、标签及近七天统计；默认排除已归档条目。

`GET /automation/v1/workflows`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 25。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: q | `string` | 可选；不区分大小写，按名称或说明的字面子串匹配；% 与 _ 无通配含义。 |
| query: namespace | `string[]` | 可选；仅返回指定命名空间的定义，名称按小写匹配。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: scope | `"platform"` / `"own"[]` | 可选；platform 仅平台定义，own 仅租户自建定义；省略返回两者。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: archived | `boolean` | 可选；true 仅已归档，false 仅未归档；默认 false。 |
| query: labels | `object` | 可选；按标签过滤，使用 labels[k]=v；同键逗号多值取任一，不同键同时满足。 |
| query: created_at[gte] | `string` | 可选；创建时间下界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |
| query: created_at[lte] | `string` | 可选；创建时间上界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/workflows" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  --get \
  --data-urlencode "namespace=docs-samples" \
  --data-urlencode "limit=1"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.list({
  "query": {
    "namespace": [
      "docs-samples"
    ],
    "limit": 1
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的工作流摘要，按 created_at 倒序、id 倒序排列。 |
| data[].id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| data[].kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data[].namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| data[].name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| data[].description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| data[].labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| data[].owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| data[].latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| data[].latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| data[].latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| data[].dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| data[].draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| data[].latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| data[].latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| data[].latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| data[].latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| data[].latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| data[].latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| data[].latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| data[].latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| data[].latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| data[].latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| data[].latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| data[].latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| data[].latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| data[].latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| data[].latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| data[].latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| data[].latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| data[].latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| data[].latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| data[].stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| data[].stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| data[].stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| data[].archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| data[].created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| data[].updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "wf_00mv67m4jad0d5c2a3d1e04dc9ac4c18cff616eca7",
      "owner": "tnt_3a9759864ccb4e00",
      "kind": "workflow",
      "namespace": "docs-samples",
      "name": "sample-workflows-1791867412840-b05e8a",
      "description": "",
      "labels": {},
      "latest_version": null,
      "dist_tags": {},
      "draft_changed": true,
      "latest_run": null,
      "stats_7d": {
        "runs": 0,
        "failures": 0
      },
      "archived_at": null,
      "created_at": "2026-10-13T04:57:29.206Z",
      "updated_at": "2026-10-13T04:57:29.206Z"
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 创建工作流

创建工作流及可编辑草稿，不会发布或启动运行；脚本与工作流共用名称空间，同租户重名返回 NAME_TAKEN。 run.workflow 支持 ns/name@range 或 {namespace, name, version, input}；run.script 使用相同引用形状（平台扩展）。 对象的 namespace、name、version 必填；version 支持精确版本、dist-tag 或范围，发布时锁定依赖。 对象 input 默认为 {}，支持表达式；字符串引用继续使用任务级 with。run.await 默认 true，等待子运行输出； false 以 detach 创建子运行，任务立即输出 {run_id}，父取消不级联。内联 script.code 返回 DEFINITION_INVALID， detail 提示「请先保存为脚本再引用」。raise.error 的 type URI、status、title、detail 保留到运行错误。

`POST /automation/v1/workflows`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| namespace | `string` | 必填 / 必有；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 pattern: "^[a-zA-Z0-9][a-zA-Z0-9._-]&#123;0,63&#125;$" |
| name | `string` | 必填 / 必有；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 pattern: "^[a-zA-Z0-9][a-zA-Z0-9._-]&#123;0,63&#125;$" |
| description | `string` | 可选；说明，最多 1000 个字符。 maxLength: 1000 |
| draft | `string` | 可选；可编辑源码；脚本为 TypeScript，工作流为 YAML。创建时省略为空字符串。 |
| labels | `object` | 可选；最多 50 个标签；键为 1–40 个字符，值最多 500 个字符。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/workflows" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "namespace": "docs-samples",
  "name": "sample-workflows",
  "draft": "document:\n  dsl: '\''1.0.3'\''\n  namespace: docs-samples\n  name: sample-workflows\n  version: '\''1.0.0'\''\ndo:\n  - answer:\n      set:\n        answer: 42\n"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.create({
  "body": {
    "namespace": "docs-samples",
    "name": "sample-workflows",
    "draft": "document:\n  dsl: '1.0.3'\n  namespace: docs-samples\n  name: sample-workflows\n  version: '1.0.0'\ndo:\n  - answer:\n      set:\n        answer: 42\n"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| draft | `object` | 必填 / 必有；脚本或工作流的可编辑草稿；发布版本时以草稿或某次运行的源码为准。 不接受额外字段。 |
| draft.source | `string` | 必填 / 必有；草稿源码：脚本为 TypeScript，工作流为 YAML。 |
| draft.revision | `string` | 必填 / 必有；草稿修订标识（ETag），发布时作为 expected_draft_revision，更新草稿时作为 If-Match；与当前不一致返回 412。 |
| draft.updated_at | `string` | 必填 / 必有；草稿最近一次修改的时间（RFC 3339 UTC）。 |
| draft.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| draft.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| draft.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wf_00mv67m4jad0d5c2a3d1e04dc9ac4c18cff616eca7",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "workflow",
  "namespace": "docs-samples",
  "name": "sample-workflows-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "latest_version": null,
  "dist_tags": {},
  "draft_changed": true,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:29.206Z",
  "updated_at": "2026-10-13T04:57:29.206Z",
  "draft": {
    "source": "document:\n  dsl: '1.0.3'\n  namespace: docs-samples\n  name: sample-workflows-1791867412840-b05e8a\n  version: '1.0.0'\ndo:\n  - answer:\n      set:\n        answer: 42\n",
    "revision": "draft_00mv67m4ja0e38625d463646e3a526bb774bf453ee",
    "updated_at": "2026-10-13T04:57:29.206Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 NAME_TAKEN：名称已被同一租户占用。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取工作流

读取工作流详情及草稿源码；ETag 是草稿修订，可作为修改请求的 If-Match。

`GET /automation/v1/workflows/{ns}/{name}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.retrieve({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| ETag | `string` | Current resource revision for conditional updates. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| draft | `object` | 必填 / 必有；脚本或工作流的可编辑草稿；发布版本时以草稿或某次运行的源码为准。 不接受额外字段。 |
| draft.source | `string` | 必填 / 必有；草稿源码：脚本为 TypeScript，工作流为 YAML。 |
| draft.revision | `string` | 必填 / 必有；草稿修订标识（ETag），发布时作为 expected_draft_revision，更新草稿时作为 If-Match；与当前不一致返回 412。 |
| draft.updated_at | `string` | 必填 / 必有；草稿最近一次修改的时间（RFC 3339 UTC）。 |
| draft.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| draft.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| draft.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wf_00mv67m4jad0d5c2a3d1e04dc9ac4c18cff616eca7",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "workflow",
  "namespace": "docs-samples",
  "name": "sample-workflows-1791867412840-b05e8a",
  "description": "",
  "labels": {},
  "latest_version": null,
  "dist_tags": {},
  "draft_changed": true,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:29.206Z",
  "updated_at": "2026-10-13T04:57:29.206Z",
  "draft": {
    "source": "document:\n  dsl: '1.0.3'\n  namespace: docs-samples\n  name: sample-workflows-1791867412840-b05e8a\n  version: '1.0.0'\ndo:\n  - answer:\n      set:\n        answer: 42\n",
    "revision": "draft_00mv67m4ja0e38625d463646e3a526bb774bf453ee",
    "updated_at": "2026-10-13T04:57:29.206Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 更新工作流草稿

修改说明、标签或草稿，必须携带与当前草稿匹配的 If-Match；即使只改元数据也会生成新的草稿修订。

`PATCH /automation/v1/workflows/{ns}/{name}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| header: If-Match | `string` | 必填；当前资源的 ETag，可直接使用对象里的 draft.revision 或 etag 字段值：裸值、带双引号或弱校验写法 W/"…" 均接受（RFC 7232 弱比较）；缺失返回 400，修订不匹配返回 412。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| description | `string` | 可选；说明，最多 1000 个字符。 maxLength: 1000 |
| labels | `object` | 可选；最多 50 个标签；键为 1–40 个字符，值最多 500 个字符。 |
| draft | `string` | 可选；可编辑源码；脚本为 TypeScript，工作流为 YAML。创建时省略为空字符串。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |
| ETAG | [最新 GET 响应头 ETag（保留引号）](/docs/api/native/automation/getWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
: "${ETAG:?Set ETAG}"
curl --fail-with-body -X PATCH "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "If-Match: ${ETAG}" \
  -H "Content-Type: application/json" \
  --data '{
  "description": "Sample definition",
  "draft": "document:\n  dsl: '\''1.0.3'\''\n  namespace: docs-samples\n  name: sample-workflows-1791867412840-b05e8a\n  version: '\''1.0.0'\''\ndo:\n  - answer:\n      set:\n        answer: 42\n"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.update({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME")
  },
  "headers": {
    "If-Match": env("ETAG")
  },
  "body": {
    "description": "Sample definition",
    "draft": "document:\n  dsl: '1.0.3'\n  namespace: docs-samples\n  name: sample-workflows-1791867412840-b05e8a\n  version: '1.0.0'\ndo:\n  - answer:\n      set:\n        answer: 42\n"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| draft | `object` | 必填 / 必有；脚本或工作流的可编辑草稿；发布版本时以草稿或某次运行的源码为准。 不接受额外字段。 |
| draft.source | `string` | 必填 / 必有；草稿源码：脚本为 TypeScript，工作流为 YAML。 |
| draft.revision | `string` | 必填 / 必有；草稿修订标识（ETag），发布时作为 expected_draft_revision，更新草稿时作为 If-Match；与当前不一致返回 412。 |
| draft.updated_at | `string` | 必填 / 必有；草稿最近一次修改的时间（RFC 3339 UTC）。 |
| draft.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| draft.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| draft.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wf_00mv67m4jad0d5c2a3d1e04dc9ac4c18cff616eca7",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "workflow",
  "namespace": "docs-samples",
  "name": "sample-workflows-1791867412840-b05e8a",
  "description": "Sample definition",
  "labels": {},
  "latest_version": null,
  "dist_tags": {},
  "draft_changed": true,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:29.206Z",
  "updated_at": "2026-10-13T04:57:31.570Z",
  "draft": {
    "source": "document:\n  dsl: '1.0.3'\n  namespace: docs-samples\n  name: sample-workflows-1791867412840-b05e8a\n  version: '1.0.0'\ndo:\n  - answer:\n      set:\n        answer: 42\n",
    "revision": "draft_00mv67m4ja0e38625d463646e3a526bb774bf453ee",
    "updated_at": "2026-10-13T04:57:29.206Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 归档工作流

归档后保留名称、版本和草稿；默认列表隐藏该条目，新的目标解析和运行请求拒绝已归档目标。

`POST /automation/v1/workflows/{ns}/{name}/archive`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

### application/json [#applicationjson]

不接受额外字段。
object

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/archive" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.archive({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wf_00mv67m4jad0d5c2a3d1e04dc9ac4c18cff616eca7",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "workflow",
  "namespace": "docs-samples",
  "name": "sample-workflows-1791867412840-b05e8a",
  "description": "Sample definition",
  "labels": {},
  "latest_version": {
    "version": "1.0.0",
    "published_at": "2026-10-13T04:57:32.297Z"
  },
  "dist_tags": {
    "latest": "1.0.0"
  },
  "draft_changed": false,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": "2026-10-13T04:57:37.671Z",
  "created_at": "2026-10-13T04:57:29.206Z",
  "updated_at": "2026-10-13T04:57:37.671Z"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 恢复工作流

恢复已归档定义，保留版本和标签。名称无需重新分配。

`POST /automation/v1/workflows/{ns}/{name}/restore`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

### application/json [#applicationjson]

不接受额外字段。
object

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/restore" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.restore({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；编排 ID，脚本前缀 scr_，工作流前缀 wf_；日常使用 namespace 与 name。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；命名空间，引用形如 namespace/name@版本。 |
| name | `string` | 必填 / 必有；名字，与 namespace 一起在租户内唯一，脚本与工作流共用命名空间，重名返回 409 NAME_TAKEN。 |
| description | `string` | 必填 / 必有；说明文字，最多 1000 字符。 |
| labels | `object` | 必填 / 必有；用户自定义标签：字符串键值对，用于分类与列表过滤（labels[key]=value）；键不能以 praxis. 开头。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| latest_version | `null` / `object` | 必填 / 必有；latest 标签指向的已发布版本 &#123;version, published_at&#125;；尚未发布为 null。 |
| latest_version（分支2).version | `string` | 必填 / 必有；最新发布版本的版本号（semver）。 |
| latest_version（分支2).published_at | `string` | 必填 / 必有；该版本的发布时间（RFC 3339 UTC）。 |
| dist_tags | `object` | 必填 / 必有；标签到精确版本号的映射，例如 latest 指向 1.2.0；用 ns/name@标签 运行时按此解析。 |
| draft_changed | `boolean` | 必填 / 必有；true 表示草稿内容（摘要）不同于 latest 版本，即有未发布的改动。 |
| latest_run | `null` / `object` | 必填 / 必有；该编排最近一次运行的摘要；还没有运行为 null。 |
| latest_run（分支2).id | `string` | 必填 / 必有；运行 ID（run_ 前缀），可用于 runs.retrieve。 |
| latest_run（分支2).number | `null` / `number` | 必填 / 必有；运行在该脚本或工作流内的递增序号。 |
| latest_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| latest_run（分支2).created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait | `null` / `object` | 必填 / 必有；当前未完成的等待点；没有等待为 null。 |
| latest_run（分支2).current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| latest_run（分支2).current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| latest_run（分支2).current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| latest_run（分支2).current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| latest_run（分支2).current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| latest_run（分支2).current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| latest_run（分支2).current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| latest_run（分支2).current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| latest_run（分支2).current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| latest_run（分支2).current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| latest_run（分支2).current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| stats_7d | `object` | 必填 / 必有；近七天的运行统计：按运行结束日期累计，在运行结束时更新，读取时不扫描运行。 不接受额外字段。 |
| stats_7d.runs | `number` | 必填 / 必有；近七天内结束的运行总数（任意终态）。 |
| stats_7d.failures | `number` | 必填 / 必有；其中以 faulted 结束的运行数。 |
| archived_at | `null` / `string` | 必填 / 必有；归档时间；未归档为 null。归档后名字保留，不可复用。 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wf_00mv67m4jad0d5c2a3d1e04dc9ac4c18cff616eca7",
  "owner": "tnt_3a9759864ccb4e00",
  "kind": "workflow",
  "namespace": "docs-samples",
  "name": "sample-workflows-1791867412840-b05e8a",
  "description": "Sample definition",
  "labels": {},
  "latest_version": {
    "version": "1.0.0",
    "published_at": "2026-10-13T04:57:32.297Z"
  },
  "dist_tags": {
    "latest": "1.0.0"
  },
  "draft_changed": false,
  "latest_run": null,
  "stats_7d": {
    "runs": 0,
    "failures": 0
  },
  "archived_at": null,
  "created_at": "2026-10-13T04:57:29.206Z",
  "updated_at": "2026-10-13T04:57:38.354Z"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 发布工作流版本

从草稿或临时运行源码发布版本，校验定义并锁定依赖。草稿须匹配 expected_draft_revision；临时运行由 from_run 与 expected_source_sha256 指定。版本相同且内容相同返回已有版本，内容不同返回 VERSION_EXISTS；预发布版本必须显式带 tag（不能是 latest，tag 只能含 URL 安全字符且不能是版本号或范围，违规返回 TAG_REQUIRED 或 TAG_INVALID，hint 给出完整规则），校验不通过返回 DEFINITION_INVALID。稳定版本仅高于已有最高稳定版本时自动移动 latest；工作流成为 latest 时同步定义中的定时触发器。run.workflow/run.script 的字符串与对象引用使用相同版本解析和依赖锁定规则。 发布会去掉版本号的 +build 元数据。

`POST /automation/v1/workflows/{ns}/{name}/versions`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

### application/json [#applicationjson]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| （分支1).version | `string` | 必填 / 必有；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 |
| （分支1).expected_draft_revision | `string` | 必填 / 必有；发布的草稿修订，必须匹配当前草稿；与 from_run 发布方式二选一。 |
| （分支1).tag | `string` | 可选；发布标签。预发布版本（如 1.3.0-beta.1）必须带 tag 且不能是 latest；tag 只能由 URL 安全字符组成（字母、数字及 - _ . ! ~ * ' ( )），不含空格和 / ? #，首尾无空白；不能是版本号或版本范围（如 1.2.3、^1、1.x、*）；beta、next、debug 等其余名称均可。违规返回 TAG_INVALID 或 TAG_REQUIRED，hint 给出完整规则。 |
| （分支2).version | `string` | 必填 / 必有；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 |
| （分支2).from_run | `string` | 必填 / 必有；提供源码快照的临时运行 ID；已发布目标的运行当前没有可用于此入口的快照。须同时给出 expected_source_sha256，不能同时给 expected_draft_revision。 |
| （分支2).expected_source_sha256 | `string` | 必填 / 必有；运行源码的 SHA-256 摘要，必须与快照匹配。 |
| （分支2).tag | `string` | 可选；发布标签。预发布版本（如 1.3.0-beta.1）必须带 tag 且不能是 latest；tag 只能由 URL 安全字符组成（字母、数字及 - _ . ! ~ * ' ( )），不含空格和 / ? #，首尾无空白；不能是版本号或版本范围（如 1.2.3、^1、1.x、*）；beta、next、debug 等其余名称均可。违规返回 TAG_INVALID 或 TAG_REQUIRED，hint 给出完整规则。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |
| DRAFT_REVISION | [当前 draft.revision](/docs/api/native/automation/getWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
: "${DRAFT_REVISION:?Set DRAFT_REVISION}"
BODY=$(jq -n --arg DRAFT_REVISION "$DRAFT_REVISION" '{
  "version": "1.0.0",
  "expected_draft_revision": $DRAFT_REVISION
}')
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/versions" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data "$BODY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.versions.publish({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME")
  },
  "body": {
    "version": "1.0.0",
    "expected_draft_revision": env("DRAFT_REVISION")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；版本 ID，脚本前缀 scv_，工作流前缀 wfv_。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| version | `string` | 必填 / 必有；版本号（semver，已去掉 +build 元数据）。 |
| digest | `string` | 必填 / 必有；源码与契约的内容摘要。 |
| source | `string` | 必填 / 必有；该版本的完整源码。版本列表默认不返回，需要时加 expand=source。 |
| input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| references | `object[]` | 必填 / 必有；该版本依赖的动作、平台 API、脚本与工作流。脚本和工作流依赖在发布时锁定到精确版本。 |
| references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| outline | `null` / `object[]` | 必填 / 必有；工作流的步骤大纲（OutlineNode 数组），由解析器静态生成；脚本为 null。 |
| outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| sdk_version | `null` / `string` | 必填 / 必有；发布脚本所用的 SDK 版本；工作流为 null。 |
| published_at | `string` | 必填 / 必有；发布时间（RFC 3339 UTC）。 |
| published_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| published_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| published_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| deprecated | `null` / `string` | 必填 / 必有；弃用说明；未弃用为 null。弃用的版本仍可运行，但按范围或标签解析时优先选用未弃用的版本。 |
| deprecated_at | `null` / `string` | 必填 / 必有；弃用时间（RFC 3339 UTC）；未弃用为 null。 |
| deprecated_by | `null` / `object` | 必填 / 必有；执行弃用的主体；未弃用为 null。 |
| deprecated_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| deprecated_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wfv_00mv67m6x5409408c354944fa8a960d207eb33c297",
  "kind": "workflow",
  "version": "1.0.0",
  "digest": "ea7352d51087eca0113ee82230848ce1506fd97d27aad4c7b1911e5c4ef9b5fb",
  "input_schema": {},
  "output_schema": {},
  "references": [],
  "outline": [
    {
      "name": "answer",
      "reference": "/do/0/answer",
      "kind": "set"
    }
  ],
  "sdk_version": null,
  "published_at": "2026-10-13T04:57:32.297Z",
  "published_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "deprecated": null,
  "deprecated_at": null,
  "deprecated_by": null,
  "source": "document:\n  dsl: '1.0.3'\n  namespace: docs-samples\n  name: sample-workflows-1791867412840-b05e8a\n  version: '1.0.0'\ndo:\n  - answer:\n      set:\n        answer: 42\n"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 TAG_REQUIRED：预发布版本必须显式指定发布标签（例如 beta，不能是 latest）；响应 hint 列出完整规则。 TAG_INVALID：标签无效：预发布版本不能打 latest；tag 只能含 URL 安全字符（不含空格和 / ? #）；不能是版本号或范围；latest 不能删除。响应 hint 列出完整规则。 DEFINITION_INVALID：源码未通过定义校验。 INPUT_INVALID：输入不满足目标契约或业务校验。 SCHEDULE_INVALID：定时规则或时间边界无效。 TIMEZONE_INVALID：时区不是有效的 IANA 时区。 INTERVAL_TOO_SHORT：定时间隔短于一分钟。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 VERSION_EXISTS：版本号已存在且源码内容不同。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 DEFINITION_IDENTITY_MISMATCH：源码声明或运行语言与发布目标不一致。 NO_MATCHING_VERSION：没有满足标签、版本或范围的已发布版本。 CYCLE_DETECTED：发布后依赖会形成环（A 依赖 B、B 又依赖 A）；detail 给出环路径。 |
| 429 | TRIGGER_LIMIT：租户已达到 100 个启用触发器的上限。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出工作流版本

按语义版本倒序分页列出不可变的 schema 和锁定依赖。默认不带源码；仅 expand=source 带完整源码，其它值返回 400。详情接口保持全文。

`GET /automation/v1/workflows/{ns}/{name}/versions`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 25。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: expand | `"source"` | 可选；仅接受 source；默认不带源码，其它值返回 400。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/versions" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.versions.list({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的工作流版本（默认不含源码，expand=source 才带），按 semver 降序排列。 |
| data[].id | `string` | 必填 / 必有；版本 ID，脚本前缀 scv_，工作流前缀 wfv_。 |
| data[].kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data[].version | `string` | 必填 / 必有；版本号（semver，已去掉 +build 元数据）。 |
| data[].digest | `string` | 必填 / 必有；源码与契约的内容摘要。 |
| data[].source | `string` | 可选；该版本的完整源码。版本列表默认不返回，需要时加 expand=source。 |
| data[].input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| data[].input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| data[].input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].output_schema | `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| data[].output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| data[].output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].references | `object[]` | 必填 / 必有；该版本依赖的动作、平台 API、脚本与工作流。脚本和工作流依赖在发布时锁定到精确版本。 |
| data[].references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| data[].references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| data[].references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| data[].references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| data[].outline | `null` / `object[]` | 必填 / 必有；工作流的步骤大纲（OutlineNode 数组），由解析器静态生成；脚本为 null。 |
| data[].outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| data[].outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| data[].outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| data[].outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| data[].outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| data[].outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| data[].outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| data[].outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| data[].outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| data[].outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| data[].outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| data[].outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| data[].outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| data[].outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| data[].sdk_version | `null` / `string` | 必填 / 必有；发布脚本所用的 SDK 版本；工作流为 null。 |
| data[].published_at | `string` | 必填 / 必有；发布时间（RFC 3339 UTC）。 |
| data[].published_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| data[].published_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].published_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[].deprecated | `null` / `string` | 必填 / 必有；弃用说明；未弃用为 null。弃用的版本仍可运行，但按范围或标签解析时优先选用未弃用的版本。 |
| data[].deprecated_at | `null` / `string` | 必填 / 必有；弃用时间（RFC 3339 UTC）；未弃用为 null。 |
| data[].deprecated_by | `null` / `object` | 必填 / 必有；执行弃用的主体；未弃用为 null。 |
| data[].deprecated_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].deprecated_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "wfv_00mv67m6x5409408c354944fa8a960d207eb33c297",
      "kind": "workflow",
      "version": "1.0.0",
      "digest": "ea7352d51087eca0113ee82230848ce1506fd97d27aad4c7b1911e5c4ef9b5fb",
      "input_schema": {},
      "output_schema": {},
      "references": [],
      "outline": [
        {
          "name": "answer",
          "reference": "/do/0/answer",
          "kind": "set"
        }
      ],
      "sdk_version": null,
      "published_at": "2026-10-13T04:57:32.297Z",
      "published_by": {
        "type": "api_key",
        "id": "key_3e00b8984967"
      },
      "deprecated": null,
      "deprecated_at": null,
      "deprecated_by": null
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取工作流版本

读取精确版本的源码、输入输出契约及弃用说明；版本缺失返回 VERSION_NOT_FOUND。 详情始终返回完整源码。 version 接受精确版本或 dist-tag；range 返回 400，hint 提示改用 /resolve。

`GET /automation/v1/workflows/{ns}/{name}/versions/{version}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: version | `string` | 必填；精确版本或 dist-tag；不接受 range（400，带 hint）。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/versions/1.0.0" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.versions.retrieve({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME"),
    "version": "1.0.0"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；版本 ID，脚本前缀 scv_，工作流前缀 wfv_。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| version | `string` | 必填 / 必有；版本号（semver，已去掉 +build 元数据）。 |
| digest | `string` | 必填 / 必有；源码与契约的内容摘要。 |
| source | `string` | 必填 / 必有；该版本的完整源码。版本列表默认不返回，需要时加 expand=source。 |
| input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| references | `object[]` | 必填 / 必有；该版本依赖的动作、平台 API、脚本与工作流。脚本和工作流依赖在发布时锁定到精确版本。 |
| references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| outline | `null` / `object[]` | 必填 / 必有；工作流的步骤大纲（OutlineNode 数组），由解析器静态生成；脚本为 null。 |
| outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| sdk_version | `null` / `string` | 必填 / 必有；发布脚本所用的 SDK 版本；工作流为 null。 |
| published_at | `string` | 必填 / 必有；发布时间（RFC 3339 UTC）。 |
| published_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| published_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| published_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| deprecated | `null` / `string` | 必填 / 必有；弃用说明；未弃用为 null。弃用的版本仍可运行，但按范围或标签解析时优先选用未弃用的版本。 |
| deprecated_at | `null` / `string` | 必填 / 必有；弃用时间（RFC 3339 UTC）；未弃用为 null。 |
| deprecated_by | `null` / `object` | 必填 / 必有；执行弃用的主体；未弃用为 null。 |
| deprecated_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| deprecated_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wfv_00mv67m6x5409408c354944fa8a960d207eb33c297",
  "kind": "workflow",
  "version": "1.0.0",
  "digest": "ea7352d51087eca0113ee82230848ce1506fd97d27aad4c7b1911e5c4ef9b5fb",
  "input_schema": {},
  "output_schema": {},
  "references": [],
  "outline": [
    {
      "name": "answer",
      "reference": "/do/0/answer",
      "kind": "set"
    }
  ],
  "sdk_version": null,
  "published_at": "2026-10-13T04:57:32.297Z",
  "published_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "deprecated": null,
  "deprecated_at": null,
  "deprecated_by": null,
  "source": "document:\n  dsl: '1.0.3'\n  namespace: docs-samples\n  name: sample-workflows-1791867412840-b05e8a\n  version: '1.0.0'\ndo:\n  - answer:\n      set:\n        answer: 42\n"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 弃用工作流版本

记录版本弃用说明；message 为空字符串时取消弃用，版本源码不变。

`POST /automation/v1/workflows/{ns}/{name}/versions/{version}/deprecate`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: version | `string` | 必填；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| message | `string` | 必填 / 必有；弃用说明；空字符串取消弃用。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/versions/1.0.0/deprecate" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "message": ""
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.versions.deprecate({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME"),
    "version": "1.0.0"
  },
  "body": {
    "message": ""
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；版本 ID，脚本前缀 scv_，工作流前缀 wfv_。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| version | `string` | 必填 / 必有；版本号（semver，已去掉 +build 元数据）。 |
| digest | `string` | 必填 / 必有；源码与契约的内容摘要。 |
| source | `string` | 必填 / 必有；该版本的完整源码。版本列表默认不返回，需要时加 expand=source。 |
| input_schema | `object` | 必填 / 必有；任意 JSON 对象（键为字符串，值为任意 JSON 值）。 |
| input_schema.*（分支5) | `object` | 递归 JSON 值。 |
| input_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| output_schema.*（分支5) | `object` | 递归 JSON 值。 |
| output_schema.*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| references | `object[]` | 必填 / 必有；该版本依赖的动作、平台 API、脚本与工作流。脚本和工作流依赖在发布时锁定到精确版本。 |
| references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| outline | `null` / `object[]` | 必填 / 必有；工作流的步骤大纲（OutlineNode 数组），由解析器静态生成；脚本为 null。 |
| outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| sdk_version | `null` / `string` | 必填 / 必有；发布脚本所用的 SDK 版本；工作流为 null。 |
| published_at | `string` | 必填 / 必有；发布时间（RFC 3339 UTC）。 |
| published_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| published_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| published_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| deprecated | `null` / `string` | 必填 / 必有；弃用说明；未弃用为 null。弃用的版本仍可运行，但按范围或标签解析时优先选用未弃用的版本。 |
| deprecated_at | `null` / `string` | 必填 / 必有；弃用时间（RFC 3339 UTC）；未弃用为 null。 |
| deprecated_by | `null` / `object` | 必填 / 必有；执行弃用的主体；未弃用为 null。 |
| deprecated_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| deprecated_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wfv_00mv67m6x5409408c354944fa8a960d207eb33c297",
  "kind": "workflow",
  "version": "1.0.0",
  "digest": "ea7352d51087eca0113ee82230848ce1506fd97d27aad4c7b1911e5c4ef9b5fb",
  "input_schema": {},
  "output_schema": {},
  "references": [],
  "outline": [
    {
      "name": "answer",
      "reference": "/do/0/answer",
      "kind": "set"
    }
  ],
  "sdk_version": null,
  "published_at": "2026-10-13T04:57:32.297Z",
  "published_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "deprecated": null,
  "deprecated_at": null,
  "deprecated_by": null,
  "source": "document:\n  dsl: '1.0.3'\n  namespace: docs-samples\n  name: sample-workflows-1791867412840-b05e8a\n  version: '1.0.0'\ndo:\n  - answer:\n      set:\n        answer: 42\n"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出工作流标签

读取发布标签指向的精确版本。同时返回更新时间和更新者。

`GET /automation/v1/workflows/{ns}/{name}/dist-tags`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/dist-tags" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.distTags.list({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| .*.version | `string` | 必填 / 必有；标签当前指向的精确版本号。 |
| .*.updated_at | `string` | 必填 / 必有；标签最近一次移动的时间（RFC 3339 UTC）。 |
| .*.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| .*.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| .*.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "latest": {
    "version": "1.0.0",
    "updated_at": "2026-10-13T04:57:32.297Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 设置工作流标签

将发布标签指向已有精确版本，标签不能是版本号或版本范围；移动 latest 可用于回滚，工作流会同步定时触发器。

`PUT /automation/v1/workflows/{ns}/{name}/dist-tags/{tag}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: tag | `string` | 必填；发布标签。预发布版本（如 1.3.0-beta.1）必须带 tag 且不能是 latest；tag 只能由 URL 安全字符组成（字母、数字及 - _ . ! ~ * ' ( )），不含空格和 / ? #，首尾无空白；不能是版本号或版本范围（如 1.2.3、^1、1.x、*）；beta、next、debug 等其余名称均可。违规返回 TAG_INVALID 或 TAG_REQUIRED，hint 给出完整规则。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| version | `string` | 必填 / 必有；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X PUT "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/dist-tags/sample" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "version": "1.0.0"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.distTags.set({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME"),
    "tag": "sample"
  },
  "body": {
    "version": "1.0.0"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| .*.version | `string` | 必填 / 必有；标签当前指向的精确版本号。 |
| .*.updated_at | `string` | 必填 / 必有；标签最近一次移动的时间（RFC 3339 UTC）。 |
| .*.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| .*.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| .*.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "latest": {
    "version": "1.0.0",
    "updated_at": "2026-10-13T04:57:32.297Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  },
  "sample": {
    "version": "1.0.0",
    "updated_at": "2026-10-13T04:57:36.329Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 TAG_INVALID：标签无效：预发布版本不能打 latest；tag 只能含 URL 安全字符（不含空格和 / ? #）；不能是版本号或范围；latest 不能删除。响应 hint 列出完整规则。 INPUT_INVALID：输入不满足目标契约或业务校验。 SCHEDULE_INVALID：定时规则或时间边界无效。 TIMEZONE_INVALID：时区不是有效的 IANA 时区。 INTERVAL_TOO_SHORT：定时间隔短于一分钟。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 429 | TRIGGER_LIMIT：租户已达到 100 个启用触发器的上限。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 删除工作流标签

删除发布标签但保留版本；latest 不可删除，标签不能是版本号或范围，不存在的合法标签可重复删除。

`DELETE /automation/v1/workflows/{ns}/{name}/dist-tags/{tag}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: ns | `string` | 必填；命名空间，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;；praxis 只读。 |
| path: name | `string` | 必填；名称，存储前转为小写，格式 [a-z0-9][a-z0-9._-]&#123;0,63&#125;。 |
| path: tag | `string` | 必填；发布标签。预发布版本（如 1.3.0-beta.1）必须带 tag 且不能是 latest；tag 只能由 URL 安全字符组成（字母、数字及 - _ . ! ~ * ' ( )），不含空格和 / ? #，首尾无空白；不能是版本号或版本范围（如 1.2.3、^1、1.x、*）；beta、next、debug 等其余名称均可。违规返回 TAG_INVALID 或 TAG_REQUIRED，hint 给出完整规则。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| WORKFLOW_NAME | [创建工作流返回的 name](/docs/api/native/automation/createWorkflow) |

```bash
: "${WORKFLOW_NAME:?Set WORKFLOW_NAME}"
curl --fail-with-body -X DELETE "https://api.deepraxis.ai/automation/v1/workflows/docs-samples/${WORKFLOW_NAME}/dist-tags/sample" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.workflows.distTags.delete({
  "path": {
    "ns": "docs-samples",
    "name": env("WORKFLOW_NAME"),
    "tag": "sample"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| .*.version | `string` | 必填 / 必有；标签当前指向的精确版本号。 |
| .*.updated_at | `string` | 必填 / 必有；标签最近一次移动的时间（RFC 3339 UTC）。 |
| .*.updated_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| .*.updated_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| .*.updated_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "latest": {
    "version": "1.0.0",
    "updated_at": "2026-10-13T04:57:32.297Z",
    "updated_by": {
      "type": "api_key",
      "id": "key_3e00b8984967"
    }
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 TAG_INVALID：标签无效：预发布版本不能打 latest；tag 只能含 URL 安全字符（不含空格和 / ? #）；不能是版本号或范围；latest 不能删除。响应 hint 列出完整规则。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 校验定义

校验源码并返回诊断及输入输出契约。支持动作、脚本和工作流；结果含 valid 及引用，不会保存定义，源码不合法通过 valid=false 返回。 脚本/动作输出 schema 支持返回类型推断：Promise 解包、Record、交叉类型、Date；推不出时使用空 schema 并给 warning（warnings）。源码诊断使用 /source 或 /implementation/source，line/column 从 1 起。kind=action 与创建动作使用同一套准入检查（禁止导入外部模块、平台操作必须写成 call(praxis/<api>.<op>, 输入) 直接调用、不能调用 agent 或 automation 接口），校验通过的动作源码创建时不会再被拒绝。

`POST /automation/v1/validate`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| kind | `"action"` / `"script"` / `"workflow"` | 必填 / 必有；源码类型：action、script 或 workflow。 |
| source | `string` | 必填 / 必有；待校验的源码；action 和 script 使用 TypeScript，workflow 使用 YAML。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/validate" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "kind": "script",
  "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.validate.create({
  "body": {
    "kind": "script",
    "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| valid | `boolean` | 必填 / 必有；源码是否通过校验：true 可发布或运行，false 见 errors。 |
| errors | `object[]` | 必填 / 必有；校验错误列表，每项含 pointer 与中文 detail；为空数组时 valid 为 true。 |
| errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| input_schema | `null` / `object` | 必填 / 必有；从源码推导出的输入 JSON Schema；无法解析源码时为 null。 |
| input_schema（分支2).*（分支5) | `object` | 递归 JSON 值。 |
| input_schema（分支2).*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output_schema | `null` / `object` | 必填 / 必有；脚本从返回类型推导，支持 Promise 解包、Record、交叉类型和 Date（date-time）；推不出时为空 schema，并在 /validate 的 warnings 给出 warning。 |
| output_schema（分支2).*（分支5) | `object` | 递归 JSON 值。 |
| output_schema（分支2).*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| references | `object[]` | 必填 / 必有；源码依赖的动作、平台 API、脚本与工作流。 |
| references[].kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` / `"run"` | 必填 / 必有；依赖类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流；run 为脚本中 invoke("ns/name") 调用的子运行目标（脚本或工作流，发布时解析）。 |
| references[].name | `string` | 必填 / 必有；被依赖对象：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| references[].range | `string` | 可选；引用时写的版本范围或标签（npm 规则）；未写时为空。 |
| references[].locked_version | `string` | 可选；发布时锁定的精确版本；仅脚本与工作流依赖有，动作与平台 API 不锁定。 |
| outline | `null` / `object[]` | 必填 / 必有；工作流步骤大纲；脚本和动作为 null。 |
| outline（分支2)[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| outline（分支2)[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start；与运行时 Task.reference 一致。 |
| outline（分支2)[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| outline（分支2)[].target | `string` | 可选；步骤调用的目标：call 步骤为动作 ns/name，run 步骤为 ns/name@范围；其它类型没有。 |
| outline（分支2)[].wait | `object` | 可选；等待步骤的摘要：时长（seconds 或 duration）或等待的事件类型（event）。 不接受额外字段。 |
| outline（分支2)[].wait.until | `string` | 可选；等待结束的绝对时刻，仅在可静态确定时给出；目前大纲不填充该字段。 |
| outline（分支2)[].wait.seconds | `number` | 可选；可静态换算的等待秒数；时长对象与可换算的 ISO 时长均投影到此字段。 |
| outline（分支2)[].wait.event | `string` | 可选；listen 步骤等待的事件类型。 |
| outline（分支2)[].wait.duration | `string` | 可选；无法静态换算成秒的原始时长或运行时表达式；不与 seconds 强行换算。 |
| outline（分支2)[].loop | `object` | 可选；for 步骤的循环信息 &#123;each, in&#125;。 不接受额外字段。 |
| outline（分支2)[].loop.each | `string` | 必填 / 必有；循环变量名；未指定时为 item。 |
| outline（分支2)[].loop.in | `string` | 必填 / 必有；被遍历的集合表达式原文。 |
| outline（分支2)[].children | `object[]` | 可选；嵌套的子步骤（do、fork 分支、try 与 catch 内的步骤）。 |
| outline（分支2)[].children[] | `object` | 递归 JSON 值。 |
| warnings | `object[]` | 可选；脚本/动作静态分析的非阻断诊断；无法推导类型时使用空 schema 并给 warning。工作流分析可省略。 |
| warnings[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| warnings[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| warnings[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| warnings[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| warnings[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| platform_apis | `string[]` | 可选；脚本/动作引用的平台 API 集合（字符串数组）；工作流分析可省略。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "valid": true,
  "errors": [],
  "warnings": [],
  "input_schema": {
    "type": "object",
    "properties": {
      "n": {
        "type": "number"
      }
    },
    "required": [
      "n"
    ]
  },
  "output_schema": {
    "type": "object",
    "properties": {
      "answer": {
        "type": "number"
      }
    },
    "required": [
      "answer"
    ]
  },
  "references": [],
  "outline": null,
  "platform_apis": []
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 解析运行目标

将 ns/name@tag、精确版本或版本范围解析为可运行的精确版本；省略 @ 时使用 latest，归档目标拒绝解析，无匹配返回 NO_MATCHING_VERSION。

`GET /automation/v1/resolve`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| query: target | `string` | 必填；ns/name@tag、ns/name@version 或 ns/name@range；省略 @ 时使用 latest。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TARGET | [已发布的 docs-samples/name@1.0.0](/docs/api/native/automation/publishScriptVersion) |

```bash
: "${TARGET:?Set TARGET}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/resolve" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  --get \
  --data-urlencode "target=${TARGET}"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.resolve.retrieve({
  "query": {
    "target": env("TARGET")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| namespace | `string` | 必填 / 必有；编排命名空间。 |
| name | `string` | 必填 / 必有；编排名字。 |
| version | `string` | 必填 / 必有；target 解析到的精确版本号。 |
| version_id | `string` | 必填 / 必有；该版本的 ID（scv_ 或 wfv_ 前缀）。 |
| deprecated | `null` / `string` | 必填 / 必有；解析到的版本被弃用时的弃用说明；未弃用为 null。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "kind": "script",
  "namespace": "docs-samples",
  "name": "sample-scripts-1791867412840-b05e8a",
  "version": "1.0.0",
  "version_id": "scv_00mv67lza679fc5498438040079f0c5684208c4915",
  "deprecated": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 422 | NO_MATCHING_VERSION：没有满足标签、版本或范围的已发布版本。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 搜索自动化定义

按名称搜索可见目标，按名称升序分页；默认排除归档目标，可筛选已发布的脚本和工作流。

`GET /automation/v1/targets`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| query: q | `string` | 可选；不区分大小写，按 ns/name 或说明的字面子串匹配。 |
| query: kind | `"action"` / `"script"` / `"workflow"[]` | 可选；action、script 或 workflow；省略返回全部。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 25。 minimum: 1；maximum: 100 |
| query: labels | `object` | 可选；按标签过滤，使用 labels[k]=v；同键逗号多值取任一，不同键同时满足。 |
| query: created_at[gte] | `string` | 可选；创建时间下界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |
| query: created_at[lte] | `string` | 可选；创建时间上界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |
| query: cursor | `string` | 可选；上一页的 next_cursor；翻页时保留原筛选条件。 |
| query: archived | `boolean` | 可选；默认 false，仅返回未归档目标；true 仅返回已归档目标。 default: false |
| query: published | `boolean` | 可选；true 仅返回有已发布版本的编排；动作始终可用。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/targets" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  --get \
  --data-urlencode "q=sample-" \
  --data-urlencode "limit=1"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.targets.list({
  "query": {
    "q": "sample-",
    "limit": 1
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的目标搜索结果（动作、脚本、工作流），按相关度和创建时间排列。 |
| data[].kind | `"action"` / `"script"` / `"workflow"` | 必填 / 必有；目标类型。action 为动作；script 为脚本；workflow 为工作流。 |
| data[].namespace | `string` | 必填 / 必有；目标命名空间。 |
| data[].name | `string` | 必填 / 必有；目标名字。 |
| data[].description | `string` | 必填 / 必有；目标的说明文字。 |
| data[].latest_version | `null` / `string` | 必填 / 必有；latest 标签指向的版本号；动作或尚未发布时为 null。 |
| data[].archived | `boolean` | 必填 / 必有；true 表示目标已归档，不能再被运行。 |
| next_cursor | `string` / `null` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "kind": "action",
      "namespace": "docs-samples",
      "name": "sample-action-1791867412840-b05e8a",
      "description": "",
      "latest_version": null,
      "archived": false
    }
  ],
  "next_cursor": "WyJbXCJ0YXJnZXRzXCIsXCJ0bnRfM2E5NzU5ODY0Y2NiNGUwMFwiLHtcInFcIjpcInNhbXBsZS1cIn1dIiwiZG9jcy1zYW1wbGVzL3NhbXBsZS1hY3Rpb24tMTc5MTg2NzQxMjg0MC1iMDVlOGEiLCJmdW5jdGlvbjphY3RfMDBtdjY3bG96NGZlNGYyN2JkZjg5MzQ2Yzg4NWIzYTI4YjIwMzhjMDkxIl0="
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 创建运行

target 与 source 二选一；source 还须提供 language，输入与源码先校验再创建运行。wait 为 0–60 秒（默认 0），返回时已到终态为 200，否则 202；Idempotency-Key 在租户、方法、路径内保留 24 小时，请求指纹不含 wait。重放返回当前运行并带 Idempotent-Replayed: true，同键不同内容返回 422，处理中返回 409。新建非确定性运行 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位十六进制 DO ID，共 78 字符；旧随机 ID 为 46 字符，历史与确定性 ID 仍有效。同毫秒内不保证顺序。

`POST /automation/v1/runs`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| header: Idempotency-Key | `string` | 可选；1–256 字符；租户、方法、路径内去重 24 小时，请求指纹不含 wait。 |

### application/json [#applicationjson]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| （分支1).target | `string` | 必填 / 必有；脚本或工作流引用 ns/name@tag、ns/name@version 或 ns/name@range，省略 @ 时使用 latest；与 source 互斥。 |
| （分支1).input | `null` / `string` / `number` / `boolean` / `object` / `null` / `string` / `number` / `boolean` / `object` / `JSON[][]` | 可选；传给运行的 JSON 输入，缺省为 &#123;&#125;；必须符合目标输入契约，最多 1 MiB。 |
| （分支1).input（分支5).*（分支5) | `object` | 递归 JSON 值。 |
| （分支1).input（分支5).*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).input（分支6)[]（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).input（分支6)[]（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).wait | `number` | 可选；等待终态的秒数，0–60，默认 0；不计入幂等请求指纹。 minimum: 0；maximum: 60 |
| （分支1).labels | `object` | 可选；最多 50 个标签；键为 1–40 个字符，值最多 500 个字符。 |
| （分支1).deadline_seconds | `integer` | 可选；正整数秒，最多 604800；脚本默认且最多 300 秒，工作流默认 86400 秒、最多 7 天。 minimum: 1 |
| （分支2).source | `string` | 必填 / 必有；源码；创建临时运行时与 target 互斥，且必须同时提供 language，最多 1 MiB。 |
| （分支2).language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言：ts 表示脚本，yaml 表示工作流。 |
| （分支2).input | `null` / `string` / `number` / `boolean` / `object` / `null` / `string` / `number` / `boolean` / `object` / `JSON[][]` | 可选；传给运行的 JSON 输入，缺省为 &#123;&#125;；必须符合目标输入契约，最多 1 MiB。 |
| （分支2).input（分支5).*（分支5) | `object` | 递归 JSON 值。 |
| （分支2).input（分支5).*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支2).input（分支6)[]（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支2).input（分支6)[]（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支2).wait | `number` | 可选；等待终态的秒数，0–60，默认 0；不计入幂等请求指纹。 minimum: 0；maximum: 60 |
| （分支2).labels | `object` | 可选；最多 50 个标签；键为 1–40 个字符，值最多 500 个字符。 |
| （分支2).deadline_seconds | `integer` | 可选；正整数秒，最多 604800；脚本默认且最多 300 秒，工作流默认 86400 秒、最多 7 天。 minimum: 1 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/runs" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });",
  "language": "ts",
  "input": {
    "n": 41
  },
  "wait": 60,
  "labels": {
    "namespace": "docs-samples",
    "name": "sample-run"
  }
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.create({
  "body": {
    "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });",
    "language": "ts",
    "input": {
      "n": 41
    },
    "wait": 60,
    "labels": {
      "namespace": "docs-samples",
      "name": "sample-run"
    }
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | true when returning a replayed run. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |

### HTTP 202 [#http-202]

Run accepted; still pending or executing when wait expires.

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | true when returning a replayed run. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1",
  "kind": "script",
  "number": null,
  "definition": null,
  "target": null,
  "resolved_version": null,
  "source_digest": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d",
  "language": "ts",
  "status": "completed",
  "progress": null,
  "current_wait": null,
  "counters": {
    "calls": 0,
    "action_calls": 0,
    "child_runs": 0,
    "tasks_completed": 0,
    "tasks_total": null
  },
  "input": {
    "n": 41
  },
  "output": {
    "answer": 42
  },
  "error": null,
  "initiator": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "channel": "api",
  "owner": "tnt_3a9759864ccb4e00",
  "trigger": null,
  "parent": null,
  "parent_run_id": null,
  "root_run_id": "run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1",
  "depth": 0,
  "attach": null,
  "deadline_at": "2026-10-13T05:02:40.954Z",
  "created_at": "2026-10-13T04:57:40.954Z",
  "started_at": "2026-10-13T04:57:42.283Z",
  "ended_at": "2026-10-13T04:57:42.367Z",
  "updated_at": "2026-10-13T04:57:42.367Z",
  "heartbeat_at": "2026-10-13T04:57:42.283Z",
  "cancel_requested_at": null,
  "cancelled_by": null,
  "cancel_reason": null,
  "cancel_message": null,
  "suspend_requested_at": null,
  "suspended_by": null,
  "queued_ms": 1329,
  "run_ms": 84,
  "wait_ms": null,
  "usage": null,
  "rerun_of": null,
  "labels": {
    "namespace": "docs-samples",
    "name": "sample-run-1791867412840-b05e8a"
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 DEFINITION_INVALID：源码未通过定义校验。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| 409 | TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 |
| 413 | PAYLOAD_TOO_LARGE：请求内容超过本操作允许的大小。 |
| 422 | NO_MATCHING_VERSION：没有满足标签、版本或范围的已发布版本。 IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出运行

按创建时间倒序筛选租户内运行。支持状态多选、目标、来源、labels[k] 和创建时间下界筛选。q 以 run_ 开头时精确匹配运行 ID，否则按编排名称前缀匹配。大 input/output 在列表中为 null，对应 input_truncated/output_truncated 为 true；详情返回全文。

`GET /automation/v1/runs`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 50。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: kind | `"script"` / `"workflow"[]` | 可选；script 或 workflow；省略返回两者。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: definition | `string[]` | 可选；精确编排名，格式 ns/name。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: version | `string[]` | 可选；规范的精确语义版本，例如 1.2.0 或 1.3.0-beta.1；不能是范围。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: status | `"pending"` / `"running"` / `"waiting"` / `"suspended"` / `"cancelled"` / `"faulted"` / `"completed"[]` | 可选；逗号分隔的状态，可选 pending、running、waiting、suspended、cancelled、faulted、completed；省略不过滤。 多个值以逗号分隔，匹配任一值。 |
| query: channel | `"console"` / `"api"` / `"internal"` / `"run"` / `"trigger"[]` | 可选；来源渠道：run 仅子运行；console、api、internal、trigger 为根运行。多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: initiator_type | `"user"` / `"api_key"` / `"agent"` / `"trigger"[]` | 可选；根发起方类型：user、api_key、agent 或 trigger，子运行继承根发起方。run 返回 INPUT_INVALID；按来源筛选用 channel=run 或 parent_run_id。多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: initiator | `"me"` | 可选；仅支持 me，匹配当前凭证的主体类型和 ID，包含由我的运行派生出的子运行；省略不限制。 |
| query: adhoc | `boolean` | 可选；true 仅临时运行，false 仅已发布定义的运行；省略返回两者。 |
| query: language | `"ts"` / `"yaml"[]` | 可选；源码语言：ts 或 yaml。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: parent_run_id | `string[]` | 可选；按直接父运行 ID 精确匹配；用它列出某个运行的子运行（由工作流 run 步骤或脚本 invoke() 启动），每项含 ID、目标、状态与耗时。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: root_run_id | `string[]` | 可选；按根运行 ID 精确匹配，读取同一运行树。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: q | `string` | 可选；run_ 开头时精确匹配运行 ID，否则按编排名称前缀匹配；% 与 _ 作为普通字符。 |
| query: labels | `object` | 可选；按标签过滤，使用 labels[k]=v；同键逗号多值取任一，不同键同时满足。 |
| query: created_at[gte] | `string` | 可选；创建时间下界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |
| query: created_at[lte] | `string` | 可选；创建时间上界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  --get \
  --data-urlencode "labels[name]=sample-run-1791867412840-b05e8a" \
  --data-urlencode "limit=1"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.list({
  "query": {
    "labels": {
      "name": "sample-run-1791867412840-b05e8a"
    },
    "limit": 1
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的运行摘要，按 created_at 倒序、id 倒序排列。 |
| data[].id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| data[].kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data[].number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| data[].definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| data[].definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| data[].definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| data[].target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| data[].resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| data[].source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| data[].language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| data[].status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| data[].progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| data[].progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| data[].progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| data[].progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| data[].progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| data[].current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| data[].current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| data[].current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| data[].current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| data[].current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| data[].current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| data[].current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| data[].current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| data[].current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| data[].current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| data[].current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| data[].current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| data[].current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| data[].current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| data[].counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| data[].counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| data[].counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| data[].counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| data[].counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| data[].counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| data[].input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[].input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[].output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| data[].error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data[].error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data[].error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data[].error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data[].error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data[].error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data[].error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data[].error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data[].error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data[].error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data[].error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data[].error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data[].error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data[].error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data[].error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data[].error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data[].error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[].error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[].error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data[].initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| data[].initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[].channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| data[].owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| data[].parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| data[].parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| data[].parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| data[].parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| data[].parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| data[].parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| data[].parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| data[].root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| data[].depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| data[].attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| data[].deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| data[].created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| data[].started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| data[].ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| data[].updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| data[].heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| data[].cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| data[].cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| data[].cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[].cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| data[].suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| data[].suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| data[].suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[].queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| data[].run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| data[].wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| data[].usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| data[].usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| data[].usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| data[].usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| data[].usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| data[].usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| data[].usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| data[].usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| data[].rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| data[].labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| data[].trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| data[].trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| data[].trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| data[].cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| data[].input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| data[].output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1",
      "kind": "script",
      "number": null,
      "definition": null,
      "target": null,
      "resolved_version": null,
      "source_digest": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d",
      "language": "ts",
      "status": "completed",
      "progress": null,
      "current_wait": null,
      "counters": {
        "calls": 0,
        "action_calls": 0,
        "child_runs": 0,
        "tasks_completed": 0,
        "tasks_total": null
      },
      "input": {
        "n": 41
      },
      "output": {
        "answer": 42
      },
      "error": null,
      "initiator": {
        "type": "api_key",
        "id": "key_3e00b8984967"
      },
      "channel": "api",
      "owner": "tnt_3a9759864ccb4e00",
      "trigger": null,
      "parent": null,
      "parent_run_id": null,
      "root_run_id": "run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1",
      "depth": 0,
      "attach": null,
      "deadline_at": "2026-10-13T05:02:40.954Z",
      "created_at": "2026-10-13T04:57:40.954Z",
      "started_at": "2026-10-13T04:57:42.283Z",
      "ended_at": "2026-10-13T04:57:42.367Z",
      "updated_at": "2026-10-13T04:57:42.367Z",
      "heartbeat_at": "2026-10-13T04:57:42.283Z",
      "cancel_requested_at": null,
      "cancelled_by": null,
      "cancel_reason": null,
      "cancel_message": null,
      "suspend_requested_at": null,
      "suspended_by": null,
      "queued_ms": 1329,
      "run_ms": 84,
      "wait_ms": null,
      "usage": null,
      "rerun_of": null,
      "labels": {
        "namespace": "docs-samples",
        "name": "sample-run-1791867412840-b05e8a"
      }
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取运行

读取运行详情，可用 expand 一次带回调用、步骤、步骤聚合、日志或源码；传 wait（秒，0–60）可挂起请求直到运行到达终态或超时，不必轮询；展开页最多 200 条，后续通过各账本端点的游标读取。 工作流 raise 错误保留完整 type URI、status、title、detail；只有平台内部异常归为 runtime。

`GET /automation/v1/runs/{id}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| query: expand | `"calls"` / `"tasks"` / `"task_groups"` / `"logs"` / `"source"[]` | 可选；逗号分隔且不能重复：calls、tasks、task_groups、logs、source，这是全部合法取值（output 不是展开项，运行输出在 output 字段里）；省略不展开，展开页最多 200 条。无效取值返回 INVALID_PARAMS 并列出合法取值。 minItems: 1 |
| query: wait | `integer` | 可选；等待运行到达终态的秒数，0–60 的整数，默认 0（立即返回）。超时后运行仍未结束则返回当前运行（状态码仍为 200），请检查 status；超过 60 或不是整数返回 INVALID_PARAMS。含义与 runs.create 的 wait 相同。 minimum: 0；maximum: 60 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.retrieve({
  "path": {
    "id": env("RUN_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| calls | `object` | 可选；expand=calls 时返回的调用记录分页：&#123;data, next_cursor&#125;。 不接受额外字段。 |
| calls.data | `object[]` | 必填 / 必有；本页的调用记录（Call）。 maxItems: 200 |
| calls.data[].id | `string` | 必填 / 必有；调用 ID，前缀 call_。 |
| calls.data[].run_id | `string` | 必填 / 必有；发出该调用的脚本运行 ID（run_ 前缀）。 |
| calls.data[].seq | `number` | 必填 / 必有；调用在该运行中的序号，随调用顺序递增；与 run_id 一起定位这次调用。 |
| calls.data[].target | `object` | 必填 / 必有；被调用的目标 &#123;kind, name, revision?, version?&#125;。 不接受额外字段。 |
| calls.data[].target.kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` | 必填 / 必有；目标类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流。 |
| calls.data[].target.name | `string` | 必填 / 必有；目标名称：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| calls.data[].target.revision | `string` | 可选；实际执行的动作修订 ID（actr_ 前缀）；仅动作调用有。 |
| calls.data[].target.version | `string` | 可选；实际运行的精确版本号；仅脚本与工作流调用有。 |
| calls.data[].args_preview | `string` | 必填 / 必有；调用参数的单行预览，由服务端截断；超过 32 KB 的原文存放在对象存储而不内联。 |
| calls.data[].result_preview | `null` / `string` | 必填 / 必有；返回值的单行预览，由服务端截断；调用结束前为 null。 |
| calls.data[].status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` | 必填 / 必有；调用状态。running 执行中；completed 已正常返回；faulted 失败，error 给出原因；cancelled 因运行被取消而中止。 |
| calls.data[].started_at | `string` | 必填 / 必有；调用开始的时间（RFC 3339 UTC）。 |
| calls.data[].ended_at | `null` / `string` | 必填 / 必有；调用结束的时间（RFC 3339 UTC）；仍在执行为 null。 |
| calls.data[].duration_ms | `null` / `number` | 必填 / 必有；从开始到结束的毫秒数；未结束为 null。 |
| calls.data[].error | `null` / `object` | 必填 / 必有；调用失败时的错误详情；成功或仍在执行为 null。 |
| calls.data[].error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| calls.data[].error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| calls.data[].error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| calls.data[].error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| calls.data[].error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| calls.data[].error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| calls.data[].error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| calls.data[].error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| calls.data[].error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| calls.data[].error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| calls.data[].error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| calls.data[].error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| calls.data[].error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| calls.data[].error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| calls.data[].error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| calls.data[].error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| calls.data[].error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| calls.data[].error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| calls.data[].error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| calls.data[].child_run_id | `null` / `string` | 必填 / 必有；目标是脚本或工作流时，由本次调用启动的子运行 ID；动作与平台 API 调用为 null。 |
| calls.data[].invocation_key | `string` | 必填 / 必有；标识这一次逻辑调用的键，随调用发往下游，使至少一次语义下的重试可被去重。 |
| calls.data[].request_id | `string` / `null` | 必填 / 必有；下游响应的 X-Request-Id；尚未收到响应或响应未提供该头时为 null。 |
| calls.next_cursor | `null` / `string` | 必填 / 必有；下一页游标；没有更多为 null。 |
| tasks | `object` | 可选；expand=tasks 时返回的工作流步骤分页：&#123;data, next_cursor&#125;。 不接受额外字段。 |
| tasks.data | `object[]` | 必填 / 必有；本页的步骤（Task）。 maxItems: 200 |
| tasks.data[].id | `string` | 必填 / 必有；步骤执行记录的标识，按不透明字符串处理。 |
| tasks.data[].run_id | `string` | 必填 / 必有；所属运行 ID。 |
| tasks.data[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start。 |
| tasks.data[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| tasks.data[].kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| tasks.data[].iteration | `number[]` | 必填 / 必有；外层 for 循环的当前迭代下标，由外到内；不在循环中为空数组。 |
| tasks.data[].attempt | `number` | 必填 / 必有；第几次尝试；步骤因重试而重新执行时递增。 |
| tasks.data[].status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；步骤状态，取值与运行状态相同。pending 尚未开始；running 执行中；waiting 在等待事件、定时器或子运行；suspended 因运行被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| tasks.data[].skipped | `boolean` | 必填 / 必有；true 表示该步骤被跳过而没有实际执行。 |
| tasks.data[].started_at | `null` / `string` | 必填 / 必有；步骤开始的时间（RFC 3339 UTC）；未开始为 null。 |
| tasks.data[].ended_at | `null` / `string` | 必填 / 必有；步骤结束的时间（RFC 3339 UTC）；未结束为 null。 |
| tasks.data[].duration_ms | `null` / `number` | 必填 / 必有；执行耗时毫秒数；未结束为 null。 |
| tasks.data[].input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| tasks.data[].input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| tasks.data[].input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| tasks.data[].input_truncated | `boolean` | 必填 / 必有；true 表示 input 超过 32 KB 已被截断。 |
| tasks.data[].output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| tasks.data[].output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| tasks.data[].output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| tasks.data[].output_truncated | `boolean` | 必填 / 必有；输出超过内联限制而被省略时为 true。 |
| tasks.data[].error | `null` / `object` | 必填 / 必有；步骤失败时的错误详情；未失败为 null。 |
| tasks.data[].error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| tasks.data[].error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| tasks.data[].error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| tasks.data[].error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| tasks.data[].error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| tasks.data[].error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| tasks.data[].error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| tasks.data[].error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| tasks.data[].error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| tasks.data[].error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| tasks.data[].error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| tasks.data[].error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| tasks.data[].error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| tasks.data[].error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| tasks.data[].error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| tasks.data[].error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| tasks.data[].error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| tasks.data[].error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| tasks.data[].error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| tasks.data[].action | `null` / `object` | 必填 / 必有；call 步骤执行的动作 &#123;name, revision&#125;；其它步骤为 null。 |
| tasks.data[].action（分支2).name | `string` | 必填 / 必有；动作全名 ns/name。 |
| tasks.data[].action（分支2).revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| tasks.data[].child_run | `null` / `object` | 必填 / 必有；run 步骤启动的子运行摘要 &#123;id, number, status, resolved_version&#125;；其它步骤为 null。 |
| tasks.data[].child_run（分支2).id | `string` | 必填 / 必有；子运行 ID（run_ 前缀），创建后即可读取。 |
| tasks.data[].child_run（分支2).number | `null` / `number` | 必填 / 必有；子运行在其定义内的序号；临时运行为 null。 |
| tasks.data[].child_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；子运行的状态。pending 尚未开始；running 执行中；waiting 在等待；suspended 已暂停；cancelled 已取消；faulted 失败；completed 成功完成。等待型子运行在结束时补全终态，detach 的子运行只记录启动时的状态。 |
| tasks.data[].child_run（分支2).resolved_version | `null` / `string` | 必填 / 必有；子运行解析到的精确版本号；临时运行为 null。 |
| tasks.next_cursor | `null` / `string` | 必填 / 必有；下一页游标；没有更多为 null。 |
| task_groups | `object` | 可选；expand=task_groups 时返回、按 reference 聚合的步骤分页 &#123;data, next_cursor&#125;（循环的多次迭代合并为一行）；脚本运行为空页。 不接受额外字段。 |
| task_groups.data | `object[]` | 必填 / 必有；本页的聚合行（TaskGroup）。 maxItems: 200 |
| task_groups.data[].reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start。 |
| task_groups.data[].name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| task_groups.data[].count | `number` | 必填 / 必有；该 reference 下合并的执行记录条数（循环的迭代数）。 |
| task_groups.data[].status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；步骤状态，取值与运行状态相同。pending 尚未开始；running 执行中；waiting 在等待事件、定时器或子运行；suspended 因运行被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| task_groups.data[].duration_ms | `null` / `number` | 必填 / 必有；执行耗时毫秒数；未结束为 null。 |
| task_groups.next_cursor | `null` / `string` | 必填 / 必有；下一页游标；没有更多为 null。 |
| logs | `object` | 可选；expand=logs 时返回的日志分页：&#123;data, next_cursor&#125;。 不接受额外字段。 |
| logs.data | `object[]` | 必填 / 必有；本页的日志行（LogLine）。 maxItems: 200 |
| logs.data[].cursor | `string` | 必填 / 必有；该行的游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| logs.data[].ts | `string` | 必填 / 必有；日志产生的时间（RFC 3339 UTC）。 |
| logs.data[].level | `"debug"` / `"info"` / `"warn"` / `"error"` | 必填 / 必有；日志级别。debug 调试信息；info 一般信息；warn 警告；error 错误。 |
| logs.data[].message | `string` | 必填 / 必有；日志文本。 |
| logs.next_cursor | `null` / `string` | 必填 / 必有；下一页游标；没有更多为 null。 |
| source | `object` | 可选；临时运行的源码快照 &#123;language, source, sha256&#125;。 不接受额外字段。 |
| source.language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| source.source | `string` | 必填 / 必有；运行时使用的完整源码（ts 或 yaml）。 |
| source.sha256 | `string` | 必填 / 必有；源码的 SHA-256 摘要，可作为发布时的 expected_source_sha256。 |
| cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1",
  "kind": "script",
  "number": null,
  "definition": null,
  "target": null,
  "resolved_version": null,
  "source_digest": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d",
  "language": "ts",
  "status": "completed",
  "progress": null,
  "current_wait": null,
  "counters": {
    "calls": 0,
    "action_calls": 0,
    "child_runs": 0,
    "tasks_completed": 0,
    "tasks_total": null
  },
  "input": {
    "n": 41
  },
  "output": {
    "answer": 42
  },
  "error": null,
  "initiator": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "channel": "api",
  "owner": "tnt_3a9759864ccb4e00",
  "trigger": null,
  "parent": null,
  "parent_run_id": null,
  "root_run_id": "run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1",
  "depth": 0,
  "attach": null,
  "deadline_at": "2026-10-13T05:02:40.954Z",
  "created_at": "2026-10-13T04:57:40.954Z",
  "started_at": "2026-10-13T04:57:42.283Z",
  "ended_at": "2026-10-13T04:57:42.367Z",
  "updated_at": "2026-10-13T04:57:42.367Z",
  "heartbeat_at": "2026-10-13T04:57:42.283Z",
  "cancel_requested_at": null,
  "cancelled_by": null,
  "cancel_reason": null,
  "cancel_message": null,
  "suspend_requested_at": null,
  "suspended_by": null,
  "queued_ms": 1329,
  "run_ms": 84,
  "wait_ms": null,
  "usage": {
    "currency": "USD",
    "cost": "0.000000",
    "pending_events": 0,
    "by_service": [],
    "tree_cost": "0.000000"
  },
  "rerun_of": null,
  "labels": {
    "namespace": "docs-samples",
    "name": "sample-run-1791867412840-b05e8a"
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 取消运行

请求取消运行。返回 202：工作流直接终止，脚本先请求中止并在宽限期后强制结束；已终态运行返回 409 RUN_INVALID_STATE。取消传播到附着子运行，不影响 detach 子运行；可选 reason 为 1–500 字符，保存为 Run.cancel_message；用户取消的 cancel_reason 仍为 user。

`POST /automation/v1/runs/{id}/cancel`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| reason | `string` | 可选；可选取消备注，1–500 字符；保存为 Run.cancel_message，cancel_reason 仍为 user。 minLength: 1；maxLength: 500 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/cancel" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "reason": "Sample completed"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.cancel({
  "path": {
    "id": env("RUN_ID")
  },
  "body": {
    "reason": "Sample completed"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 202 [#http-202]

Cancellation accepted; updated Run.

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |

### 实测响应 [#实测响应]

HTTP 202

```json
{
  "id": "run_00mv67mwcj0f099fa839644b384742cdfbbbff67226e46f1eed8a36c5226f15a3cf730a221",
  "kind": "workflow",
  "number": null,
  "definition": null,
  "target": null,
  "resolved_version": null,
  "source_digest": "fa40016c6458f18ae4e5b418247cdccccfc4d5dfabe2bdec76f3103842ea15ad",
  "language": "yaml",
  "status": "cancelled",
  "progress": null,
  "current_wait": null,
  "counters": {
    "calls": 0,
    "action_calls": 0,
    "child_runs": 0,
    "tasks_completed": 0,
    "tasks_total": 1
  },
  "input": {},
  "output": null,
  "error": null,
  "initiator": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "channel": "api",
  "owner": "tnt_3a9759864ccb4e00",
  "trigger": null,
  "parent": null,
  "parent_run_id": null,
  "root_run_id": "run_00mv67mwcj0f099fa839644b384742cdfbbbff67226e46f1eed8a36c5226f15a3cf730a221",
  "depth": 0,
  "attach": null,
  "deadline_at": "2026-10-14T04:58:05.251Z",
  "created_at": "2026-10-13T04:58:05.251Z",
  "started_at": null,
  "ended_at": "2026-10-13T04:58:07.803Z",
  "updated_at": "2026-10-13T04:58:07.803Z",
  "heartbeat_at": null,
  "cancel_requested_at": "2026-10-13T04:58:07.754Z",
  "cancelled_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "cancel_reason": "user",
  "cancel_message": "Sample completed",
  "suspend_requested_at": null,
  "suspended_by": null,
  "queued_ms": 2552,
  "run_ms": 0,
  "wait_ms": null,
  "usage": null,
  "rerun_of": null,
  "labels": {
    "namespace": "docs-samples",
    "name": "sample-run-1791867412840-b05e8a"
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| 409 | RUN_INVALID_STATE：当前状态不允许执行该动作。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 重新运行

用原精确版本或原临时源码创建新的根运行，保留标签并记录 rerun_of；可覆盖 input，未提供则沿用原输入。原目标已归档会拒绝重新运行，运行令牌不能使用此入口。

`POST /automation/v1/runs/{id}/rerun`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| input | `null` / `string` / `number` / `boolean` / `object` / `null` / `string` / `number` / `boolean` / `object` / `JSON[][]` | 可选；可选的新输入；省略沿用原运行输入，必须符合目标契约。 |
| input（分支5).*（分支5) | `object` | 递归 JSON 值。 |
| input（分支5).*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[]（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[]（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/rerun" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "input": {
    "n": 42
  }
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.rerun({
  "path": {
    "id": env("RUN_ID")
  },
  "body": {
    "input": {
      "n": 42
    }
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "run_00mv67mj3s5141d7514d6e0c18cd71ba7e821b89faadad8897cc6bedb103209efe6de40b4d",
  "kind": "script",
  "number": null,
  "definition": null,
  "target": null,
  "resolved_version": null,
  "source_digest": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d",
  "language": "ts",
  "status": "running",
  "progress": null,
  "current_wait": null,
  "counters": {
    "calls": 0,
    "action_calls": 0,
    "child_runs": 0,
    "tasks_completed": 0,
    "tasks_total": null
  },
  "input": {
    "n": 42
  },
  "output": null,
  "error": null,
  "initiator": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "channel": "api",
  "owner": "tnt_3a9759864ccb4e00",
  "trigger": null,
  "parent": null,
  "parent_run_id": null,
  "root_run_id": "run_00mv67mj3s5141d7514d6e0c18cd71ba7e821b89faadad8897cc6bedb103209efe6de40b4d",
  "depth": 0,
  "attach": null,
  "deadline_at": "2026-10-13T05:02:48.088Z",
  "created_at": "2026-10-13T04:57:48.088Z",
  "started_at": "2026-10-13T04:57:49.075Z",
  "ended_at": null,
  "updated_at": "2026-10-13T04:57:49.075Z",
  "heartbeat_at": "2026-10-13T04:57:49.075Z",
  "cancel_requested_at": null,
  "cancelled_by": null,
  "cancel_reason": null,
  "cancel_message": null,
  "suspend_requested_at": null,
  "suspended_by": null,
  "queued_ms": 987,
  "run_ms": null,
  "wait_ms": null,
  "usage": null,
  "rerun_of": "run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1",
  "labels": {
    "namespace": "docs-samples",
    "name": "sample-run-1791867412840-b05e8a"
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 DEFINITION_INVALID：源码未通过定义校验。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| 403 | NAMESPACE_FORBIDDEN：命名空间只读或运行令牌不允许此调用。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 413 | PAYLOAD_TOO_LARGE：请求内容超过本操作允许的大小。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 NO_MATCHING_VERSION：没有满足标签、版本或范围的已发布版本。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 暂停运行

仅可暂停正在运行或等待中的工作流；脚本返回 OPERATION_NOT_SUPPORTED，其他状态返回 RUN_INVALID_STATE。

`POST /automation/v1/runs/{id}/suspend`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |

### application/json [#applicationjson]

不接受额外字段。
object

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/suspend" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.suspend({
  "path": {
    "id": env("RUN_ID")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "run_00mv67mkw52c7fa90cc9649b1053e66fd836b071f289acb667ff8ca853e65bc4608e9a45bd",
  "kind": "workflow",
  "number": null,
  "definition": null,
  "target": null,
  "resolved_version": null,
  "source_digest": "1f559f7323adda4865d889639a4d878eab97e1ce3e542c68ea4022af4cd0f7fa",
  "language": "yaml",
  "status": "suspended",
  "progress": null,
  "current_wait": {
    "id": "wait_wf-eebc9ef34869206fa1bcc1e2ae6375990a7ab34c5ad485ac98a4f189c4b37346",
    "run_id": "run_00mv67mkw52c7fa90cc9649b1053e66fd836b071f289acb667ff8ca853e65bc4608e9a45bd",
    "kind": "event",
    "state": "open",
    "task": {
      "reference": "/do/0/ready",
      "name": "ready"
    },
    "resume_at": null,
    "event_type": "ready",
    "child_run_id": null,
    "created_at": "2026-10-13T04:57:56.982Z",
    "expires_at": "2026-10-14T04:57:50.405Z",
    "resolved_at": null
  },
  "counters": {
    "calls": 0,
    "action_calls": 0,
    "child_runs": 0,
    "tasks_completed": 0,
    "tasks_total": 1
  },
  "input": {},
  "output": null,
  "error": null,
  "initiator": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "channel": "api",
  "owner": "tnt_3a9759864ccb4e00",
  "trigger": null,
  "parent": null,
  "parent_run_id": null,
  "root_run_id": "run_00mv67mkw52c7fa90cc9649b1053e66fd836b071f289acb667ff8ca853e65bc4608e9a45bd",
  "depth": 0,
  "attach": null,
  "deadline_at": "2026-10-14T04:57:50.405Z",
  "created_at": "2026-10-13T04:57:50.405Z",
  "started_at": "2026-10-13T04:57:56.933Z",
  "ended_at": null,
  "updated_at": "2026-10-13T04:57:58.173Z",
  "heartbeat_at": null,
  "cancel_requested_at": null,
  "cancelled_by": null,
  "cancel_reason": null,
  "cancel_message": null,
  "suspend_requested_at": "2026-10-13T04:57:58.173Z",
  "suspended_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "queued_ms": 6528,
  "run_ms": null,
  "wait_ms": null,
  "usage": null,
  "rerun_of": null,
  "labels": {
    "namespace": "docs-samples",
    "name": "sample-run-1791867412840-b05e8a"
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| 409 | OPERATION_NOT_SUPPORTED：该资源类型不支持此操作。 RUN_INVALID_STATE：当前状态不允许执行该动作。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 恢复运行

仅恢复 suspended 状态的工作流，回到暂停前的运行或等待状态；并发名额不足时仍保持暂停，脚本不支持此操作。

`POST /automation/v1/runs/{id}/resume`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |

### application/json [#applicationjson]

不接受额外字段。
object

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/resume" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.resume({
  "path": {
    "id": env("RUN_ID")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "run_00mv67mkw52c7fa90cc9649b1053e66fd836b071f289acb667ff8ca853e65bc4608e9a45bd",
  "kind": "workflow",
  "number": null,
  "definition": null,
  "target": null,
  "resolved_version": null,
  "source_digest": "1f559f7323adda4865d889639a4d878eab97e1ce3e542c68ea4022af4cd0f7fa",
  "language": "yaml",
  "status": "waiting",
  "progress": null,
  "current_wait": {
    "id": "wait_wf-eebc9ef34869206fa1bcc1e2ae6375990a7ab34c5ad485ac98a4f189c4b37346",
    "run_id": "run_00mv67mkw52c7fa90cc9649b1053e66fd836b071f289acb667ff8ca853e65bc4608e9a45bd",
    "kind": "event",
    "state": "open",
    "task": {
      "reference": "/do/0/ready",
      "name": "ready"
    },
    "resume_at": null,
    "event_type": "ready",
    "child_run_id": null,
    "created_at": "2026-10-13T04:57:56.982Z",
    "expires_at": "2026-10-14T04:57:50.405Z",
    "resolved_at": null
  },
  "counters": {
    "calls": 0,
    "action_calls": 0,
    "child_runs": 0,
    "tasks_completed": 0,
    "tasks_total": 1
  },
  "input": {},
  "output": null,
  "error": null,
  "initiator": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "channel": "api",
  "owner": "tnt_3a9759864ccb4e00",
  "trigger": null,
  "parent": null,
  "parent_run_id": null,
  "root_run_id": "run_00mv67mkw52c7fa90cc9649b1053e66fd836b071f289acb667ff8ca853e65bc4608e9a45bd",
  "depth": 0,
  "attach": null,
  "deadline_at": "2026-10-14T04:57:50.405Z",
  "created_at": "2026-10-13T04:57:50.405Z",
  "started_at": "2026-10-13T04:57:56.933Z",
  "ended_at": null,
  "updated_at": "2026-10-13T04:58:02.193Z",
  "heartbeat_at": null,
  "cancel_requested_at": null,
  "cancelled_by": null,
  "cancel_reason": null,
  "cancel_message": null,
  "suspend_requested_at": null,
  "suspended_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "queued_ms": 6528,
  "run_ms": null,
  "wait_ms": null,
  "usage": null,
  "rerun_of": null,
  "labels": {
    "namespace": "docs-samples",
    "name": "sample-run-1791867412840-b05e8a"
  }
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| 409 | OPERATION_NOT_SUPPORTED：该资源类型不支持此操作。 RUN_INVALID_STATE：当前状态不允许执行该动作。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出等待点

按账本顺序列出运行的等待点。包括当前及历史的 event、timer 与 child 等待点。

`GET /automation/v1/runs/{id}/waits`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 50。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/waits" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.waits.list({
  "path": {
    "id": env("RUN_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的等待点（当前与历史），按 created_at 倒序、id 倒序排列。 |
| data[].id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| data[].run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| data[].kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| data[].state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| data[].task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| data[].task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| data[].task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| data[].resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| data[].event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| data[].child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| data[].created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| data[].expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| data[].resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "wait_wf-eebc9ef34869206fa1bcc1e2ae6375990a7ab34c5ad485ac98a4f189c4b37346",
      "run_id": "run_00mv67mkw52c7fa90cc9649b1053e66fd836b071f289acb667ff8ca853e65bc4608e9a45bd",
      "kind": "event",
      "state": "open",
      "task": {
        "reference": "/do/0/ready",
        "name": "ready"
      },
      "resume_at": null,
      "event_type": "ready",
      "child_run_id": null,
      "created_at": "2026-10-13T04:57:56.982Z",
      "expires_at": "2026-10-14T04:57:50.405Z",
      "resolved_at": null
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出运行调用

分页读取调用账本及执行结果。结果按账本顺序列出目标、参数与结果预览、状态和耗时。脚本运行读调用账本；工作流运行的动作调用记在步骤上，这里列出带动作的步骤（不含被跳过的），与 counters.action_calls 一致。

`GET /automation/v1/runs/{id}/calls`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| query: limit | `integer` | 可选；运行台账每页条数，整数 1–200，默认 50；其它集合上限为 100。 minimum: 1；maximum: 200 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/calls" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.calls.list({
  "path": {
    "id": env("RUN_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的脚本调用记录，按 seq 顺序排列。 |
| data[].id | `string` | 必填 / 必有；调用 ID，前缀 call_。 |
| data[].run_id | `string` | 必填 / 必有；发出该调用的脚本运行 ID（run_ 前缀）。 |
| data[].seq | `number` | 必填 / 必有；调用在该运行中的序号，随调用顺序递增；与 run_id 一起定位这次调用。 |
| data[].target | `object` | 必填 / 必有；被调用的目标 &#123;kind, name, revision?, version?&#125;。 不接受额外字段。 |
| data[].target.kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` | 必填 / 必有；目标类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流。 |
| data[].target.name | `string` | 必填 / 必有；目标名称：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| data[].target.revision | `string` | 可选；实际执行的动作修订 ID（actr_ 前缀）；仅动作调用有。 |
| data[].target.version | `string` | 可选；实际运行的精确版本号；仅脚本与工作流调用有。 |
| data[].args_preview | `string` | 必填 / 必有；调用参数的单行预览，由服务端截断；超过 32 KB 的原文存放在对象存储而不内联。 |
| data[].result_preview | `null` / `string` | 必填 / 必有；返回值的单行预览，由服务端截断；调用结束前为 null。 |
| data[].status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` | 必填 / 必有；调用状态。running 执行中；completed 已正常返回；faulted 失败，error 给出原因；cancelled 因运行被取消而中止。 |
| data[].started_at | `string` | 必填 / 必有；调用开始的时间（RFC 3339 UTC）。 |
| data[].ended_at | `null` / `string` | 必填 / 必有；调用结束的时间（RFC 3339 UTC）；仍在执行为 null。 |
| data[].duration_ms | `null` / `number` | 必填 / 必有；从开始到结束的毫秒数；未结束为 null。 |
| data[].error | `null` / `object` | 必填 / 必有；调用失败时的错误详情；成功或仍在执行为 null。 |
| data[].error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data[].error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data[].error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data[].error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data[].error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data[].error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data[].error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data[].error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data[].error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data[].error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data[].error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data[].error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data[].error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data[].error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data[].error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data[].error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data[].error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[].error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[].error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data[].child_run_id | `null` / `string` | 必填 / 必有；目标是脚本或工作流时，由本次调用启动的子运行 ID；动作与平台 API 调用为 null。 |
| data[].invocation_key | `string` | 必填 / 必有；标识这一次逻辑调用的键，随调用发往下游，使至少一次语义下的重试可被去重。 |
| data[].request_id | `string` / `null` | 必填 / 必有；下游响应的 X-Request-Id；尚未收到响应或响应未提供该头时为 null。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出运行产物

读取运行产物及其文件引用。按账本顺序返回类型、大小及所属步骤。

`GET /automation/v1/runs/{id}/artifacts`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 50。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/artifacts" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.artifacts.list({
  "path": {
    "id": env("RUN_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的运行产物，按 created_at 倒序、id 倒序排列。 |
| data[].id | `string` | 必填 / 必有；产物 ID，按不透明字符串处理。 |
| data[].file_id | `string` | 必填 / 必有；产物在文件服务中的文件 ID，用文件接口下载内容。 |
| data[].name | `string` | 必填 / 必有；产物文件名。 |
| data[].content_type | `string` | 必填 / 必有；产物的 MIME 类型。 |
| data[].size_in_bytes | `number` | 必填 / 必有；产物大小，单位字节。 |
| data[].task | `null` / `string` | 必填 / 必有；产生该产物的工作流步骤的 JSON Pointer；不属于某个步骤为 null。 |
| data[].created_at | `string` | 必填 / 必有；产物创建时间（RFC 3339 UTC）。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 完成等待点

仅完成 event 等待点，payload 上限 32 KiB 且须满足等待条件；timer 与 child 不支持手动完成。相同 id 与相同 payload 重放返回 replayed=true，其他重复提交返回 WAIT_ALREADY_RESOLVED，超时返回 WAIT_EXPIRED。

`POST /automation/v1/runs/{id}/waits/{wait_id}/complete`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| path: wait_id | `string` | 必填；该运行下的等待点 ID（wait_）。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 可选；可选事件去重 ID；同一等待点重复提交相同 ID 和 payload 返回 replayed=true。 |
| payload | `null` / `string` / `number` / `boolean` / `object` / `null` / `string` / `number` / `boolean` / `object` / `JSON[][]` | 必填 / 必有；事件数据，JSON 编码最多 32 KiB；必须满足等待点的过滤条件。 |
| payload（分支5).*（分支5) | `object` | 递归 JSON 值。 |
| payload（分支5).*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| payload（分支6)[]（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| payload（分支6)[]（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |
| WAIT_ID | [同一运行中 kind=event、state=open 的等待点 id](/docs/api/native/automation/listRunWaits) |

```bash
: "${RUN_ID:?Set RUN_ID}"
: "${WAIT_ID:?Set WAIT_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/waits/${WAIT_ID}/complete" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "payload": {
    "answer": 42
  }
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.waits.complete({
  "path": {
    "id": env("RUN_ID"),
    "wait_id": env("WAIT_ID")
  },
  "body": {
    "payload": {
      "answer": 42
    }
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；等待点 ID，前缀 wait_。 |
| run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件；timer 等待到点；child 等待子运行；本接口只对 event 有效。 |
| state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；完成后的等待点状态。open 仍在等待；resolved 已被满足；expired 已到期；cancelled 已取消。成功提交的事件使其变为 resolved。 |
| task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer。 |
| task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）。 |
| replayed | `boolean` | 必填 / 必有；true 表示这是对同一 id 且相同 payload 的重复提交，返回的是原结果而不是再次处理。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "wait_wf-eebc9ef34869206fa1bcc1e2ae6375990a7ab34c5ad485ac98a4f189c4b37346",
  "run_id": "run_00mv67mkw52c7fa90cc9649b1053e66fd836b071f289acb667ff8ca853e65bc4608e9a45bd",
  "kind": "event",
  "state": "resolved",
  "task": {
    "reference": "/do/0/ready",
    "name": "ready"
  },
  "resume_at": null,
  "event_type": "ready",
  "child_run_id": null,
  "created_at": "2026-10-13T04:57:56.982Z",
  "expires_at": "2026-10-14T04:57:50.405Z",
  "resolved_at": "2026-10-13T04:58:03.972Z",
  "replayed": false
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 WAIT_NOT_FOUND：运行中不存在该等待点。 |
| 409 | OPERATION_NOT_SUPPORTED：该资源类型不支持此操作。 WAIT_ALREADY_RESOLVED：等待点已关闭，或重复事件与原提交不同。 |
| 410 | WAIT_EXPIRED：等待点已超过到期时间。 |
| 413 | PAYLOAD_TOO_LARGE：请求内容超过本操作允许的大小。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出运行步骤

分页读取步骤账本；include=planned 附带尚未执行的顶层步骤，group_by=reference 按步骤引用聚合次数、状态和耗时。

`GET /automation/v1/runs/{id}/tasks`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| query: limit | `integer` | 可选；运行台账每页条数，整数 1–200，默认 50；其它集合上限为 100。 minimum: 1；maximum: 200 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: include | `"planned"` | 可选；仅支持 planned，附带尚未执行的顶层步骤；省略只读已有步骤。 |
| query: group_by | `"reference"` | 可选；仅支持 reference，按步骤引用聚合循环执行；省略返回逐次步骤。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/tasks" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.tasks.list({
  "path": {
    "id": env("RUN_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object` / `object[]` | 必填 / 必有；本页的工作流步骤记录；group_by=reference 时为按 reference 聚合的 TaskGroup 行，按执行顺序排列。 |
| data[]（分支1).id | `string` | 必填 / 必有；步骤执行记录的标识，按不透明字符串处理。 |
| data[]（分支1).run_id | `string` | 必填 / 必有；所属运行 ID。 |
| data[]（分支1).reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start。 |
| data[]（分支1).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| data[]（分支1).kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| data[]（分支1).iteration | `number[]` | 必填 / 必有；外层 for 循环的当前迭代下标，由外到内；不在循环中为空数组。 |
| data[]（分支1).attempt | `number` | 必填 / 必有；第几次尝试；步骤因重试而重新执行时递增。 |
| data[]（分支1).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；步骤状态，取值与运行状态相同。pending 尚未开始；running 执行中；waiting 在等待事件、定时器或子运行；suspended 因运行被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| data[]（分支1).skipped | `boolean` | 必填 / 必有；true 表示该步骤被跳过而没有实际执行。 |
| data[]（分支1).started_at | `null` / `string` | 必填 / 必有；步骤开始的时间（RFC 3339 UTC）；未开始为 null。 |
| data[]（分支1).ended_at | `null` / `string` | 必填 / 必有；步骤结束的时间（RFC 3339 UTC）；未结束为 null。 |
| data[]（分支1).duration_ms | `null` / `number` | 必填 / 必有；执行耗时毫秒数；未结束为 null。 |
| data[]（分支1).input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[]（分支1).input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支1).input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支1).input_truncated | `boolean` | 必填 / 必有；true 表示 input 超过 32 KB 已被截断。 |
| data[]（分支1).output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[]（分支1).output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支1).output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支1).output_truncated | `boolean` | 必填 / 必有；输出超过内联限制而被省略时为 true。 |
| data[]（分支1).error | `null` / `object` | 必填 / 必有；步骤失败时的错误详情；未失败为 null。 |
| data[]（分支1).error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data[]（分支1).error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data[]（分支1).error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data[]（分支1).error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data[]（分支1).error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data[]（分支1).error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data[]（分支1).error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data[]（分支1).error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data[]（分支1).error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data[]（分支1).error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data[]（分支1).error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data[]（分支1).error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data[]（分支1).error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data[]（分支1).error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data[]（分支1).error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data[]（分支1).error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data[]（分支1).error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[]（分支1).error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[]（分支1).error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data[]（分支1).action | `null` / `object` | 必填 / 必有；call 步骤执行的动作 &#123;name, revision&#125;；其它步骤为 null。 |
| data[]（分支1).action（分支2).name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data[]（分支1).action（分支2).revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data[]（分支1).child_run | `null` / `object` | 必填 / 必有；run 步骤启动的子运行摘要 &#123;id, number, status, resolved_version&#125;；其它步骤为 null。 |
| data[]（分支1).child_run（分支2).id | `string` | 必填 / 必有；子运行 ID（run_ 前缀），创建后即可读取。 |
| data[]（分支1).child_run（分支2).number | `null` / `number` | 必填 / 必有；子运行在其定义内的序号；临时运行为 null。 |
| data[]（分支1).child_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；子运行的状态。pending 尚未开始；running 执行中；waiting 在等待；suspended 已暂停；cancelled 已取消；faulted 失败；completed 成功完成。等待型子运行在结束时补全终态，detach 的子运行只记录启动时的状态。 |
| data[]（分支1).child_run（分支2).resolved_version | `null` / `string` | 必填 / 必有；子运行解析到的精确版本号；临时运行为 null。 |
| data[]（分支2).reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start。 |
| data[]（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| data[]（分支2).count | `number` | 必填 / 必有；该 reference 下合并的执行记录条数（循环的迭代数）。 |
| data[]（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；步骤状态，取值与运行状态相同。pending 尚未开始；running 执行中；waiting 在等待事件、定时器或子运行；suspended 因运行被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| data[]（分支2).duration_ms | `null` / `number` | 必填 / 必有；执行耗时毫秒数；未结束为 null。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取运行事件

读取 CloudEvents 账本或订阅实时事件流。默认返回 CloudEvents 账本页，Accept: text/event-stream 开启实时流，事件名为 ai.praxis.automation.run.status、ai.praxis.automation.run.progress、ai.praxis.automation.call.started、ai.praxis.automation.call.completed、ai.praxis.automation.task.started、ai.praxis.automation.task.completed、ai.praxis.automation.wait.created、ai.praxis.automation.wait.resolved。id 为续传游标，Last-Event-ID 优先于 cursor；每 20 秒发送 : ping，运行终态后以 event: end 收尾。

`GET /automation/v1/runs/{id}/events`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 50。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| header: Accept | `"application/json"` / `"text/event-stream"` | 可选；application/json（默认）读取账本页；text/event-stream 订阅实时流。 |
| header: Last-Event-ID | `string` | 可选；SSE 续传游标，读取该事件之后的记录；优先于 cursor，仅用于实时流。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/events" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Accept: text/event-stream"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
for await (const event of automation.runs.events({
  "path": {
    "id": env("RUN_ID")
  }
})) {
  console.log(event);
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object` / `object` / `object` / `object` / `object[]` | 必填 / 必有；本页的账本事件（RunEvent），按事件顺序排列。 |
| data[]（分支1).type | `"ai.praxis.automation.run.status"` | 必填 / 必有；事件类型：固定为 ai.praxis.automation.run.status，运行状态发生变化，data 为完整的运行。 |
| data[]（分支1).data | `object` | 必填 / 必有；一次运行的完整状态：目标、状态、输入输出、错误、发起方、运行树位置和各类时间。 不接受额外字段。 |
| data[]（分支1).data.id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| data[]（分支1).data.kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data[]（分支1).data.number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| data[]（分支1).data.definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| data[]（分支1).data.definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| data[]（分支1).data.definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| data[]（分支1).data.target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| data[]（分支1).data.resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| data[]（分支1).data.source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| data[]（分支1).data.language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| data[]（分支1).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| data[]（分支1).data.progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| data[]（分支1).data.progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| data[]（分支1).data.progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| data[]（分支1).data.progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| data[]（分支1).data.progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| data[]（分支1).data.current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| data[]（分支1).data.current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| data[]（分支1).data.current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| data[]（分支1).data.current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| data[]（分支1).data.current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| data[]（分支1).data.current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| data[]（分支1).data.current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| data[]（分支1).data.current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| data[]（分支1).data.current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| data[]（分支1).data.current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| data[]（分支1).data.current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| data[]（分支1).data.current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| data[]（分支1).data.current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| data[]（分支1).data.current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| data[]（分支1).data.counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| data[]（分支1).data.counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| data[]（分支1).data.counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| data[]（分支1).data.counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| data[]（分支1).data.counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| data[]（分支1).data.counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| data[]（分支1).data.input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[]（分支1).data.input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支1).data.input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支1).data.output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[]（分支1).data.output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支1).data.output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支1).data.error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| data[]（分支1).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data[]（分支1).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data[]（分支1).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data[]（分支1).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data[]（分支1).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data[]（分支1).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data[]（分支1).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data[]（分支1).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data[]（分支1).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data[]（分支1).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data[]（分支1).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data[]（分支1).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data[]（分支1).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data[]（分支1).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data[]（分支1).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data[]（分支1).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data[]（分支1).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[]（分支1).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[]（分支1).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data[]（分支1).data.initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| data[]（分支1).data.initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[]（分支1).data.initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[]（分支1).data.channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| data[]（分支1).data.owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| data[]（分支1).data.parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| data[]（分支1).data.parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| data[]（分支1).data.parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| data[]（分支1).data.parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| data[]（分支1).data.parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| data[]（分支1).data.parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| data[]（分支1).data.parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| data[]（分支1).data.root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| data[]（分支1).data.depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| data[]（分支1).data.attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| data[]（分支1).data.deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| data[]（分支1).data.created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| data[]（分支1).data.started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| data[]（分支1).data.ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| data[]（分支1).data.updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| data[]（分支1).data.heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| data[]（分支1).data.cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| data[]（分支1).data.cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| data[]（分支1).data.cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[]（分支1).data.cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[]（分支1).data.cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| data[]（分支1).data.suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| data[]（分支1).data.suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| data[]（分支1).data.suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[]（分支1).data.suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[]（分支1).data.queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| data[]（分支1).data.run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| data[]（分支1).data.wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| data[]（分支1).data.usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| data[]（分支1).data.usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| data[]（分支1).data.usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| data[]（分支1).data.usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| data[]（分支1).data.usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| data[]（分支1).data.usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| data[]（分支1).data.usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| data[]（分支1).data.usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| data[]（分支1).data.rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| data[]（分支1).data.labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| data[]（分支1).data.trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| data[]（分支1).data.trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| data[]（分支1).data.trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| data[]（分支1).data.cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| data[]（分支1).data.input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| data[]（分支1).data.output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |
| data[]（分支1).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data[]（分支1).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data[]（分支1).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data[]（分支1).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data[]（分支1).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data[]（分支1).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| data[]（分支2).type | `"ai.praxis.automation.run.progress"` | 必填 / 必有；事件类型：固定为 ai.praxis.automation.run.progress，运行上报了新进度，data 为进度。 |
| data[]（分支2).data | `object` | 必填 / 必有；运行报告的进度，包含说明、已完成量与总量。 不接受额外字段。 |
| data[]（分支2).data.label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| data[]（分支2).data.current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| data[]（分支2).data.total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| data[]（分支2).data.updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| data[]（分支2).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data[]（分支2).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data[]（分支2).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data[]（分支2).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data[]（分支2).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data[]（分支2).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| data[]（分支3).type | `"ai.praxis.automation.call.started"` / `"ai.praxis.automation.call.completed"` | 必填 / 必有；事件类型。ai.praxis.automation.call.started 调用开始；ai.praxis.automation.call.completed 调用结束（成功或失败）；data 为调用记录。 |
| data[]（分支3).data | `object` | 必填 / 必有；脚本运行中的一次调用记录（动作、平台 API、脚本或工作流），按 seq 顺序排列。 不接受额外字段。 |
| data[]（分支3).data.id | `string` | 必填 / 必有；调用 ID，前缀 call_。 |
| data[]（分支3).data.run_id | `string` | 必填 / 必有；发出该调用的脚本运行 ID（run_ 前缀）。 |
| data[]（分支3).data.seq | `number` | 必填 / 必有；调用在该运行中的序号，随调用顺序递增；与 run_id 一起定位这次调用。 |
| data[]（分支3).data.target | `object` | 必填 / 必有；被调用的目标 &#123;kind, name, revision?, version?&#125;。 不接受额外字段。 |
| data[]（分支3).data.target.kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` | 必填 / 必有；目标类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流。 |
| data[]（分支3).data.target.name | `string` | 必填 / 必有；目标名称：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| data[]（分支3).data.target.revision | `string` | 可选；实际执行的动作修订 ID（actr_ 前缀）；仅动作调用有。 |
| data[]（分支3).data.target.version | `string` | 可选；实际运行的精确版本号；仅脚本与工作流调用有。 |
| data[]（分支3).data.args_preview | `string` | 必填 / 必有；调用参数的单行预览，由服务端截断；超过 32 KB 的原文存放在对象存储而不内联。 |
| data[]（分支3).data.result_preview | `null` / `string` | 必填 / 必有；返回值的单行预览，由服务端截断；调用结束前为 null。 |
| data[]（分支3).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` | 必填 / 必有；调用状态。running 执行中；completed 已正常返回；faulted 失败，error 给出原因；cancelled 因运行被取消而中止。 |
| data[]（分支3).data.started_at | `string` | 必填 / 必有；调用开始的时间（RFC 3339 UTC）。 |
| data[]（分支3).data.ended_at | `null` / `string` | 必填 / 必有；调用结束的时间（RFC 3339 UTC）；仍在执行为 null。 |
| data[]（分支3).data.duration_ms | `null` / `number` | 必填 / 必有；从开始到结束的毫秒数；未结束为 null。 |
| data[]（分支3).data.error | `null` / `object` | 必填 / 必有；调用失败时的错误详情；成功或仍在执行为 null。 |
| data[]（分支3).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data[]（分支3).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data[]（分支3).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data[]（分支3).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data[]（分支3).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data[]（分支3).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data[]（分支3).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data[]（分支3).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data[]（分支3).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data[]（分支3).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data[]（分支3).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data[]（分支3).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data[]（分支3).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data[]（分支3).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data[]（分支3).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data[]（分支3).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data[]（分支3).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[]（分支3).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[]（分支3).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data[]（分支3).data.child_run_id | `null` / `string` | 必填 / 必有；目标是脚本或工作流时，由本次调用启动的子运行 ID；动作与平台 API 调用为 null。 |
| data[]（分支3).data.invocation_key | `string` | 必填 / 必有；标识这一次逻辑调用的键，随调用发往下游，使至少一次语义下的重试可被去重。 |
| data[]（分支3).data.request_id | `string` / `null` | 必填 / 必有；下游响应的 X-Request-Id；尚未收到响应或响应未提供该头时为 null。 |
| data[]（分支3).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data[]（分支3).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data[]（分支3).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data[]（分支3).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data[]（分支3).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data[]（分支3).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| data[]（分支4).type | `"ai.praxis.automation.task.started"` / `"ai.praxis.automation.task.completed"` | 必填 / 必有；事件类型。ai.praxis.automation.task.started 步骤开始；ai.praxis.automation.task.completed 步骤结束；data 为步骤记录。 |
| data[]（分支4).data | `object` | 必填 / 必有；工作流中一个步骤的一次执行记录。循环会让同一步骤产生多条记录（iteration 不同），重试会让 attempt 递增。 不接受额外字段。 |
| data[]（分支4).data.id | `string` | 必填 / 必有；步骤执行记录的标识，按不透明字符串处理。 |
| data[]（分支4).data.run_id | `string` | 必填 / 必有；所属运行 ID。 |
| data[]（分支4).data.reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start。 |
| data[]（分支4).data.name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| data[]（分支4).data.kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| data[]（分支4).data.iteration | `number[]` | 必填 / 必有；外层 for 循环的当前迭代下标，由外到内；不在循环中为空数组。 |
| data[]（分支4).data.attempt | `number` | 必填 / 必有；第几次尝试；步骤因重试而重新执行时递增。 |
| data[]（分支4).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；步骤状态，取值与运行状态相同。pending 尚未开始；running 执行中；waiting 在等待事件、定时器或子运行；suspended 因运行被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| data[]（分支4).data.skipped | `boolean` | 必填 / 必有；true 表示该步骤被跳过而没有实际执行。 |
| data[]（分支4).data.started_at | `null` / `string` | 必填 / 必有；步骤开始的时间（RFC 3339 UTC）；未开始为 null。 |
| data[]（分支4).data.ended_at | `null` / `string` | 必填 / 必有；步骤结束的时间（RFC 3339 UTC）；未结束为 null。 |
| data[]（分支4).data.duration_ms | `null` / `number` | 必填 / 必有；执行耗时毫秒数；未结束为 null。 |
| data[]（分支4).data.input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[]（分支4).data.input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支4).data.input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支4).data.input_truncated | `boolean` | 必填 / 必有；true 表示 input 超过 32 KB 已被截断。 |
| data[]（分支4).data.output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[]（分支4).data.output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支4).data.output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[]（分支4).data.output_truncated | `boolean` | 必填 / 必有；输出超过内联限制而被省略时为 true。 |
| data[]（分支4).data.error | `null` / `object` | 必填 / 必有；步骤失败时的错误详情；未失败为 null。 |
| data[]（分支4).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data[]（分支4).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data[]（分支4).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data[]（分支4).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data[]（分支4).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data[]（分支4).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data[]（分支4).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data[]（分支4).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data[]（分支4).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data[]（分支4).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data[]（分支4).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data[]（分支4).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data[]（分支4).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data[]（分支4).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data[]（分支4).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data[]（分支4).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data[]（分支4).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[]（分支4).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data[]（分支4).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data[]（分支4).data.action | `null` / `object` | 必填 / 必有；call 步骤执行的动作 &#123;name, revision&#125;；其它步骤为 null。 |
| data[]（分支4).data.action（分支2).name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data[]（分支4).data.action（分支2).revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data[]（分支4).data.child_run | `null` / `object` | 必填 / 必有；run 步骤启动的子运行摘要 &#123;id, number, status, resolved_version&#125;；其它步骤为 null。 |
| data[]（分支4).data.child_run（分支2).id | `string` | 必填 / 必有；子运行 ID（run_ 前缀），创建后即可读取。 |
| data[]（分支4).data.child_run（分支2).number | `null` / `number` | 必填 / 必有；子运行在其定义内的序号；临时运行为 null。 |
| data[]（分支4).data.child_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；子运行的状态。pending 尚未开始；running 执行中；waiting 在等待；suspended 已暂停；cancelled 已取消；faulted 失败；completed 成功完成。等待型子运行在结束时补全终态，detach 的子运行只记录启动时的状态。 |
| data[]（分支4).data.child_run（分支2).resolved_version | `null` / `string` | 必填 / 必有；子运行解析到的精确版本号；临时运行为 null。 |
| data[]（分支4).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data[]（分支4).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data[]（分支4).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data[]（分支4).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data[]（分支4).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data[]（分支4).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| data[]（分支5).type | `"ai.praxis.automation.wait.created"` / `"ai.praxis.automation.wait.resolved"` | 必填 / 必有；事件类型。ai.praxis.automation.wait.created 等待点创建；ai.praxis.automation.wait.resolved 等待点被满足、到期或取消；data 为等待点。 |
| data[]（分支5).data | `object` | 必填 / 必有；运行上的一个等待点，工作流在它被满足、到期或取消之前不会继续。 不接受额外字段。 |
| data[]（分支5).data.id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| data[]（分支5).data.run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| data[]（分支5).data.kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| data[]（分支5).data.state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| data[]（分支5).data.task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| data[]（分支5).data.task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| data[]（分支5).data.task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| data[]（分支5).data.resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| data[]（分支5).data.event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| data[]（分支5).data.child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| data[]（分支5).data.created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| data[]（分支5).data.expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| data[]（分支5).data.resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| data[]（分支5).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data[]（分支5).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data[]（分支5).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data[]（分支5).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data[]（分支5).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data[]（分支5).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

`text/event-stream`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 可选；Resume cursor of this entry; send it back as Last-Event-ID, or as cursor on the JSON form, to continue after it. Absent on the end event. |
| event | `"ai.praxis.automation.run.status"` / `"ai.praxis.automation.run.progress"` / `"ai.praxis.automation.call.started"` / `"ai.praxis.automation.call.completed"` / `"ai.praxis.automation.task.started"` / `"ai.praxis.automation.task.completed"` / `"ai.praxis.automation.wait.created"` / `"ai.praxis.automation.wait.resolved"` / `"end"` | 必填 / 必有；SSE event name: one of ai.praxis.automation.run.status, ai.praxis.automation.run.progress, ai.praxis.automation.call.started, ai.praxis.automation.call.completed, ai.praxis.automation.task.started, ai.praxis.automation.task.completed, ai.praxis.automation.wait.created, ai.praxis.automation.wait.resolved, naming the RunEvent type carried in data; end is sent once when the run has reached a terminal status and closes the stream. |
| data | `object` / `object` / `object` / `object` / `object` / `object` | 必填 / 必有；Decoded JSON of one run event, whose shape is selected by its type; for the end event, an empty object. |
| data（分支1)（分支1).type | `"ai.praxis.automation.run.status"` | 必填 / 必有；事件类型：固定为 ai.praxis.automation.run.status，运行状态发生变化，data 为完整的运行。 |
| data（分支1)（分支1).data | `object` | 必填 / 必有；一次运行的完整状态：目标、状态、输入输出、错误、发起方、运行树位置和各类时间。 不接受额外字段。 |
| data（分支1)（分支1).data.id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| data（分支1)（分支1).data.kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| data（分支1)（分支1).data.number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| data（分支1)（分支1).data.definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| data（分支1)（分支1).data.definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| data（分支1)（分支1).data.definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| data（分支1)（分支1).data.target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| data（分支1)（分支1).data.resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| data（分支1)（分支1).data.source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| data（分支1)（分支1).data.language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| data（分支1)（分支1).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| data（分支1)（分支1).data.progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| data（分支1)（分支1).data.progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| data（分支1)（分支1).data.progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| data（分支1)（分支1).data.progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| data（分支1)（分支1).data.progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| data（分支1)（分支1).data.current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| data（分支1)（分支1).data.current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| data（分支1)（分支1).data.current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| data（分支1)（分支1).data.current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| data（分支1)（分支1).data.current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| data（分支1)（分支1).data.current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| data（分支1)（分支1).data.current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| data（分支1)（分支1).data.current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| data（分支1)（分支1).data.current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| data（分支1)（分支1).data.current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| data（分支1)（分支1).data.current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| data（分支1)（分支1).data.current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| data（分支1)（分支1).data.current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| data（分支1)（分支1).data.current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| data（分支1)（分支1).data.counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| data（分支1)（分支1).data.counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| data（分支1)（分支1).data.counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| data（分支1)（分支1).data.counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| data（分支1)（分支1).data.counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| data（分支1)（分支1).data.counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| data（分支1)（分支1).data.input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data（分支1)（分支1).data.input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data（分支1)（分支1).data.input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data（分支1)（分支1).data.output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data（分支1)（分支1).data.output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data（分支1)（分支1).data.output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data（分支1)（分支1).data.error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| data（分支1)（分支1).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data（分支1)（分支1).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data（分支1)（分支1).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data（分支1)（分支1).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data（分支1)（分支1).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data（分支1)（分支1).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data（分支1)（分支1).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data（分支1)（分支1).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data（分支1)（分支1).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data（分支1)（分支1).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data（分支1)（分支1).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data（分支1)（分支1).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data（分支1)（分支1).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data（分支1)（分支1).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data（分支1)（分支1).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data（分支1)（分支1).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data（分支1)（分支1).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data（分支1)（分支1).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data（分支1)（分支1).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data（分支1)（分支1).data.initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| data（分支1)（分支1).data.initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data（分支1)（分支1).data.initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data（分支1)（分支1).data.channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| data（分支1)（分支1).data.owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| data（分支1)（分支1).data.parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| data（分支1)（分支1).data.parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| data（分支1)（分支1).data.parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| data（分支1)（分支1).data.parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| data（分支1)（分支1).data.parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| data（分支1)（分支1).data.parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| data（分支1)（分支1).data.parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| data（分支1)（分支1).data.root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| data（分支1)（分支1).data.depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| data（分支1)（分支1).data.attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| data（分支1)（分支1).data.deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| data（分支1)（分支1).data.created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| data（分支1)（分支1).data.started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| data（分支1)（分支1).data.ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| data（分支1)（分支1).data.updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| data（分支1)（分支1).data.heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| data（分支1)（分支1).data.cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| data（分支1)（分支1).data.cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| data（分支1)（分支1).data.cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data（分支1)（分支1).data.cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data（分支1)（分支1).data.cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| data（分支1)（分支1).data.suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| data（分支1)（分支1).data.suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| data（分支1)（分支1).data.suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data（分支1)（分支1).data.suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data（分支1)（分支1).data.queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| data（分支1)（分支1).data.run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| data（分支1)（分支1).data.wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| data（分支1)（分支1).data.usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| data（分支1)（分支1).data.usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| data（分支1)（分支1).data.usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| data（分支1)（分支1).data.usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| data（分支1)（分支1).data.usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| data（分支1)（分支1).data.usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| data（分支1)（分支1).data.usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| data（分支1)（分支1).data.usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| data（分支1)（分支1).data.rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| data（分支1)（分支1).data.labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| data（分支1)（分支1).data.trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| data（分支1)（分支1).data.trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| data（分支1)（分支1).data.trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| data（分支1)（分支1).data.cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| data（分支1)（分支1).data.input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| data（分支1)（分支1).data.output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |
| data（分支1)（分支1).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data（分支1)（分支1).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data（分支1)（分支1).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data（分支1)（分支1).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data（分支1)（分支1).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data（分支1)（分支1).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| data（分支1)（分支2).type | `"ai.praxis.automation.run.progress"` | 必填 / 必有；事件类型：固定为 ai.praxis.automation.run.progress，运行上报了新进度，data 为进度。 |
| data（分支1)（分支2).data | `object` | 必填 / 必有；运行报告的进度，包含说明、已完成量与总量。 不接受额外字段。 |
| data（分支1)（分支2).data.label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| data（分支1)（分支2).data.current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| data（分支1)（分支2).data.total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| data（分支1)（分支2).data.updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| data（分支1)（分支2).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data（分支1)（分支2).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data（分支1)（分支2).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data（分支1)（分支2).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data（分支1)（分支2).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data（分支1)（分支2).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| data（分支1)（分支3).type | `"ai.praxis.automation.call.started"` / `"ai.praxis.automation.call.completed"` | 必填 / 必有；事件类型。ai.praxis.automation.call.started 调用开始；ai.praxis.automation.call.completed 调用结束（成功或失败）；data 为调用记录。 |
| data（分支1)（分支3).data | `object` | 必填 / 必有；脚本运行中的一次调用记录（动作、平台 API、脚本或工作流），按 seq 顺序排列。 不接受额外字段。 |
| data（分支1)（分支3).data.id | `string` | 必填 / 必有；调用 ID，前缀 call_。 |
| data（分支1)（分支3).data.run_id | `string` | 必填 / 必有；发出该调用的脚本运行 ID（run_ 前缀）。 |
| data（分支1)（分支3).data.seq | `number` | 必填 / 必有；调用在该运行中的序号，随调用顺序递增；与 run_id 一起定位这次调用。 |
| data（分支1)（分支3).data.target | `object` | 必填 / 必有；被调用的目标 &#123;kind, name, revision?, version?&#125;。 不接受额外字段。 |
| data（分支1)（分支3).data.target.kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` | 必填 / 必有；目标类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流。 |
| data（分支1)（分支3).data.target.name | `string` | 必填 / 必有；目标名称：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| data（分支1)（分支3).data.target.revision | `string` | 可选；实际执行的动作修订 ID（actr_ 前缀）；仅动作调用有。 |
| data（分支1)（分支3).data.target.version | `string` | 可选；实际运行的精确版本号；仅脚本与工作流调用有。 |
| data（分支1)（分支3).data.args_preview | `string` | 必填 / 必有；调用参数的单行预览，由服务端截断；超过 32 KB 的原文存放在对象存储而不内联。 |
| data（分支1)（分支3).data.result_preview | `null` / `string` | 必填 / 必有；返回值的单行预览，由服务端截断；调用结束前为 null。 |
| data（分支1)（分支3).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` | 必填 / 必有；调用状态。running 执行中；completed 已正常返回；faulted 失败，error 给出原因；cancelled 因运行被取消而中止。 |
| data（分支1)（分支3).data.started_at | `string` | 必填 / 必有；调用开始的时间（RFC 3339 UTC）。 |
| data（分支1)（分支3).data.ended_at | `null` / `string` | 必填 / 必有；调用结束的时间（RFC 3339 UTC）；仍在执行为 null。 |
| data（分支1)（分支3).data.duration_ms | `null` / `number` | 必填 / 必有；从开始到结束的毫秒数；未结束为 null。 |
| data（分支1)（分支3).data.error | `null` / `object` | 必填 / 必有；调用失败时的错误详情；成功或仍在执行为 null。 |
| data（分支1)（分支3).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data（分支1)（分支3).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data（分支1)（分支3).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data（分支1)（分支3).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data（分支1)（分支3).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data（分支1)（分支3).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data（分支1)（分支3).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data（分支1)（分支3).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data（分支1)（分支3).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data（分支1)（分支3).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data（分支1)（分支3).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data（分支1)（分支3).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data（分支1)（分支3).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data（分支1)（分支3).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data（分支1)（分支3).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data（分支1)（分支3).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data（分支1)（分支3).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data（分支1)（分支3).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data（分支1)（分支3).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data（分支1)（分支3).data.child_run_id | `null` / `string` | 必填 / 必有；目标是脚本或工作流时，由本次调用启动的子运行 ID；动作与平台 API 调用为 null。 |
| data（分支1)（分支3).data.invocation_key | `string` | 必填 / 必有；标识这一次逻辑调用的键，随调用发往下游，使至少一次语义下的重试可被去重。 |
| data（分支1)（分支3).data.request_id | `string` / `null` | 必填 / 必有；下游响应的 X-Request-Id；尚未收到响应或响应未提供该头时为 null。 |
| data（分支1)（分支3).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data（分支1)（分支3).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data（分支1)（分支3).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data（分支1)（分支3).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data（分支1)（分支3).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data（分支1)（分支3).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| data（分支1)（分支4).type | `"ai.praxis.automation.task.started"` / `"ai.praxis.automation.task.completed"` | 必填 / 必有；事件类型。ai.praxis.automation.task.started 步骤开始；ai.praxis.automation.task.completed 步骤结束；data 为步骤记录。 |
| data（分支1)（分支4).data | `object` | 必填 / 必有；工作流中一个步骤的一次执行记录。循环会让同一步骤产生多条记录（iteration 不同），重试会让 attempt 递增。 不接受额外字段。 |
| data（分支1)（分支4).data.id | `string` | 必填 / 必有；步骤执行记录的标识，按不透明字符串处理。 |
| data（分支1)（分支4).data.run_id | `string` | 必填 / 必有；所属运行 ID。 |
| data（分支1)（分支4).data.reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start。 |
| data（分支1)（分支4).data.name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| data（分支1)（分支4).data.kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| data（分支1)（分支4).data.iteration | `number[]` | 必填 / 必有；外层 for 循环的当前迭代下标，由外到内；不在循环中为空数组。 |
| data（分支1)（分支4).data.attempt | `number` | 必填 / 必有；第几次尝试；步骤因重试而重新执行时递增。 |
| data（分支1)（分支4).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；步骤状态，取值与运行状态相同。pending 尚未开始；running 执行中；waiting 在等待事件、定时器或子运行；suspended 因运行被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| data（分支1)（分支4).data.skipped | `boolean` | 必填 / 必有；true 表示该步骤被跳过而没有实际执行。 |
| data（分支1)（分支4).data.started_at | `null` / `string` | 必填 / 必有；步骤开始的时间（RFC 3339 UTC）；未开始为 null。 |
| data（分支1)（分支4).data.ended_at | `null` / `string` | 必填 / 必有；步骤结束的时间（RFC 3339 UTC）；未结束为 null。 |
| data（分支1)（分支4).data.duration_ms | `null` / `number` | 必填 / 必有；执行耗时毫秒数；未结束为 null。 |
| data（分支1)（分支4).data.input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data（分支1)（分支4).data.input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data（分支1)（分支4).data.input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data（分支1)（分支4).data.input_truncated | `boolean` | 必填 / 必有；true 表示 input 超过 32 KB 已被截断。 |
| data（分支1)（分支4).data.output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data（分支1)（分支4).data.output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data（分支1)（分支4).data.output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data（分支1)（分支4).data.output_truncated | `boolean` | 必填 / 必有；输出超过内联限制而被省略时为 true。 |
| data（分支1)（分支4).data.error | `null` / `object` | 必填 / 必有；步骤失败时的错误详情；未失败为 null。 |
| data（分支1)（分支4).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| data（分支1)（分支4).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| data（分支1)（分支4).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| data（分支1)（分支4).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| data（分支1)（分支4).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| data（分支1)（分支4).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| data（分支1)（分支4).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| data（分支1)（分支4).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| data（分支1)（分支4).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| data（分支1)（分支4).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data（分支1)（分支4).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data（分支1)（分支4).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| data（分支1)（分支4).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| data（分支1)（分支4).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| data（分支1)（分支4).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| data（分支1)（分支4).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| data（分支1)（分支4).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data（分支1)（分支4).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| data（分支1)（分支4).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| data（分支1)（分支4).data.action | `null` / `object` | 必填 / 必有；call 步骤执行的动作 &#123;name, revision&#125;；其它步骤为 null。 |
| data（分支1)（分支4).data.action（分支2).name | `string` | 必填 / 必有；动作全名 ns/name。 |
| data（分支1)（分支4).data.action（分支2).revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| data（分支1)（分支4).data.child_run | `null` / `object` | 必填 / 必有；run 步骤启动的子运行摘要 &#123;id, number, status, resolved_version&#125;；其它步骤为 null。 |
| data（分支1)（分支4).data.child_run（分支2).id | `string` | 必填 / 必有；子运行 ID（run_ 前缀），创建后即可读取。 |
| data（分支1)（分支4).data.child_run（分支2).number | `null` / `number` | 必填 / 必有；子运行在其定义内的序号；临时运行为 null。 |
| data（分支1)（分支4).data.child_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；子运行的状态。pending 尚未开始；running 执行中；waiting 在等待；suspended 已暂停；cancelled 已取消；faulted 失败；completed 成功完成。等待型子运行在结束时补全终态，detach 的子运行只记录启动时的状态。 |
| data（分支1)（分支4).data.child_run（分支2).resolved_version | `null` / `string` | 必填 / 必有；子运行解析到的精确版本号；临时运行为 null。 |
| data（分支1)（分支4).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data（分支1)（分支4).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data（分支1)（分支4).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data（分支1)（分支4).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data（分支1)（分支4).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data（分支1)（分支4).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| data（分支1)（分支5).type | `"ai.praxis.automation.wait.created"` / `"ai.praxis.automation.wait.resolved"` | 必填 / 必有；事件类型。ai.praxis.automation.wait.created 等待点创建；ai.praxis.automation.wait.resolved 等待点被满足、到期或取消；data 为等待点。 |
| data（分支1)（分支5).data | `object` | 必填 / 必有；运行上的一个等待点，工作流在它被满足、到期或取消之前不会继续。 不接受额外字段。 |
| data（分支1)（分支5).data.id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| data（分支1)（分支5).data.run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| data（分支1)（分支5).data.kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| data（分支1)（分支5).data.state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| data（分支1)（分支5).data.task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| data（分支1)（分支5).data.task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| data（分支1)（分支5).data.task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| data（分支1)（分支5).data.resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| data（分支1)（分支5).data.event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| data（分支1)（分支5).data.child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| data（分支1)（分支5).data.created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| data（分支1)（分支5).data.expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| data（分支1)（分支5).data.resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| data（分支1)（分支5).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| data（分支1)（分支5).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| data（分支1)（分支5).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| data（分支1)（分支5).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| data（分支1)（分支5).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data（分支1)（分支5).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| （分支1).event | `"ai.praxis.automation.run.status"` / `"ai.praxis.automation.run.progress"` / `"ai.praxis.automation.call.started"` / `"ai.praxis.automation.call.completed"` / `"ai.praxis.automation.task.started"` / `"ai.praxis.automation.task.completed"` / `"ai.praxis.automation.wait.created"` / `"ai.praxis.automation.wait.resolved"` | 可选；SSE event name: one of ai.praxis.automation.run.status, ai.praxis.automation.run.progress, ai.praxis.automation.call.started, ai.praxis.automation.call.completed, ai.praxis.automation.task.started, ai.praxis.automation.task.completed, ai.praxis.automation.wait.created, ai.praxis.automation.wait.resolved, naming the RunEvent type carried in data. |
| （分支1).data | `object` / `object` / `object` / `object` / `object` | 可选；运行账本中的一条 CloudEvents 事件，载荷带完整投影，收到后不必回拉。type 决定 data 的类型：run.status 为运行，run.progress 为进度，call.* 为调用，task.* 为步骤，wait.* 为等待点。 |
| （分支1).data（分支1).type | `"ai.praxis.automation.run.status"` | 必填 / 必有；事件类型：固定为 ai.praxis.automation.run.status，运行状态发生变化，data 为完整的运行。 |
| （分支1).data（分支1).data | `object` | 必填 / 必有；一次运行的完整状态：目标、状态、输入输出、错误、发起方、运行树位置和各类时间。 不接受额外字段。 |
| （分支1).data（分支1).data.id | `string` | 必填 / 必有；不透明运行 ID。新建非确定性 ID 为 run_ + 10 位 base36 毫秒时间前缀 + 64 位 hex DO ID，共 78 字符；旧随机 ID 为 46 字符，历史及确定性 ID 仍有效。同毫秒内不保证创建顺序。 |
| （分支1).data（分支1).data.kind | `"script"` / `"workflow"` | 必填 / 必有；编排类型。script 为 TypeScript 脚本，一次执行；workflow 为 YAML 工作流，由步骤组成，可等待事件、定时器或子运行并可暂停。 |
| （分支1).data（分支1).data.number | `null` / `number` | 必填 / 必有；运行在其脚本或工作流内的递增序号；临时运行为 null。 |
| （分支1).data（分支1).data.definition | `null` / `object` | 必填 / 必有；运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行（直接传 source）为 null。 |
| （分支1).data（分支1).data.definition（分支2).namespace | `string` | 必填 / 必有；脚本或工作流的命名空间。 |
| （分支1).data（分支1).data.definition（分支2).name | `string` | 必填 / 必有；脚本或工作流的名字。 |
| （分支1).data（分支1).data.target | `null` / `string` | 必填 / 必有；创建时 target 参数的原文（如 acme/report@latest）；临时运行为 null。 |
| （分支1).data（分支1).data.resolved_version | `null` / `string` | 必填 / 必有；target 解析到的精确版本号；临时运行为 null。 |
| （分支1).data（分支1).data.source_digest | `null` / `string` | 必填 / 必有；临时运行的源码摘要，可用于读取源码；由已发布定义启动的运行为 null。 |
| （分支1).data（分支1).data.language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| （分支1).data（分支1).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；运行状态。pending 已创建尚未开始；running 执行中；waiting 工作流在等待事件、定时器或子运行；suspended 工作流被暂停；cancelled 已取消；faulted 失败，error 给出原因；completed 成功完成，output 为结果。后三种是终态。 |
| （分支1).data（分支1).data.progress | `null` / `object` | 必填 / 必有；运行报告的最新进度 &#123;label, current, total, updated_at&#125;；未报告为 null。 |
| （分支1).data（分支1).data.progress（分支2).label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| （分支1).data（分支1).data.progress（分支2).current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| （分支1).data（分支1).data.progress（分支2).total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| （分支1).data（分支1).data.progress（分支2).updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| （分支1).data（分支1).data.current_wait | `null` / `object` | 必填 / 必有；运行当前未完成的等待点；不在等待为 null。 |
| （分支1).data（分支1).data.current_wait（分支2).id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| （分支1).data（分支1).data.current_wait（分支2).run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| （分支1).data（分支1).data.current_wait（分支2).kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| （分支1).data（分支1).data.current_wait（分支2).state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| （分支1).data（分支1).data.current_wait（分支2).task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| （分支1).data（分支1).data.current_wait（分支2).task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| （分支1).data（分支1).data.current_wait（分支2).task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| （分支1).data（分支1).data.current_wait（分支2).resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| （分支1).data（分支1).data.current_wait（分支2).event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| （分支1).data（分支1).data.current_wait（分支2).child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| （分支1).data（分支1).data.current_wait（分支2).created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| （分支1).data（分支1).data.current_wait（分支2).expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| （分支1).data（分支1).data.current_wait（分支2).resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| （分支1).data（分支1).data.counters | `object` | 必填 / 必有；运行的累计计数。 不接受额外字段。 |
| （分支1).data（分支1).data.counters.calls | `number` | 必填 / 必有；脚本发出的调用总数。 |
| （分支1).data（分支1).data.counters.action_calls | `number` | 必填 / 必有；其中调用动作的次数。 |
| （分支1).data（分支1).data.counters.child_runs | `number` | 必填 / 必有；启动的子运行数。 |
| （分支1).data（分支1).data.counters.tasks_completed | `number` | 必填 / 必有；工作流已完成的步骤数。 |
| （分支1).data（分支1).data.counters.tasks_total | `null` / `number` | 必填 / 必有；工作流顶层步骤总数；脚本运行为 null。 |
| （分支1).data（分支1).data.input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| （分支1).data（分支1).data.input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).data（分支1).data.input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).data（分支1).data.output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| （分支1).data（分支1).data.output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).data（分支1).data.output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).data（分支1).data.error | `null` / `object` | 必填 / 必有；运行失败（faulted）时的错误详情；未失败为 null。 |
| （分支1).data（分支1).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| （分支1).data（分支1).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| （分支1).data（分支1).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| （分支1).data（分支1).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| （分支1).data（分支1).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| （分支1).data（分支1).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| （分支1).data（分支1).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| （分支1).data（分支1).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| （分支1).data（分支1).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| （分支1).data（分支1).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| （分支1).data（分支1).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| （分支1).data（分支1).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| （分支1).data（分支1).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| （分支1).data（分支1).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| （分支1).data（分支1).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| （分支1).data（分支1).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| （分支1).data（分支1).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| （分支1).data（分支1).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| （分支1).data（分支1).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| （分支1).data（分支1).data.initiator | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| （分支1).data（分支1).data.initiator.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| （分支1).data（分支1).data.initiator.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| （分支1).data（分支1).data.channel | `"run"` / `"console"` / `"api"` / `"internal"` / `"trigger"` | 必填 / 必有；请求进入平台的渠道。console 为控制台（经 BFF）；api 为公开 API 调用；internal 为平台内部服务调用；run 为由另一个运行创建的子运行；trigger 为触发器启动。 |
| （分支1).data（分支1).data.owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| （分支1).data（分支1).data.parent | `null` / `object` | 必填 / 必有；派生本运行的父运行 &#123;id, number, definition&#125;；根运行为 null。 |
| （分支1).data（分支1).data.parent（分支2).id | `string` | 必填 / 必有；父运行 ID（run_ 前缀）。 |
| （分支1).data（分支1).data.parent（分支2).number | `null` / `number` | 必填 / 必有；父运行在其定义内的序号；父运行是临时运行时为 null。 |
| （分支1).data（分支1).data.parent（分支2).definition | `null` / `object` | 必填 / 必有；父运行所属的脚本或工作流 &#123;namespace, name&#125;；临时运行为 null。 |
| （分支1).data（分支1).data.parent（分支2).definition（分支2).namespace | `string` | 必填 / 必有；父运行所属定义的命名空间。 |
| （分支1).data（分支1).data.parent（分支2).definition（分支2).name | `string` | 必填 / 必有；父运行所属定义的名字。 |
| （分支1).data（分支1).data.parent_run_id | `string` / `null` | 必填 / 必有；派生出本运行的父运行 id；根运行为 null |
| （分支1).data（分支1).data.root_run_id | `string` | 必填 / 必有；运行树根运行的 ID；根运行自身指向自己。 |
| （分支1).data（分支1).data.depth | `number` | 必填 / 必有；运行树中的深度：根运行为 0，每一层子运行加 1，最大 10。 |
| （分支1).data（分支1).data.attach | `null` / `"wait"` / `"detach"` | 必填 / 必有；子运行与父运行的关系。wait 表示父运行等待子运行结束，且子运行的截止时间不晚于父运行；detach 表示父运行不等待，也不会因父运行取消而被取消；根运行为 null。 |
| （分支1).data（分支1).data.deadline_at | `string` | 必填 / 必有；运行的截止时间（RFC 3339 UTC）：创建时间加 deadline_seconds（脚本默认且最多 300 秒，工作流默认 86400 秒、最多 604800 秒），等待型子运行不晚于父运行截止前 1 秒。 |
| （分支1).data（分支1).data.created_at | `string` | 必填 / 必有；运行创建时间（RFC 3339 UTC）。 |
| （分支1).data（分支1).data.started_at | `null` / `string` | 必填 / 必有；开始执行的时间（RFC 3339 UTC）；仍在排队为 null。 |
| （分支1).data（分支1).data.ended_at | `null` / `string` | 必填 / 必有；进入终态的时间（RFC 3339 UTC）；尚未结束为 null。 |
| （分支1).data（分支1).data.updated_at | `string` | 必填 / 必有；运行记录最近一次更新的时间（RFC 3339 UTC）。 |
| （分支1).data（分支1).data.heartbeat_at | `null` / `string` | 必填 / 必有；执行器最近一次存活信号的时间（RFC 3339 UTC）；尚未开始为 null。 |
| （分支1).data（分支1).data.cancel_requested_at | `null` / `string` | 必填 / 必有；收到取消请求的时间（RFC 3339 UTC）；未取消为 null。 |
| （分支1).data（分支1).data.cancelled_by | `null` / `object` | 必填 / 必有；请求取消的主体；未取消或非人为取消为 null。 |
| （分支1).data（分支1).data.cancelled_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| （分支1).data（分支1).data.cancelled_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| （分支1).data（分支1).data.cancel_reason | `null` / `"user"` / `"parent_cancelled"` / `"deadline"` / `"executor_lost"` | 必填 / 必有；取消原因。user 为用户取消；parent_cancelled 为父运行被取消而级联取消；deadline 为超过截止时间；executor_lost 为执行器丢失；未取消为 null。 |
| （分支1).data（分支1).data.suspend_requested_at | `null` / `string` | 必填 / 必有；请求暂停工作流的时间（RFC 3339 UTC）；未暂停为 null。 |
| （分支1).data（分支1).data.suspended_by | `null` / `object` | 必填 / 必有；请求暂停的主体；未暂停为 null。 |
| （分支1).data（分支1).data.suspended_by（分支2).type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| （分支1).data（分支1).data.suspended_by（分支2).id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| （分支1).data（分支1).data.queued_ms | `null` / `number` | 必填 / 必有；从创建到开始执行的排队毫秒数；尚未开始为 null。 |
| （分支1).data（分支1).data.run_ms | `null` / `number` | 必填 / 必有；实际执行毫秒数，不含等待点上的等待时间；结束后固定。 |
| （分支1).data（分支1).data.wait_ms | `null` / `number` | 必填 / 必有；在等待点上累计等待的毫秒数；尚无等待为 null。 |
| （分支1).data（分支1).data.usage | `object` / `null` | 必填 / 必有；仅单个运行详情（含 expand）返回；列表为 null。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| （分支1).data（分支1).data.usage（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| （分支1).data（分支1).data.usage（分支1).cost | `string` | 必填 / 必有；仅本运行自身的已评级实扣（不含子运行），美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| （分支1).data（分支1).data.usage（分支1).pending_events | `integer` | 必填 / 必有；本运行自身尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| （分支1).data（分支1).data.usage（分支1).by_service | `object[]` | 必填 / 必有；本运行按服务拆分的实扣，每项为 service 与 cost（6 位小数美元字符串）；没有用量时为空数组。 |
| （分支1).data（分支1).data.usage（分支1).by_service[].service | `string` | 必填 / 必有；产生用量的服务名，例如 router 或 search。 |
| （分支1).data（分支1).data.usage（分支1).by_service[].cost | `string` | 必填 / 必有；该服务已评级实扣的美元十进制字符串，精确到 6 位小数。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| （分支1).data（分支1).data.usage（分支1).tree_cost | `string` / `null` | 必填 / 必有；仅根运行返回整棵运行树的已评级实扣（含自身），6 位小数美元字符串；子运行为 null。 |
| （分支1).data（分支1).data.rerun_of | `null` / `string` | 必填 / 必有；重跑来源：本运行是对哪个运行（run_ ID）的重跑；否则为 null。 |
| （分支1).data（分支1).data.labels | `object` | 必填 / 必有；用户标签与系统标签；触发器运行支持 64 个用户标签，系统标签不占用名额。 |
| （分支1).data（分支1).data.trigger | `object` / `null` | 必填 / 必有；启动本运行的触发器 &#123;id, name&#125;；不是触发器启动时为 null。 |
| （分支1).data（分支1).data.trigger（分支1).id | `string` | 必填 / 必有；启动本运行的触发器 ID（trg_ 前缀）。 |
| （分支1).data（分支1).data.trigger（分支1).name | `string` | 必填 / 必有；启动本运行的触发器名称。 |
| （分支1).data（分支1).data.cancel_message | `string` / `null` | 必填 / 必有；用户提供的取消备注（1–500 字符）；未提供时为 null，cancel_reason 枚举不变。 |
| （分支1).data（分支1).data.input_truncated | `boolean` | 可选；列表省略外置 input 时为 true，此时 input 为 null；内联值不变，运行详情返回完整值。 |
| （分支1).data（分支1).data.output_truncated | `boolean` | 可选；列表省略外置 output 时为 true，此时 output 为 null；内联值不变，运行详情返回完整值。 |
| （分支1).data（分支1).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| （分支1).data（分支1).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| （分支1).data（分支1).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| （分支1).data（分支1).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| （分支1).data（分支1).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| （分支1).data（分支1).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| （分支1).data（分支2).type | `"ai.praxis.automation.run.progress"` | 必填 / 必有；事件类型：固定为 ai.praxis.automation.run.progress，运行上报了新进度，data 为进度。 |
| （分支1).data（分支2).data | `object` | 必填 / 必有；运行报告的进度，包含说明、已完成量与总量。 不接受额外字段。 |
| （分支1).data（分支2).data.label | `string` | 必填 / 必有；进度说明文字，例如当前阶段。 |
| （分支1).data（分支2).data.current | `null` / `number` | 必填 / 必有；已完成的数量；未报告为 null。 |
| （分支1).data（分支2).data.total | `null` / `number` | 必填 / 必有；总量；未知为 null。 |
| （分支1).data（分支2).data.updated_at | `string` | 必填 / 必有；进度最近一次更新的时间（RFC 3339 UTC）。 |
| （分支1).data（分支2).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| （分支1).data（分支2).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| （分支1).data（分支2).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| （分支1).data（分支2).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| （分支1).data（分支2).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| （分支1).data（分支2).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| （分支1).data（分支3).type | `"ai.praxis.automation.call.started"` / `"ai.praxis.automation.call.completed"` | 必填 / 必有；事件类型。ai.praxis.automation.call.started 调用开始；ai.praxis.automation.call.completed 调用结束（成功或失败）；data 为调用记录。 |
| （分支1).data（分支3).data | `object` | 必填 / 必有；脚本运行中的一次调用记录（动作、平台 API、脚本或工作流），按 seq 顺序排列。 不接受额外字段。 |
| （分支1).data（分支3).data.id | `string` | 必填 / 必有；调用 ID，前缀 call_。 |
| （分支1).data（分支3).data.run_id | `string` | 必填 / 必有；发出该调用的脚本运行 ID（run_ 前缀）。 |
| （分支1).data（分支3).data.seq | `number` | 必填 / 必有；调用在该运行中的序号，随调用顺序递增；与 run_id 一起定位这次调用。 |
| （分支1).data（分支3).data.target | `object` | 必填 / 必有；被调用的目标 &#123;kind, name, revision?, version?&#125;。 不接受额外字段。 |
| （分支1).data（分支3).data.target.kind | `"action"` / `"script"` / `"workflow"` / `"platform_api"` | 必填 / 必有；目标类型。action 为动作；platform_api 为平台 API 操作；script 为脚本；workflow 为工作流。 |
| （分支1).data（分支3).data.target.name | `string` | 必填 / 必有；目标名称：动作为 ns/name，平台 API 为操作名，脚本与工作流为 ns/name。 |
| （分支1).data（分支3).data.target.revision | `string` | 可选；实际执行的动作修订 ID（actr_ 前缀）；仅动作调用有。 |
| （分支1).data（分支3).data.target.version | `string` | 可选；实际运行的精确版本号；仅脚本与工作流调用有。 |
| （分支1).data（分支3).data.args_preview | `string` | 必填 / 必有；调用参数的单行预览，由服务端截断；超过 32 KB 的原文存放在对象存储而不内联。 |
| （分支1).data（分支3).data.result_preview | `null` / `string` | 必填 / 必有；返回值的单行预览，由服务端截断；调用结束前为 null。 |
| （分支1).data（分支3).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` | 必填 / 必有；调用状态。running 执行中；completed 已正常返回；faulted 失败，error 给出原因；cancelled 因运行被取消而中止。 |
| （分支1).data（分支3).data.started_at | `string` | 必填 / 必有；调用开始的时间（RFC 3339 UTC）。 |
| （分支1).data（分支3).data.ended_at | `null` / `string` | 必填 / 必有；调用结束的时间（RFC 3339 UTC）；仍在执行为 null。 |
| （分支1).data（分支3).data.duration_ms | `null` / `number` | 必填 / 必有；从开始到结束的毫秒数；未结束为 null。 |
| （分支1).data（分支3).data.error | `null` / `object` | 必填 / 必有；调用失败时的错误详情；成功或仍在执行为 null。 |
| （分支1).data（分支3).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| （分支1).data（分支3).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| （分支1).data（分支3).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| （分支1).data（分支3).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| （分支1).data（分支3).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| （分支1).data（分支3).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| （分支1).data（分支3).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| （分支1).data（分支3).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| （分支1).data（分支3).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| （分支1).data（分支3).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| （分支1).data（分支3).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| （分支1).data（分支3).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| （分支1).data（分支3).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| （分支1).data（分支3).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| （分支1).data（分支3).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| （分支1).data（分支3).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| （分支1).data（分支3).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| （分支1).data（分支3).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| （分支1).data（分支3).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| （分支1).data（分支3).data.child_run_id | `null` / `string` | 必填 / 必有；目标是脚本或工作流时，由本次调用启动的子运行 ID；动作与平台 API 调用为 null。 |
| （分支1).data（分支3).data.invocation_key | `string` | 必填 / 必有；标识这一次逻辑调用的键，随调用发往下游，使至少一次语义下的重试可被去重。 |
| （分支1).data（分支3).data.request_id | `string` / `null` | 必填 / 必有；下游响应的 X-Request-Id；尚未收到响应或响应未提供该头时为 null。 |
| （分支1).data（分支3).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| （分支1).data（分支3).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| （分支1).data（分支3).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| （分支1).data（分支3).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| （分支1).data（分支3).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| （分支1).data（分支3).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| （分支1).data（分支4).type | `"ai.praxis.automation.task.started"` / `"ai.praxis.automation.task.completed"` | 必填 / 必有；事件类型。ai.praxis.automation.task.started 步骤开始；ai.praxis.automation.task.completed 步骤结束；data 为步骤记录。 |
| （分支1).data（分支4).data | `object` | 必填 / 必有；工作流中一个步骤的一次执行记录。循环会让同一步骤产生多条记录（iteration 不同），重试会让 attempt 递增。 不接受额外字段。 |
| （分支1).data（分支4).data.id | `string` | 必填 / 必有；步骤执行记录的标识，按不透明字符串处理。 |
| （分支1).data（分支4).data.run_id | `string` | 必填 / 必有；所属运行 ID。 |
| （分支1).data（分支4).data.reference | `string` | 必填 / 必有；该步骤在工作流文档中的 JSON Pointer，例如 /do/0/start。 |
| （分支1).data（分支4).data.name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中该步骤的键。 |
| （分支1).data（分支4).data.kind | `"run"` / `"call"` / `"wait"` / `"set"` / `"for"` / `"fork"` / `"try"` / `"switch"` / `"emit"` / `"raise"` / `"listen"` / `"do"` | 必填 / 必有；工作流步骤类型。call 调用动作；run 运行子脚本或子工作流；wait 等待时长；set 设置变量；for 循环；fork 并行分支；try 带捕获的块；switch 条件分支；emit 发出事件；raise 抛出错误；listen 等待事件；do 顺序执行的步骤块。 |
| （分支1).data（分支4).data.iteration | `number[]` | 必填 / 必有；外层 for 循环的当前迭代下标，由外到内；不在循环中为空数组。 |
| （分支1).data（分支4).data.attempt | `number` | 必填 / 必有；第几次尝试；步骤因重试而重新执行时递增。 |
| （分支1).data（分支4).data.status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；步骤状态，取值与运行状态相同。pending 尚未开始；running 执行中；waiting 在等待事件、定时器或子运行；suspended 因运行被暂停；cancelled 已取消；faulted 失败；completed 成功完成。 |
| （分支1).data（分支4).data.skipped | `boolean` | 必填 / 必有；true 表示该步骤被跳过而没有实际执行。 |
| （分支1).data（分支4).data.started_at | `null` / `string` | 必填 / 必有；步骤开始的时间（RFC 3339 UTC）；未开始为 null。 |
| （分支1).data（分支4).data.ended_at | `null` / `string` | 必填 / 必有；步骤结束的时间（RFC 3339 UTC）；未结束为 null。 |
| （分支1).data（分支4).data.duration_ms | `null` / `number` | 必填 / 必有；执行耗时毫秒数；未结束为 null。 |
| （分支1).data（分支4).data.input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| （分支1).data（分支4).data.input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).data（分支4).data.input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).data（分支4).data.input_truncated | `boolean` | 必填 / 必有；true 表示 input 超过 32 KB 已被截断。 |
| （分支1).data（分支4).data.output | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| （分支1).data（分支4).data.output（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).data（分支4).data.output（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支1).data（分支4).data.output_truncated | `boolean` | 必填 / 必有；输出超过内联限制而被省略时为 true。 |
| （分支1).data（分支4).data.error | `null` / `object` | 必填 / 必有；步骤失败时的错误详情；未失败为 null。 |
| （分支1).data（分支4).data.error（分支2).type | `string` | 必填 / 必有；平台错误类别，或工作流 raise 定义的完整 URI，原样保留。 |
| （分支1).data（分支4).data.error（分支2).code | `null` / `string` | 必填 / 必有；稳定错误码，可按码分支处理；没有为 null。 |
| （分支1).data（分支4).data.error（分支2).title | `string` | 必填 / 必有；错误的简短标题。 |
| （分支1).data（分支4).data.error（分支2).detail | `null` / `string` | 必填 / 必有；错误的详细说明；没有为 null。 |
| （分支1).data（分支4).data.error（分支2).source | `null` / `object` | 必填 / 必有；错误发生的位置：工作流步骤或脚本调用；未知为 null。 |
| （分支1).data（分支4).data.error（分支2).source（分支2).kind | `"call"` / `"task"` | 必填 / 必有；位置类型。task 表示工作流步骤；call 表示脚本中的调用。 |
| （分支1).data（分支4).data.error（分支2).source（分支2).reference | `string` | 可选；task 类型时：出错步骤的 JSON Pointer。 |
| （分支1).data（分支4).data.error（分支2).source（分支2).seq | `number` | 可选；call 类型时：出错调用的序号（与 Call.seq 对应）。 |
| （分支1).data（分支4).data.error（分支2).source（分支2).action | `object` | 可选；出错的动作 &#123;name, revision&#125;；错误来自动作时才有。 不接受额外字段。 |
| （分支1).data（分支4).data.error（分支2).source（分支2).action.name | `string` | 必填 / 必有；动作全名 ns/name。 |
| （分支1).data（分支4).data.error（分支2).source（分支2).action.revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| （分支1).data（分支4).data.error（分支2).request_id | `string` / `null` | 可选；导致失败的下游响应 X-Request-Id；没有下游响应标识时为 null 或省略。 |
| （分支1).data（分支4).data.error（分支2).errors | `object[]` | 可选；逐字段校验错误；pointer 使用 RFC 6901 指向字段，detail 为中文修正说明。 |
| （分支1).data（分支4).data.error（分支2).errors[].pointer | `string` | 必填 / 必有；RFC 6901 字段指针。TypeScript 源码诊断为 /source（脚本）或 /implementation/source（动作）；行列另见 line/column，不拼在指针后。 |
| （分支1).data（分支4).data.error（分支2).errors[].detail | `string` | 必填 / 必有；中文修正说明，指出该位置出了什么问题以及怎样改。 |
| （分支1).data（分支4).data.error（分支2).errors[].hint | `string` | 可选；可选的补充提示，给出下一步可执行的动作（例如改用另一个接口）。 |
| （分支1).data（分支4).data.error（分支2).errors[].line | `integer` | 可选；行号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| （分支1).data（分支4).data.error（分支2).errors[].column | `integer` | 可选；列号，从 1 起；仅有源码位置时返回。 minimum: 1 |
| （分支1).data（分支4).data.error（分支2).status | `number` | 可选；工作流 raise 声明的 HTTP 风格状态；可省略，平台错误可能不提供。 |
| （分支1).data（分支4).data.action | `null` / `object` | 必填 / 必有；call 步骤执行的动作 &#123;name, revision&#125;；其它步骤为 null。 |
| （分支1).data（分支4).data.action（分支2).name | `string` | 必填 / 必有；动作全名 ns/name。 |
| （分支1).data（分支4).data.action（分支2).revision | `string` | 必填 / 必有；执行的动作修订 ID（actr_ 前缀）。 |
| （分支1).data（分支4).data.child_run | `null` / `object` | 必填 / 必有；run 步骤启动的子运行摘要 &#123;id, number, status, resolved_version&#125;；其它步骤为 null。 |
| （分支1).data（分支4).data.child_run（分支2).id | `string` | 必填 / 必有；子运行 ID（run_ 前缀），创建后即可读取。 |
| （分支1).data（分支4).data.child_run（分支2).number | `null` / `number` | 必填 / 必有；子运行在其定义内的序号；临时运行为 null。 |
| （分支1).data（分支4).data.child_run（分支2).status | `"running"` / `"completed"` / `"faulted"` / `"cancelled"` / `"pending"` / `"waiting"` / `"suspended"` | 必填 / 必有；子运行的状态。pending 尚未开始；running 执行中；waiting 在等待；suspended 已暂停；cancelled 已取消；faulted 失败；completed 成功完成。等待型子运行在结束时补全终态，detach 的子运行只记录启动时的状态。 |
| （分支1).data（分支4).data.child_run（分支2).resolved_version | `null` / `string` | 必填 / 必有；子运行解析到的精确版本号；临时运行为 null。 |
| （分支1).data（分支4).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| （分支1).data（分支4).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| （分支1).data（分支4).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| （分支1).data（分支4).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| （分支1).data（分支4).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| （分支1).data（分支4).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| （分支1).data（分支5).type | `"ai.praxis.automation.wait.created"` / `"ai.praxis.automation.wait.resolved"` | 必填 / 必有；事件类型。ai.praxis.automation.wait.created 等待点创建；ai.praxis.automation.wait.resolved 等待点被满足、到期或取消；data 为等待点。 |
| （分支1).data（分支5).data | `object` | 必填 / 必有；运行上的一个等待点，工作流在它被满足、到期或取消之前不会继续。 不接受额外字段。 |
| （分支1).data（分支5).data.id | `string` | 必填 / 必有；等待点 ID，前缀 wait_；完成事件等待点时作为路径中的 wait_id。 |
| （分支1).data（分支5).data.run_id | `string` | 必填 / 必有；所属运行 ID（run_ 前缀）。 |
| （分支1).data（分支5).data.kind | `"event"` / `"timer"` / `"child"` | 必填 / 必有；等待类型。event 等待外部事件，可通过 runs.completeWait 提交；timer 等待到达 resume_at；child 等待子运行结束。 |
| （分支1).data（分支5).data.state | `"cancelled"` / `"open"` / `"resolved"` / `"expired"` | 必填 / 必有；等待点状态。open 仍在等待；resolved 已被满足；expired 已超过 expires_at；cancelled 已被取消，不会再被满足。 |
| （分支1).data（分支5).data.task | `null` / `object` | 必填 / 必有；产生该等待的工作流步骤 &#123;reference, name&#125;；没有对应步骤为 null。 |
| （分支1).data（分支5).data.task（分支2).reference | `string` | 必填 / 必有；步骤的 JSON Pointer，例如 /do/2/wait_payment。 |
| （分支1).data（分支5).data.task（分支2).name | `string` | 必填 / 必有；步骤名，即工作流 YAML 中的键。 |
| （分支1).data（分支5).data.resume_at | `null` / `string` | 必填 / 必有；kind=timer 时恢复运行的时刻（RFC 3339 UTC）；其它类型为 null。 |
| （分支1).data（分支5).data.event_type | `null` / `string` | 必填 / 必有；kind=event 时等待的事件类型；其它类型为 null。 |
| （分支1).data（分支5).data.child_run_id | `null` / `string` | 必填 / 必有；kind=child 时被等待的子运行 ID；其它类型为 null。 |
| （分支1).data（分支5).data.created_at | `string` | 必填 / 必有；等待点创建时间（RFC 3339 UTC）。 |
| （分支1).data（分支5).data.expires_at | `null` / `string` | 必填 / 必有；等待点到期时间（RFC 3339 UTC）；没有期限为 null。 |
| （分支1).data（分支5).data.resolved_at | `null` / `string` | 必填 / 必有；等待点被满足的时间（RFC 3339 UTC）；尚未满足为 null。 |
| （分支1).data（分支5).specversion | `"1.0"` | 必填 / 必有；CloudEvents 规范版本，固定为 1.0。 |
| （分支1).data（分支5).id | `string` | 必填 / 必有；事件 ID，在该运行的账本内唯一。 |
| （分支1).data（分支5).source | `string` | 必填 / 必有；事件来源，形如 /automation/v1/runs/&#123;id&#125;。 |
| （分支1).data（分支5).time | `string` | 必填 / 必有；事件发生的时间（RFC 3339 UTC）。 |
| （分支1).data（分支5).cursor | `string` | 必填 / 必有；事件游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| （分支1).data（分支5).seq | `number` | 必填 / 必有；事件在运行账本中的序号，严格递增。 |
| （分支2).event | `"end"` | 可选；SSE event name end: sent once when the run has reached a terminal status, and the stream then closes. |
| （分支2).data | `object` | 可选；Always an empty object for the end event. |

### 实测响应 [#实测响应]

HTTP 200

```text
id: WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwxXQ==
event: ai.praxis.automation.run.status
data: {"type":"ai.praxis.automation.run.status","data":{"id":"run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","kind":"script","number":null,"definition":null,"target":null,"resolved_version":null,"source_digest":"7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d","language":"ts","status":"pending","progress":null,"current_wait":null,"counters":{"calls":0,"action_calls":0,"child_runs":0,"tasks_completed":0,"tasks_total":null},"input":{"n":41},"output":null,"error":null,"initiator":{"type":"api_key","id":"key_3e00b8984967"},"channel":"api","owner":"tnt_3a9759864ccb4e00","trigger":null,"parent":null,"parent_run_id":null,"root_run_id":"run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","depth":0,"attach":null,"deadline_at":"2026-10-13T05:02:40.954Z","created_at":"2026-10-13T04:57:40.954Z","started_at":null,"ended_at":null,"updated_at":"2026-10-13T04:57:40.954Z","heartbeat_at":null,"cancel_requested_at":null,"cancelled_by":null,"cancel_reason":null,"cancel_message":null,"suspend_requested_at":null,"suspended_by":null,"queued_ms":null,"run_ms":null,"wait_ms":null,"usage":null,"rerun_of":null,"labels":{"namespace":"docs-samples","name":"sample-run-1791867412840-b05e8a"}},"specversion":"1.0","id":"WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwxXQ==","cursor":"WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwxXQ==","seq":1,"source":"/automation/v1/runs/run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","time":"2026-10-13T04:57:40.954Z"}

id: WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwyXQ==
event: ai.praxis.automation.run.status
data: {"type":"ai.praxis.automation.run.status","data":{"id":"run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","kind":"script","number":null,"definition":null,"target":null,"resolved_version":null,"source_digest":"7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d","language":"ts","status":"running","progress":null,"current_wait":null,"counters":{"calls":0,"action_calls":0,"child_runs":0,"tasks_completed":0,"tasks_total":null},"input":{"n":41},"output":null,"error":null,"initiator":{"type":"api_key","id":"key_3e00b8984967"},"channel":"api","owner":"tnt_3a9759864ccb4e00","trigger":null,"parent":null,"parent_run_id":null,"root_run_id":"run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","depth":0,"attach":null,"deadline_at":"2026-10-13T05:02:40.954Z","created_at":"2026-10-13T04:57:40.954Z","started_at":"2026-10-13T04:57:42.283Z","ended_at":null,"updated_at":"2026-10-13T04:57:42.283Z","heartbeat_at":"2026-10-13T04:57:42.283Z","cancel_requested_at":null,"cancelled_by":null,"cancel_reason":null,"cancel_message":null,"suspend_requested_at":null,"suspended_by":null,"queued_ms":1329,"run_ms":null,"wait_ms":null,"usage":null,"rerun_of":null,"labels":{"namespace":"docs-samples","name":"sample-run-1791867412840-b05e8a"}},"specversion":"1.0","id":"WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwyXQ==","cursor":"WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwyXQ==","seq":2,"source":"/automation/v1/runs/run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","time":"2026-10-13T04:57:42.283Z"}

id: WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwzXQ==
event: ai.praxis.automation.run.status
data: {"type":"ai.praxis.automation.run.status","data":{"id":"run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","kind":"script","number":null,"definition":null,"target":null,"resolved_version":null,"source_digest":"7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d","language":"ts","status":"completed","progress":null,"current_wait":null,"counters":{"calls":0,"action_calls":0,"child_runs":0,"tasks_completed":0,"tasks_total":null},"input":{"n":41},"output":{"answer":42},"error":null,"initiator":{"type":"api_key","id":"key_3e00b8984967"},"channel":"api","owner":"tnt_3a9759864ccb4e00","trigger":null,"parent":null,"parent_run_id":null,"root_run_id":"run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","depth":0,"attach":null,"deadline_at":"2026-10-13T05:02:40.954Z","created_at":"2026-10-13T04:57:40.954Z","started_at":"2026-10-13T04:57:42.283Z","ended_at":"2026-10-13T04:57:42.367Z","updated_at":"2026-10-13T04:57:42.367Z","heartbeat_at":"2026-10-13T04:57:42.283Z","cancel_requested_at":null,"cancelled_by":null,"cancel_reason":null,"cancel_message":null,"suspend_requested_at":null,"suspended_by":null,"queued_ms":1329,"run_ms":84,"wait_ms":null,"usage":null,"rerun_of":null,"labels":{"namespace":"docs-samples","name":"sample-run-1791867412840-b05e8a"}},"specversion":"1.0","id":"WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwzXQ==","cursor":"WyJydW5fMDBtdjY3bWRsbTVkNWQ3MDdjZDAzMTc0NGU4NDM3ZjY3ZjZhY2YwMmFmYWFiZDE4ZTc2YmY4ZGI5ZDY3NDMzM2RlNmYxZmIyZjE6ZXZlbnRzIiwzXQ==","seq":3,"source":"/automation/v1/runs/run_00mv67mdlm5d5d707cd031744e8437f67f6acf02afaabd18e76bf8db9d674333de6f1fb2f1","time":"2026-10-13T04:57:42.367Z"}

event: end
data: {}

```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取运行日志

默认返回保留期内的日志页，保留期为 30 天；Accept: text/event-stream 开启实时流，日志帧为 event: log。id 为续传游标，Last-Event-ID 优先于 cursor；每 20 秒发送 : ping，运行终态后以 event: end 收尾。

`GET /automation/v1/runs/{id}/logs`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |
| query: limit | `integer` | 可选；运行台账每页条数，整数 1–200，默认 50；其它集合上限为 100。 minimum: 1；maximum: 200 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| header: Accept | `"application/json"` / `"text/event-stream"` | 可选；application/json（默认）读取账本页；text/event-stream 订阅实时流。 |
| header: Last-Event-ID | `string` | 可选；SSE 续传游标，读取该事件之后的记录；优先于 cursor，仅用于实时流。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/logs" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Accept: text/event-stream"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
for await (const event of automation.runs.logs({
  "path": {
    "id": env("RUN_ID")
  }
})) {
  console.log(event);
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的日志行（LogLine），按时间顺序排列。 |
| data[].cursor | `string` | 必填 / 必有；该行的游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data[].ts | `string` | 必填 / 必有；日志产生的时间（RFC 3339 UTC）。 |
| data[].level | `"debug"` / `"info"` / `"warn"` / `"error"` | 必填 / 必有；日志级别。debug 调试信息；info 一般信息；warn 警告；error 错误。 |
| data[].message | `string` | 必填 / 必有；日志文本。 |
| next_cursor | `null` / `string` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

`text/event-stream`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 可选；Resume cursor of this entry; send it back as Last-Event-ID, or as cursor on the JSON form, to continue after it. Absent on the end event. |
| event | `"log"` / `"end"` | 必填 / 必有；SSE event name: log carries one log line in data; end is sent once when the run has reached a terminal status and closes the stream. |
| data | `object` / `object` | 必填 / 必有；Decoded JSON of one log line; for the end event, an empty object. |
| data（分支1).cursor | `string` | 必填 / 必有；该行的游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| data（分支1).ts | `string` | 必填 / 必有；日志产生的时间（RFC 3339 UTC）。 |
| data（分支1).level | `"debug"` / `"info"` / `"warn"` / `"error"` | 必填 / 必有；日志级别。debug 调试信息；info 一般信息；warn 警告；error 错误。 |
| data（分支1).message | `string` | 必填 / 必有；日志文本。 |
| （分支1).event | `"log"` | 可选；SSE event name: log, one log line is carried in data. |
| （分支1).data | `object` | 可选；运行产生的一行日志，保留 30 天。 不接受额外字段。 |
| （分支1).data.cursor | `string` | 必填 / 必有；该行的游标；用作 cursor 翻页，或在 SSE 中作为 Last-Event-ID 续传。 |
| （分支1).data.ts | `string` | 必填 / 必有；日志产生的时间（RFC 3339 UTC）。 |
| （分支1).data.level | `"debug"` / `"info"` / `"warn"` / `"error"` | 必填 / 必有；日志级别。debug 调试信息；info 一般信息；warn 警告；error 错误。 |
| （分支1).data.message | `string` | 必填 / 必有；日志文本。 |
| （分支2).event | `"end"` | 可选；SSE event name end: sent once when the run has reached a terminal status, and the stream then closes. |
| （分支2).data | `object` | 可选；Always an empty object for the end event. |

### 实测响应 [#实测响应]

HTTP 200

```text
event: end
data: {}

```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取运行源码

读取运行实际使用的源码及摘要。结果包括语言与 SHA-256 摘要，适用于临时运行及已发布定义的运行。

`GET /automation/v1/runs/{id}/source`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；运行 ID（run_）。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| RUN_ID | [运行 id；暂停和恢复仅工作流；取消需非终态运行](/docs/api/native/automation/createRun) |

```bash
: "${RUN_ID:?Set RUN_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/runs/${RUN_ID}/source" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.runs.retrieveSource({
  "path": {
    "id": env("RUN_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| language | `"ts"` / `"yaml"` | 必填 / 必有；源码语言。ts 表示 TypeScript 脚本；yaml 表示工作流 YAML。 |
| source | `string` | 必填 / 必有；运行时使用的完整源码（ts 或 yaml）。 |
| sha256 | `string` | 必填 / 必有；源码的 SHA-256 摘要，可作为发布时的 expected_source_sha256。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "language": "ts",
  "source": "export default async (input: { n: number }) => ({ answer: input.n + 1 });",
  "sha256": "7ae6678882a4ef2ea96e401c105d5c6ef512917cd72a9235289d2a3bf1f1b49d"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | RUN_NOT_FOUND：运行不存在或当前租户不可见。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出触发器

分页列出租户触发器，可按目标、类型和状态筛选；ns/name 匹配该目标的所有标签或版本，ns/name@spec 精确匹配。

`GET /automation/v1/triggers`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 25。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: target | `string[]` | 可选；ns/name 匹配该目标的所有版本或标签；ns/name@spec 精确匹配已存的引用。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: kind | `"schedule"` / `"webhook"[]` | 可选；schedule 或 webhook；省略返回两者。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: state | `"enabled"` / `"paused"` / `"expired"[]` | 可选；触发器状态：enabled、paused 或 expired；省略不过滤。 多个值以逗号分隔，匹配任一值。 minItems: 1 |
| query: labels | `object` | 可选；按标签过滤，使用 labels[k]=v；同键逗号多值取任一，不同键同时满足。 |
| query: created_at[gte] | `string` | 可选；创建时间下界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |
| query: created_at[lte] | `string` | 可选；创建时间上界，包含边界；使用带时区的 ISO 8601 时间。 format: "date-time" |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TARGET | [已发布的 docs-samples/name@1.0.0](/docs/api/native/automation/publishScriptVersion) |

```bash
: "${TARGET:?Set TARGET}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/triggers" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  --get \
  --data-urlencode "target=${TARGET}"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.list({
  "query": {
    "target": [
      env("TARGET")
    ]
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的触发器，按 created_at 倒序、id 倒序排列。 |
| data[].name | `string` | 必填 / 必有；触发器名称，1–100 字符。 minLength: 1；maxLength: 100 |
| data[].description | `string` | 必填 / 必有；触发器说明，最多 1000 字符。 maxLength: 1000 |
| data[].labels | `object` | 必填 / 必有；触发器标签：字符串键值对，最多 64 个；键不能以保留前缀 praxis. 开头，违反返回 400 INPUT_INVALID。 |
| data[].target | `string` | 必填 / 必有；要运行的脚本或工作流引用，形如 ns/name@标签或版本；默认跟随 latest，写成 @1.2.0 则钉死版本。 |
| data[].input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| data[].input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| data[].kind | `"schedule"` / `"webhook"` | 必填 / 必有；触发器类型。schedule 按计划（cron、every 或 at）触发；webhook 由入站 HTTP 请求触发。 |
| data[].schedule | `object` / `object` / `object` / `null` | 必填 / 必有；定时规则，kind=schedule 时有值（cron、every 或 at 三选一）；webhook 为 null。 |
| data[].schedule（分支1)（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| data[].schedule（分支1)（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| data[].schedule（分支1)（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| data[].schedule（分支1)（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| data[].schedule（分支1)（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| data[].schedule（分支1)（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| data[].schedule（分支1)（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| data[].schedule（分支1)（分支3).at | `string` | 必填 / 必有；一次性触发的时刻（RFC 3339 UTC）；不能早于当前时间，也不能晚于一年后。执行后触发器进入 expired。 format: "date-time" |
| data[].timezone | `string` | 必填 / 必有；IANA 时区名，定时规则按它解释；API 缺省为 UTC。 default: "UTC" |
| data[].start_at | `string` / `null` | 必填 / 必有；定时触发器的开始时间（RFC 3339 UTC）；此前不触发。没有限制为 null。 |
| data[].end_at | `string` / `null` | 必填 / 必有；定时触发器的结束时间（RFC 3339 UTC）；超过后进入 expired。没有期限为 null。 |
| data[].overlap | `"skip"` / `"allow"` | 必填 / 必有；重叠策略：上一次运行未结束时又到点，skip（默认）跳过，allow 照常启动。 default: "skip" |
| data[].catchup_window_seconds | `integer` | 必填 / 必有；补跑窗口（秒），默认 300，仅定时触发器适用：到点时若已延迟超过该值（宕机、暂停期间），记为 missed 且不补跑。 default: 300；minimum: 0 |
| data[].webhook | `object` / `null` | 必填 / 必有；webhook 设置，kind=webhook 时有值；schedule 触发器为 null。 |
| data[].webhook（分支1).input_mode | `"body"` / `"envelope"` | 必填 / 必有；webhook 触发时传给目标的输入形态。body（默认）只传请求体；envelope 传含 body、raw_body、raw_body_encoding、headers、webhook_id、received_at 的信封对象。 |
| data[].webhook（分支1).url_hint | `string` | 必填 / 必有；webhook 地址的掩码提示，省略号代替私密 token，不能用于调用。新建触发器为公开完整 URL；历史记录可能为 /automation/v1/hooks/&#123;id&#125;/… 相对路径。 |
| data[].id | `string` | 必填 / 必有；触发器 ID，前缀 trg_；用于 webhook 地址以及触发器的所有接口。 |
| data[].owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| data[].state | `"enabled"` / `"paused"` / `"expired"` | 必填 / 必有；触发器状态。enabled 启用，会按计划或请求触发；paused 已暂停，不触发；expired 已到期，一次性触发器执行完或超过 end_at 后进入，不再触发。 |
| data[].source | `"api"` / `"definition"` | 必填 / 必有；触发器来源。api 为通过 API 创建，可修改和删除；definition 为由工作流 YAML 的 schedule 生成，只能暂停或恢复，修改返回 409 TRIGGER_MANAGED。 |
| data[].created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| data[].created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| data[].created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| data[].created_by_user_id | `string` | 必填 / 必有；创建者的真实用户 ID，由网关转发；触发器启动的运行以该用户身份取令牌，用于审计与用量归属。 |
| data[].next_fire_times | `string[]` | 必填 / 必有；接下来最多 5 次的触发时间（RFC 3339 UTC）；webhook、已暂停或已到期的触发器为空数组。 maxItems: 5 |
| data[].last_firing | `object` / `null` | 必填 / 必有；最近一次触发记录；从未触发为 null。 |
| data[].last_firing（分支1).id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| data[].last_firing（分支1).trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| data[].last_firing（分支1).scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| data[].last_firing（分支1).fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| data[].last_firing（分支1).outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| data[].last_firing（分支1).run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| data[].last_firing（分支1).resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| data[].last_firing（分支1).error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| data[].last_firing（分支1).error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| data[].last_firing（分支1).error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |
| data[].counts | `object` | 必填 / 必有；触发结果累计次数 &#123;started, skipped, missed, failed&#125;。 不接受额外字段。 |
| data[].counts.started | `integer` | 必填 / 必有；成功启动运行的次数。 minimum: 0 |
| data[].counts.skipped | `integer` | 必填 / 必有；因重叠策略为 skip 且上一次运行未结束而跳过的次数。 minimum: 0 |
| data[].counts.missed | `integer` | 必填 / 必有；因延迟超过补跑窗口而错过的次数。 minimum: 0 |
| data[].counts.failed | `integer` | 必填 / 必有；创建运行失败的次数。 minimum: 0 |
| data[].created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 format: "date-time" |
| data[].updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 format: "date-time" |
| data[].etag | `string` | 必填 / 必有；触发器当前修订标识，更新时作为 If-Match；不匹配返回 412。 |
| data[].usage_30d | `object` / `null` | 可选；仅 GET /triggers/&#123;id&#125; 返回，列表省略。最近 30 天由此触发器启动的运行及子运行的归因实扣。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| data[].usage_30d（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| data[].usage_30d（分支1).cost | `string` | 必填 / 必有；已评级实扣的美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| data[].usage_30d（分支1).pending_events | `integer` | 必填 / 必有；尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| next_cursor | `string` / `null` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
      "owner": "tnt_3a9759864ccb4e00",
      "name": "sample-webhook-1791867412840-b05e8a",
      "description": "",
      "labels": {
        "namespace": "docs-samples"
      },
      "target": "docs-samples/sample-scripts-1791867412840-b05e8a@1.0.0",
      "input": {},
      "kind": "webhook",
      "schedule": null,
      "timezone": "UTC",
      "start_at": null,
      "end_at": null,
      "overlap": "skip",
      "catchup_window_seconds": 300,
      "webhook": {
        "input_mode": "body",
        "url_hint": "https://api-develop.deepraxis.ai/automation/v1/hooks/trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e/…"
      },
      "state": "paused",
      "source": "api",
      "created_by": {
        "type": "api_key",
        "id": "key_3e00b8984967"
      },
      "created_by_user_id": "usr_49d4fcb99517",
      "next_fire_times": [],
      "last_firing": null,
      "counts": {
        "started": 0,
        "skipped": 0,
        "missed": 0,
        "failed": 0
      },
      "created_at": "2026-10-13T04:58:09.974Z",
      "updated_at": "2026-10-13T04:58:12.519Z",
      "etag": "etag_00mv67n1yf40e7b8d39ce5459d9ce835bfb1083701"
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 创建触发器

为已发布脚本或工作流创建定时或 webhook 触发器，每租户最多 100 个启用中的触发器。目标只接受精确版本或标签，webhook_url 仅在创建 webhook 或轮换时返回，须妥善保存。

`POST /automation/v1/triggers`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | `string` | 必填 / 必有；触发器显示名，1–100 字符且不能全为空白；不要求唯一。 minLength: 1；maxLength: 100 |
| description | `string` | 可选；说明，最多 1000 个字符。 maxLength: 1000 |
| labels | `object` | 可选；最多 64 个用户标签，禁止 praxis. 前缀；内部标签不占用名额。键 1–40 字符、值最多 500 字符。 |
| target | `string` | 必填 / 必有；ns/name@tag 或 ns/name@version，省略 @ 时用 latest；触发器不接受版本范围。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `null` / `string` / `number` / `boolean` / `object` / `JSON[][]` | 可选；定时触发的静态 JSON 输入，默认 &#123;&#125;；创建与修改时校验目标契约。webhook 未显式提供时不在创建阶段校验回调输入。 |
| input（分支5).*（分支5) | `object` | 递归 JSON 值。 |
| input（分支5).*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[]（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[]（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| kind | `"schedule"` / `"webhook"` | 必填 / 必有；schedule 按计划触发，webhook 由 HTTP 回调触发；创建后不可更改。 |
| schedule | `object` / `object` / `object` | 可选；三选一：cron 为五段表达式（支持 L/W/#）；every 为 ISO 8601 时长或时长对象，须为正整数毫秒且在 1 分钟至 366 天之间；at 为未来一年内的一次性 RFC 3339 时间。 |
| schedule（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| schedule（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| schedule（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| schedule（分支3).at | `string` | 必填 / 必有；一次性触发时刻，需带 Z 或 ±HH:MM 时区；必须在请求时刻至一年后之间。调用时将示例替换为该范围内的未来时间。 pattern: "(Z\|[+-]\\d\\d:\\d\\d)$"；format: "date-time" |
| timezone | `string` | 可选；IANA 时区，默认 UTC；夏令时跳过不存在的时刻，重复时刻只触发一次。 default: "UTC" |
| start_at | `string` / `null` | 可选；可选开始时间，RFC 3339 且带时区；null 表示不设下界。 |
| end_at | `string` / `null` | 可选；可选结束时间，RFC 3339 且带时区；不能早于 start_at，null 表示不设上界。 |
| overlap | `"skip"` / `"allow"` | 可选；skip（默认）在前次运行未结束时跳过，allow 允许并行触发。 default: "skip" |
| catchup_window_seconds | `integer` | 可选；非负整数秒，默认 300；仅对定时触发器生效；延迟超过窗口时记为 missed，不补跑，webhook 不受此窗口影响。 default: 300；minimum: 0 |
| webhook | `object` | 可选；input_mode 为 body（默认）或 envelope；后者包含 body、raw_body、raw_body_encoding、白名单 headers、webhook_id、received_at，完整 URL 仅创建或轮换时返回。 不接受额外字段。 |
| webhook.input_mode | `"body"` / `"envelope"` | 必填 / 必有；webhook 触发时传给目标的输入形态。body（默认）只传请求体；envelope 传含 body、raw_body、raw_body_encoding、headers、webhook_id、received_at 的信封对象。 default: "body" |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TARGET | [已发布的 docs-samples/name@1.0.0](/docs/api/native/automation/publishScriptVersion) |

```bash
: "${TARGET:?Set TARGET}"
BODY=$(jq -n --arg TARGET "$TARGET" '{
  "name": "sample-webhook",
  "target": $TARGET,
  "kind": "webhook",
  "labels": {
    "namespace": "docs-samples"
  },
  "webhook": {
    "input_mode": "body"
  }
}')
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/triggers" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data "$BODY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.create({
  "body": {
    "name": "sample-webhook",
    "target": env("TARGET"),
    "kind": "webhook",
    "labels": {
      "namespace": "docs-samples"
    },
    "webhook": {
      "input_mode": "body"
    }
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| ETag | `string` | Current resource revision for conditional updates. |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | `string` | 必填 / 必有；触发器名称，1–100 字符。 minLength: 1；maxLength: 100 |
| description | `string` | 必填 / 必有；触发器说明，最多 1000 字符。 maxLength: 1000 |
| labels | `object` | 必填 / 必有；触发器标签：字符串键值对，最多 64 个；键不能以保留前缀 praxis. 开头，违反返回 400 INPUT_INVALID。 |
| target | `string` | 必填 / 必有；要运行的脚本或工作流引用，形如 ns/name@标签或版本；默认跟随 latest，写成 @1.2.0 则钉死版本。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| kind | `"schedule"` / `"webhook"` | 必填 / 必有；触发器类型。schedule 按计划（cron、every 或 at）触发；webhook 由入站 HTTP 请求触发。 |
| schedule | `object` / `object` / `object` / `null` | 必填 / 必有；定时规则，kind=schedule 时有值（cron、every 或 at 三选一）；webhook 为 null。 |
| schedule（分支1)（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| schedule（分支1)（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| schedule（分支1)（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支3).at | `string` | 必填 / 必有；一次性触发的时刻（RFC 3339 UTC）；不能早于当前时间，也不能晚于一年后。执行后触发器进入 expired。 format: "date-time" |
| timezone | `string` | 必填 / 必有；IANA 时区名，定时规则按它解释；API 缺省为 UTC。 default: "UTC" |
| start_at | `string` / `null` | 必填 / 必有；定时触发器的开始时间（RFC 3339 UTC）；此前不触发。没有限制为 null。 |
| end_at | `string` / `null` | 必填 / 必有；定时触发器的结束时间（RFC 3339 UTC）；超过后进入 expired。没有期限为 null。 |
| overlap | `"skip"` / `"allow"` | 必填 / 必有；重叠策略：上一次运行未结束时又到点，skip（默认）跳过，allow 照常启动。 default: "skip" |
| catchup_window_seconds | `integer` | 必填 / 必有；补跑窗口（秒），默认 300，仅定时触发器适用：到点时若已延迟超过该值（宕机、暂停期间），记为 missed 且不补跑。 default: 300；minimum: 0 |
| webhook | `object` / `null` | 必填 / 必有；webhook 设置，kind=webhook 时有值；schedule 触发器为 null。 |
| webhook（分支1).input_mode | `"body"` / `"envelope"` | 必填 / 必有；webhook 触发时传给目标的输入形态。body（默认）只传请求体；envelope 传含 body、raw_body、raw_body_encoding、headers、webhook_id、received_at 的信封对象。 |
| webhook（分支1).url_hint | `string` | 必填 / 必有；webhook 地址的掩码提示，省略号代替私密 token，不能用于调用。新建触发器为公开完整 URL；历史记录可能为 /automation/v1/hooks/&#123;id&#125;/… 相对路径。 |
| id | `string` | 必填 / 必有；触发器 ID，前缀 trg_；用于 webhook 地址以及触发器的所有接口。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| state | `"enabled"` / `"paused"` / `"expired"` | 必填 / 必有；触发器状态。enabled 启用，会按计划或请求触发；paused 已暂停，不触发；expired 已到期，一次性触发器执行完或超过 end_at 后进入，不再触发。 |
| source | `"api"` / `"definition"` | 必填 / 必有；触发器来源。api 为通过 API 创建，可修改和删除；definition 为由工作流 YAML 的 schedule 生成，只能暂停或恢复，修改返回 409 TRIGGER_MANAGED。 |
| created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| created_by_user_id | `string` | 必填 / 必有；创建者的真实用户 ID，由网关转发；触发器启动的运行以该用户身份取令牌，用于审计与用量归属。 |
| next_fire_times | `string[]` | 必填 / 必有；接下来最多 5 次的触发时间（RFC 3339 UTC）；webhook、已暂停或已到期的触发器为空数组。 maxItems: 5 |
| last_firing | `object` / `null` | 必填 / 必有；最近一次触发记录；从未触发为 null。 |
| last_firing（分支1).id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| last_firing（分支1).trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| last_firing（分支1).scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| last_firing（分支1).fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| last_firing（分支1).outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| last_firing（分支1).run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| last_firing（分支1).resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| last_firing（分支1).error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| last_firing（分支1).error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| last_firing（分支1).error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |
| counts | `object` | 必填 / 必有；触发结果累计次数 &#123;started, skipped, missed, failed&#125;。 不接受额外字段。 |
| counts.started | `integer` | 必填 / 必有；成功启动运行的次数。 minimum: 0 |
| counts.skipped | `integer` | 必填 / 必有；因重叠策略为 skip 且上一次运行未结束而跳过的次数。 minimum: 0 |
| counts.missed | `integer` | 必填 / 必有；因延迟超过补跑窗口而错过的次数。 minimum: 0 |
| counts.failed | `integer` | 必填 / 必有；创建运行失败的次数。 minimum: 0 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 format: "date-time" |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 format: "date-time" |
| etag | `string` | 必填 / 必有；触发器当前修订标识，更新时作为 If-Match；不匹配返回 412。 |
| usage_30d | `object` / `null` | 可选；创建响应中恒为 null；近 30 天用量只在 GET /triggers/&#123;id&#125; 返回。 |
| usage_30d（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage_30d（分支1).cost | `string` | 必填 / 必有；已评级实扣的美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage_30d（分支1).pending_events | `integer` | 必填 / 必有；尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |
| webhook_url | `string` | 可选；Returned only on webhook creation or rotation. format: "uri" |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
  "owner": "tnt_3a9759864ccb4e00",
  "name": "sample-webhook-1791867412840-b05e8a",
  "description": "",
  "labels": {
    "namespace": "docs-samples"
  },
  "target": "docs-samples/sample-scripts-1791867412840-b05e8a@1.0.0",
  "input": {},
  "kind": "webhook",
  "schedule": null,
  "timezone": "UTC",
  "start_at": null,
  "end_at": null,
  "overlap": "skip",
  "catchup_window_seconds": 300,
  "webhook": {
    "input_mode": "body",
    "url_hint": "https://api-develop.deepraxis.ai/automation/v1/hooks/trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e/…"
  },
  "state": "enabled",
  "source": "api",
  "created_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "created_by_user_id": "usr_49d4fcb99517",
  "next_fire_times": [],
  "last_firing": null,
  "counts": {
    "started": 0,
    "skipped": 0,
    "missed": 0,
    "failed": 0
  },
  "created_at": "2026-10-13T04:58:09.974Z",
  "updated_at": "2026-10-13T04:58:09.974Z",
  "etag": "etag_00mv67mzzqc6ef5487c69f4857b65b91dab497104c",
  "webhook_url": "https://api-develop.deepraxis.ai/automation/v1/hooks/trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e/${WEBHOOK_TOKEN}"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 SCHEDULE_INVALID：定时规则或时间边界无效。 TIMEZONE_INVALID：时区不是有效的 IANA 时区。 INTERVAL_TOO_SHORT：定时间隔短于一分钟。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| 404 | TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 NO_MATCHING_VERSION：没有满足标签、版本或范围的已发布版本。 |
| 429 | TRIGGER_LIMIT：租户已达到 100 个启用触发器的上限。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 读取触发器

读取规则、状态、未来触发时间与最近触发结果；ETag 可用于修改，完整 webhook URL 不会再次返回。

`GET /automation/v1/triggers/{id}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；触发器 ID（trg_）。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/triggers/${TRIGGER_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.retrieve({
  "path": {
    "id": env("TRIGGER_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| ETag | `string` | Current resource revision for conditional updates. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | `string` | 必填 / 必有；触发器名称，1–100 字符。 minLength: 1；maxLength: 100 |
| description | `string` | 必填 / 必有；触发器说明，最多 1000 字符。 maxLength: 1000 |
| labels | `object` | 必填 / 必有；触发器标签：字符串键值对，最多 64 个；键不能以保留前缀 praxis. 开头，违反返回 400 INPUT_INVALID。 |
| target | `string` | 必填 / 必有；要运行的脚本或工作流引用，形如 ns/name@标签或版本；默认跟随 latest，写成 @1.2.0 则钉死版本。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| kind | `"schedule"` / `"webhook"` | 必填 / 必有；触发器类型。schedule 按计划（cron、every 或 at）触发；webhook 由入站 HTTP 请求触发。 |
| schedule | `object` / `object` / `object` / `null` | 必填 / 必有；定时规则，kind=schedule 时有值（cron、every 或 at 三选一）；webhook 为 null。 |
| schedule（分支1)（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| schedule（分支1)（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| schedule（分支1)（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支3).at | `string` | 必填 / 必有；一次性触发的时刻（RFC 3339 UTC）；不能早于当前时间，也不能晚于一年后。执行后触发器进入 expired。 format: "date-time" |
| timezone | `string` | 必填 / 必有；IANA 时区名，定时规则按它解释；API 缺省为 UTC。 default: "UTC" |
| start_at | `string` / `null` | 必填 / 必有；定时触发器的开始时间（RFC 3339 UTC）；此前不触发。没有限制为 null。 |
| end_at | `string` / `null` | 必填 / 必有；定时触发器的结束时间（RFC 3339 UTC）；超过后进入 expired。没有期限为 null。 |
| overlap | `"skip"` / `"allow"` | 必填 / 必有；重叠策略：上一次运行未结束时又到点，skip（默认）跳过，allow 照常启动。 default: "skip" |
| catchup_window_seconds | `integer` | 必填 / 必有；补跑窗口（秒），默认 300，仅定时触发器适用：到点时若已延迟超过该值（宕机、暂停期间），记为 missed 且不补跑。 default: 300；minimum: 0 |
| webhook | `object` / `null` | 必填 / 必有；webhook 设置，kind=webhook 时有值；schedule 触发器为 null。 |
| webhook（分支1).input_mode | `"body"` / `"envelope"` | 必填 / 必有；webhook 触发时传给目标的输入形态。body（默认）只传请求体；envelope 传含 body、raw_body、raw_body_encoding、headers、webhook_id、received_at 的信封对象。 |
| webhook（分支1).url_hint | `string` | 必填 / 必有；webhook 地址的掩码提示，省略号代替私密 token，不能用于调用。新建触发器为公开完整 URL；历史记录可能为 /automation/v1/hooks/&#123;id&#125;/… 相对路径。 |
| id | `string` | 必填 / 必有；触发器 ID，前缀 trg_；用于 webhook 地址以及触发器的所有接口。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| state | `"enabled"` / `"paused"` / `"expired"` | 必填 / 必有；触发器状态。enabled 启用，会按计划或请求触发；paused 已暂停，不触发；expired 已到期，一次性触发器执行完或超过 end_at 后进入，不再触发。 |
| source | `"api"` / `"definition"` | 必填 / 必有；触发器来源。api 为通过 API 创建，可修改和删除；definition 为由工作流 YAML 的 schedule 生成，只能暂停或恢复，修改返回 409 TRIGGER_MANAGED。 |
| created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| created_by_user_id | `string` | 必填 / 必有；创建者的真实用户 ID，由网关转发；触发器启动的运行以该用户身份取令牌，用于审计与用量归属。 |
| next_fire_times | `string[]` | 必填 / 必有；接下来最多 5 次的触发时间（RFC 3339 UTC）；webhook、已暂停或已到期的触发器为空数组。 maxItems: 5 |
| last_firing | `object` / `null` | 必填 / 必有；最近一次触发记录；从未触发为 null。 |
| last_firing（分支1).id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| last_firing（分支1).trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| last_firing（分支1).scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| last_firing（分支1).fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| last_firing（分支1).outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| last_firing（分支1).run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| last_firing（分支1).resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| last_firing（分支1).error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| last_firing（分支1).error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| last_firing（分支1).error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |
| counts | `object` | 必填 / 必有；触发结果累计次数 &#123;started, skipped, missed, failed&#125;。 不接受额外字段。 |
| counts.started | `integer` | 必填 / 必有；成功启动运行的次数。 minimum: 0 |
| counts.skipped | `integer` | 必填 / 必有；因重叠策略为 skip 且上一次运行未结束而跳过的次数。 minimum: 0 |
| counts.missed | `integer` | 必填 / 必有；因延迟超过补跑窗口而错过的次数。 minimum: 0 |
| counts.failed | `integer` | 必填 / 必有；创建运行失败的次数。 minimum: 0 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 format: "date-time" |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 format: "date-time" |
| etag | `string` | 必填 / 必有；触发器当前修订标识，更新时作为 If-Match；不匹配返回 412。 |
| usage_30d | `object` / `null` | 可选；仅 GET /triggers/&#123;id&#125; 返回，列表省略。最近 30 天由此触发器启动的运行及子运行的归因实扣。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage_30d（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage_30d（分支1).cost | `string` | 必填 / 必有；已评级实扣的美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage_30d（分支1).pending_events | `integer` | 必填 / 必有；尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
  "owner": "tnt_3a9759864ccb4e00",
  "name": "sample-webhook-1791867412840-b05e8a",
  "description": "",
  "labels": {
    "namespace": "docs-samples"
  },
  "target": "docs-samples/sample-scripts-1791867412840-b05e8a@1.0.0",
  "input": {},
  "kind": "webhook",
  "schedule": null,
  "timezone": "UTC",
  "start_at": null,
  "end_at": null,
  "overlap": "skip",
  "catchup_window_seconds": 300,
  "webhook": {
    "input_mode": "body",
    "url_hint": "https://api-develop.deepraxis.ai/automation/v1/hooks/trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e/…"
  },
  "state": "paused",
  "source": "api",
  "created_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "created_by_user_id": "usr_49d4fcb99517",
  "next_fire_times": [],
  "last_firing": null,
  "counts": {
    "started": 0,
    "skipped": 0,
    "missed": 0,
    "failed": 0
  },
  "created_at": "2026-10-13T04:58:09.974Z",
  "updated_at": "2026-10-13T04:58:12.519Z",
  "etag": "etag_00mv67n1yf40e7b8d39ce5459d9ce835bfb1083701",
  "usage_30d": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 更新触发器

使用匹配当前 ETag 的 If-Match 修改配置，并重新校验目标输入与规则；kind 不可更改，由定义管理的触发器拒绝修改并返回 TRIGGER_MANAGED。

`PATCH /automation/v1/triggers/{id}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；触发器 ID（trg_）。 |
| header: If-Match | `string` | 必填；当前资源的 ETag，可直接使用对象里的 draft.revision 或 etag 字段值：裸值、带双引号或弱校验写法 W/"…" 均接受（RFC 7232 弱比较）；缺失返回 400，修订不匹配返回 412。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | `string` | 可选；触发器显示名，1–100 字符且不能全为空白；不要求唯一。 minLength: 1；maxLength: 100 |
| description | `string` | 可选；说明，最多 1000 个字符。 maxLength: 1000 |
| labels | `object` | 可选；最多 64 个用户标签，禁止 praxis. 前缀；内部标签不占用名额。键 1–40 字符、值最多 500 字符。 |
| target | `string` | 可选；ns/name@tag 或 ns/name@version，省略 @ 时用 latest；触发器不接受版本范围。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `null` / `string` / `number` / `boolean` / `object` / `JSON[][]` | 可选；定时触发的静态 JSON 输入，默认 &#123;&#125;；创建与修改时校验目标契约。webhook 未显式提供时不在创建阶段校验回调输入。 |
| input（分支5).*（分支5) | `object` | 递归 JSON 值。 |
| input（分支5).*（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[]（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[]（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| kind | `"schedule"` / `"webhook"` | 可选；schedule 按计划触发，webhook 由 HTTP 回调触发；创建后不可更改。 |
| schedule | `object` / `object` / `object` | 可选；三选一：cron 为五段表达式（支持 L/W/#）；every 为 ISO 8601 时长或时长对象，须为正整数毫秒且在 1 分钟至 366 天之间；at 为未来一年内的一次性 RFC 3339 时间。 |
| schedule（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| schedule（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| schedule（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| schedule（分支3).at | `string` | 必填 / 必有；一次性触发时刻，需带 Z 或 ±HH:MM 时区；必须在请求时刻至一年后之间。调用时将示例替换为该范围内的未来时间。 pattern: "(Z\|[+-]\\d\\d:\\d\\d)$"；format: "date-time" |
| timezone | `string` | 可选；IANA 时区，默认 UTC；夏令时跳过不存在的时刻，重复时刻只触发一次。 default: "UTC" |
| start_at | `string` / `null` | 可选；可选开始时间，RFC 3339 且带时区；null 表示不设下界。 |
| end_at | `string` / `null` | 可选；可选结束时间，RFC 3339 且带时区；不能早于 start_at，null 表示不设上界。 |
| overlap | `"skip"` / `"allow"` | 可选；skip（默认）在前次运行未结束时跳过，allow 允许并行触发。 default: "skip" |
| catchup_window_seconds | `integer` | 可选；非负整数秒，默认 300；仅对定时触发器生效；延迟超过窗口时记为 missed，不补跑，webhook 不受此窗口影响。 default: 300；minimum: 0 |
| webhook | `object` | 可选；input_mode 为 body（默认）或 envelope；后者包含 body、raw_body、raw_body_encoding、白名单 headers、webhook_id、received_at，完整 URL 仅创建或轮换时返回。 不接受额外字段。 |
| webhook.input_mode | `"body"` / `"envelope"` | 必填 / 必有；webhook 触发时传给目标的输入形态。body（默认）只传请求体；envelope 传含 body、raw_body、raw_body_encoding、headers、webhook_id、received_at 的信封对象。 default: "body" |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |
| ETAG | [最新 GET 响应头 ETag（保留引号）](/docs/api/native/automation/getTrigger) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
: "${ETAG:?Set ETAG}"
curl --fail-with-body -X PATCH "https://api.deepraxis.ai/automation/v1/triggers/${TRIGGER_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "If-Match: ${ETAG}" \
  -H "Content-Type: application/json" \
  --data '{
  "description": "Sample webhook",
  "input": {
    "n": 41
  }
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.update({
  "path": {
    "id": env("TRIGGER_ID")
  },
  "headers": {
    "If-Match": env("ETAG")
  },
  "body": {
    "description": "Sample webhook",
    "input": {
      "n": 41
    }
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| ETag | `string` | Current resource revision for conditional updates. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | `string` | 必填 / 必有；触发器名称，1–100 字符。 minLength: 1；maxLength: 100 |
| description | `string` | 必填 / 必有；触发器说明，最多 1000 字符。 maxLength: 1000 |
| labels | `object` | 必填 / 必有；触发器标签：字符串键值对，最多 64 个；键不能以保留前缀 praxis. 开头，违反返回 400 INPUT_INVALID。 |
| target | `string` | 必填 / 必有；要运行的脚本或工作流引用，形如 ns/name@标签或版本；默认跟随 latest，写成 @1.2.0 则钉死版本。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| kind | `"schedule"` / `"webhook"` | 必填 / 必有；触发器类型。schedule 按计划（cron、every 或 at）触发；webhook 由入站 HTTP 请求触发。 |
| schedule | `object` / `object` / `object` / `null` | 必填 / 必有；定时规则，kind=schedule 时有值（cron、every 或 at 三选一）；webhook 为 null。 |
| schedule（分支1)（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| schedule（分支1)（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| schedule（分支1)（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支3).at | `string` | 必填 / 必有；一次性触发的时刻（RFC 3339 UTC）；不能早于当前时间，也不能晚于一年后。执行后触发器进入 expired。 format: "date-time" |
| timezone | `string` | 必填 / 必有；IANA 时区名，定时规则按它解释；API 缺省为 UTC。 default: "UTC" |
| start_at | `string` / `null` | 必填 / 必有；定时触发器的开始时间（RFC 3339 UTC）；此前不触发。没有限制为 null。 |
| end_at | `string` / `null` | 必填 / 必有；定时触发器的结束时间（RFC 3339 UTC）；超过后进入 expired。没有期限为 null。 |
| overlap | `"skip"` / `"allow"` | 必填 / 必有；重叠策略：上一次运行未结束时又到点，skip（默认）跳过，allow 照常启动。 default: "skip" |
| catchup_window_seconds | `integer` | 必填 / 必有；补跑窗口（秒），默认 300，仅定时触发器适用：到点时若已延迟超过该值（宕机、暂停期间），记为 missed 且不补跑。 default: 300；minimum: 0 |
| webhook | `object` / `null` | 必填 / 必有；webhook 设置，kind=webhook 时有值；schedule 触发器为 null。 |
| webhook（分支1).input_mode | `"body"` / `"envelope"` | 必填 / 必有；webhook 触发时传给目标的输入形态。body（默认）只传请求体；envelope 传含 body、raw_body、raw_body_encoding、headers、webhook_id、received_at 的信封对象。 |
| webhook（分支1).url_hint | `string` | 必填 / 必有；webhook 地址的掩码提示，省略号代替私密 token，不能用于调用。新建触发器为公开完整 URL；历史记录可能为 /automation/v1/hooks/&#123;id&#125;/… 相对路径。 |
| id | `string` | 必填 / 必有；触发器 ID，前缀 trg_；用于 webhook 地址以及触发器的所有接口。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| state | `"enabled"` / `"paused"` / `"expired"` | 必填 / 必有；触发器状态。enabled 启用，会按计划或请求触发；paused 已暂停，不触发；expired 已到期，一次性触发器执行完或超过 end_at 后进入，不再触发。 |
| source | `"api"` / `"definition"` | 必填 / 必有；触发器来源。api 为通过 API 创建，可修改和删除；definition 为由工作流 YAML 的 schedule 生成，只能暂停或恢复，修改返回 409 TRIGGER_MANAGED。 |
| created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| created_by_user_id | `string` | 必填 / 必有；创建者的真实用户 ID，由网关转发；触发器启动的运行以该用户身份取令牌，用于审计与用量归属。 |
| next_fire_times | `string[]` | 必填 / 必有；接下来最多 5 次的触发时间（RFC 3339 UTC）；webhook、已暂停或已到期的触发器为空数组。 maxItems: 5 |
| last_firing | `object` / `null` | 必填 / 必有；最近一次触发记录；从未触发为 null。 |
| last_firing（分支1).id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| last_firing（分支1).trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| last_firing（分支1).scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| last_firing（分支1).fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| last_firing（分支1).outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| last_firing（分支1).run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| last_firing（分支1).resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| last_firing（分支1).error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| last_firing（分支1).error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| last_firing（分支1).error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |
| counts | `object` | 必填 / 必有；触发结果累计次数 &#123;started, skipped, missed, failed&#125;。 不接受额外字段。 |
| counts.started | `integer` | 必填 / 必有；成功启动运行的次数。 minimum: 0 |
| counts.skipped | `integer` | 必填 / 必有；因重叠策略为 skip 且上一次运行未结束而跳过的次数。 minimum: 0 |
| counts.missed | `integer` | 必填 / 必有；因延迟超过补跑窗口而错过的次数。 minimum: 0 |
| counts.failed | `integer` | 必填 / 必有；创建运行失败的次数。 minimum: 0 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 format: "date-time" |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 format: "date-time" |
| etag | `string` | 必填 / 必有；触发器当前修订标识，更新时作为 If-Match；不匹配返回 412。 |
| usage_30d | `object` / `null` | 可选；仅 GET /triggers/&#123;id&#125; 返回，列表省略。最近 30 天由此触发器启动的运行及子运行的归因实扣。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage_30d（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage_30d（分支1).cost | `string` | 必填 / 必有；已评级实扣的美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage_30d（分支1).pending_events | `integer` | 必填 / 必有；尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
  "owner": "tnt_3a9759864ccb4e00",
  "name": "sample-webhook-1791867412840-b05e8a",
  "description": "Sample webhook",
  "labels": {
    "namespace": "docs-samples"
  },
  "target": "docs-samples/sample-scripts-1791867412840-b05e8a@1.0.0",
  "input": {
    "n": 41
  },
  "kind": "webhook",
  "schedule": null,
  "timezone": "UTC",
  "start_at": null,
  "end_at": null,
  "overlap": "skip",
  "catchup_window_seconds": 300,
  "webhook": {
    "input_mode": "body",
    "url_hint": "https://api-develop.deepraxis.ai/automation/v1/hooks/trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e/…"
  },
  "state": "paused",
  "source": "api",
  "created_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "created_by_user_id": "usr_49d4fcb99517",
  "next_fire_times": [],
  "last_firing": null,
  "counts": {
    "started": 0,
    "skipped": 0,
    "missed": 0,
    "failed": 0
  },
  "created_at": "2026-10-13T04:58:09.974Z",
  "updated_at": "2026-10-13T04:58:14.661Z",
  "etag": "etag_00mv67n3ib18c0371214b84064b86e9375320685fa"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 SCHEDULE_INVALID：定时规则或时间边界无效。 TIMEZONE_INVALID：时区不是有效的 IANA 时区。 INTERVAL_TOO_SHORT：定时间隔短于一分钟。 INPUT_INVALID：输入不满足目标契约或业务校验。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 TARGET_NOT_FOUND：编排目标不存在或类型不匹配。 VERSION_NOT_FOUND：指定版本或修订不存在。 |
| 409 | TRIGGER_MANAGED：触发器由定义管理，不能直接修改。 TARGET_ARCHIVED：目标已归档，不能用于本操作；动作执行错误的 detail 包含 ns/name。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 422 | NO_MATCHING_VERSION：没有满足标签、版本或范围的已发布版本。 |
| 429 | TRIGGER_LIMIT：租户已达到 100 个启用触发器的上限。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 删除触发器

删除触发器及其触发历史，返回 204；已经启动的运行不受影响。由定义管理的触发器返回 409 TRIGGER_MANAGED，需在工作流定义里删除 schedule 后重新发布。

`DELETE /automation/v1/triggers/{id}`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；触发器 ID（trg_）。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
curl --fail-with-body -X DELETE "https://api.deepraxis.ai/automation/v1/triggers/${TRIGGER_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.delete({
  "path": {
    "id": env("TRIGGER_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 204 [#http-204]

Deleted

### 实测响应 [#实测响应]

HTTP 204

```text

```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 |
| 409 | TRIGGER_MANAGED：触发器由定义管理，不能直接修改。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 暂停触发器

暂停后停止新触发，不终止已经启动的运行；由定义管理的触发器也可以暂停。

`POST /automation/v1/triggers/{id}/pause`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；触发器 ID（trg_）。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/triggers/${TRIGGER_ID}/pause" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.pause({
  "path": {
    "id": env("TRIGGER_ID")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | `string` | 必填 / 必有；触发器名称，1–100 字符。 minLength: 1；maxLength: 100 |
| description | `string` | 必填 / 必有；触发器说明，最多 1000 字符。 maxLength: 1000 |
| labels | `object` | 必填 / 必有；触发器标签：字符串键值对，最多 64 个；键不能以保留前缀 praxis. 开头，违反返回 400 INPUT_INVALID。 |
| target | `string` | 必填 / 必有；要运行的脚本或工作流引用，形如 ns/name@标签或版本；默认跟随 latest，写成 @1.2.0 则钉死版本。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| kind | `"schedule"` / `"webhook"` | 必填 / 必有；触发器类型。schedule 按计划（cron、every 或 at）触发；webhook 由入站 HTTP 请求触发。 |
| schedule | `object` / `object` / `object` / `null` | 必填 / 必有；定时规则，kind=schedule 时有值（cron、every 或 at 三选一）；webhook 为 null。 |
| schedule（分支1)（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| schedule（分支1)（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| schedule（分支1)（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支3).at | `string` | 必填 / 必有；一次性触发的时刻（RFC 3339 UTC）；不能早于当前时间，也不能晚于一年后。执行后触发器进入 expired。 format: "date-time" |
| timezone | `string` | 必填 / 必有；IANA 时区名，定时规则按它解释；API 缺省为 UTC。 default: "UTC" |
| start_at | `string` / `null` | 必填 / 必有；定时触发器的开始时间（RFC 3339 UTC）；此前不触发。没有限制为 null。 |
| end_at | `string` / `null` | 必填 / 必有；定时触发器的结束时间（RFC 3339 UTC）；超过后进入 expired。没有期限为 null。 |
| overlap | `"skip"` / `"allow"` | 必填 / 必有；重叠策略：上一次运行未结束时又到点，skip（默认）跳过，allow 照常启动。 default: "skip" |
| catchup_window_seconds | `integer` | 必填 / 必有；补跑窗口（秒），默认 300，仅定时触发器适用：到点时若已延迟超过该值（宕机、暂停期间），记为 missed 且不补跑。 default: 300；minimum: 0 |
| webhook | `object` / `null` | 必填 / 必有；webhook 设置，kind=webhook 时有值；schedule 触发器为 null。 |
| webhook（分支1).input_mode | `"body"` / `"envelope"` | 必填 / 必有；webhook 触发时传给目标的输入形态。body（默认）只传请求体；envelope 传含 body、raw_body、raw_body_encoding、headers、webhook_id、received_at 的信封对象。 |
| webhook（分支1).url_hint | `string` | 必填 / 必有；webhook 地址的掩码提示，省略号代替私密 token，不能用于调用。新建触发器为公开完整 URL；历史记录可能为 /automation/v1/hooks/&#123;id&#125;/… 相对路径。 |
| id | `string` | 必填 / 必有；触发器 ID，前缀 trg_；用于 webhook 地址以及触发器的所有接口。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| state | `"enabled"` / `"paused"` / `"expired"` | 必填 / 必有；触发器状态。enabled 启用，会按计划或请求触发；paused 已暂停，不触发；expired 已到期，一次性触发器执行完或超过 end_at 后进入，不再触发。 |
| source | `"api"` / `"definition"` | 必填 / 必有；触发器来源。api 为通过 API 创建，可修改和删除；definition 为由工作流 YAML 的 schedule 生成，只能暂停或恢复，修改返回 409 TRIGGER_MANAGED。 |
| created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| created_by_user_id | `string` | 必填 / 必有；创建者的真实用户 ID，由网关转发；触发器启动的运行以该用户身份取令牌，用于审计与用量归属。 |
| next_fire_times | `string[]` | 必填 / 必有；接下来最多 5 次的触发时间（RFC 3339 UTC）；webhook、已暂停或已到期的触发器为空数组。 maxItems: 5 |
| last_firing | `object` / `null` | 必填 / 必有；最近一次触发记录；从未触发为 null。 |
| last_firing（分支1).id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| last_firing（分支1).trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| last_firing（分支1).scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| last_firing（分支1).fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| last_firing（分支1).outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| last_firing（分支1).run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| last_firing（分支1).resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| last_firing（分支1).error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| last_firing（分支1).error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| last_firing（分支1).error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |
| counts | `object` | 必填 / 必有；触发结果累计次数 &#123;started, skipped, missed, failed&#125;。 不接受额外字段。 |
| counts.started | `integer` | 必填 / 必有；成功启动运行的次数。 minimum: 0 |
| counts.skipped | `integer` | 必填 / 必有；因重叠策略为 skip 且上一次运行未结束而跳过的次数。 minimum: 0 |
| counts.missed | `integer` | 必填 / 必有；因延迟超过补跑窗口而错过的次数。 minimum: 0 |
| counts.failed | `integer` | 必填 / 必有；创建运行失败的次数。 minimum: 0 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 format: "date-time" |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 format: "date-time" |
| etag | `string` | 必填 / 必有；触发器当前修订标识，更新时作为 If-Match；不匹配返回 412。 |
| usage_30d | `object` / `null` | 可选；仅 GET /triggers/&#123;id&#125; 返回，列表省略。最近 30 天由此触发器启动的运行及子运行的归因实扣。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage_30d（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage_30d（分支1).cost | `string` | 必填 / 必有；已评级实扣的美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage_30d（分支1).pending_events | `integer` | 必填 / 必有；尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
  "owner": "tnt_3a9759864ccb4e00",
  "name": "sample-webhook-1791867412840-b05e8a",
  "description": "",
  "labels": {
    "namespace": "docs-samples"
  },
  "target": "docs-samples/sample-scripts-1791867412840-b05e8a@1.0.0",
  "input": {},
  "kind": "webhook",
  "schedule": null,
  "timezone": "UTC",
  "start_at": null,
  "end_at": null,
  "overlap": "skip",
  "catchup_window_seconds": 300,
  "webhook": {
    "input_mode": "body",
    "url_hint": "https://api-develop.deepraxis.ai/automation/v1/hooks/trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e/…"
  },
  "state": "paused",
  "source": "api",
  "created_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "created_by_user_id": "usr_49d4fcb99517",
  "next_fire_times": [],
  "last_firing": null,
  "counts": {
    "started": 0,
    "skipped": 0,
    "missed": 0,
    "failed": 0
  },
  "created_at": "2026-10-13T04:58:09.974Z",
  "updated_at": "2026-10-13T04:58:12.519Z",
  "etag": "etag_00mv67n1yf40e7b8d39ce5459d9ce835bfb1083701"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 恢复触发器

恢复触发并清空连续失败计数；已过结束时间或已执行完的一次性触发器保持 expired，启用配额已满时返回 TRIGGER_LIMIT。

`POST /automation/v1/triggers/{id}/resume`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；触发器 ID（trg_）。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/triggers/${TRIGGER_ID}/resume" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.resume({
  "path": {
    "id": env("TRIGGER_ID")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | `string` | 必填 / 必有；触发器名称，1–100 字符。 minLength: 1；maxLength: 100 |
| description | `string` | 必填 / 必有；触发器说明，最多 1000 字符。 maxLength: 1000 |
| labels | `object` | 必填 / 必有；触发器标签：字符串键值对，最多 64 个；键不能以保留前缀 praxis. 开头，违反返回 400 INPUT_INVALID。 |
| target | `string` | 必填 / 必有；要运行的脚本或工作流引用，形如 ns/name@标签或版本；默认跟随 latest，写成 @1.2.0 则钉死版本。 |
| input | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 必填 / 必有；任意 JSON 值：null、布尔、数字、字符串、数组或对象。 |
| input（分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| input（分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| kind | `"schedule"` / `"webhook"` | 必填 / 必有；触发器类型。schedule 按计划（cron、every 或 at）触发；webhook 由入站 HTTP 请求触发。 |
| schedule | `object` / `object` / `object` / `null` | 必填 / 必有；定时规则，kind=schedule 时有值（cron、every 或 at 三选一）；webhook 为 null。 |
| schedule（分支1)（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| schedule（分支1)（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| schedule（分支1)（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| schedule（分支1)（分支3).at | `string` | 必填 / 必有；一次性触发的时刻（RFC 3339 UTC）；不能早于当前时间，也不能晚于一年后。执行后触发器进入 expired。 format: "date-time" |
| timezone | `string` | 必填 / 必有；IANA 时区名，定时规则按它解释；API 缺省为 UTC。 default: "UTC" |
| start_at | `string` / `null` | 必填 / 必有；定时触发器的开始时间（RFC 3339 UTC）；此前不触发。没有限制为 null。 |
| end_at | `string` / `null` | 必填 / 必有；定时触发器的结束时间（RFC 3339 UTC）；超过后进入 expired。没有期限为 null。 |
| overlap | `"skip"` / `"allow"` | 必填 / 必有；重叠策略：上一次运行未结束时又到点，skip（默认）跳过，allow 照常启动。 default: "skip" |
| catchup_window_seconds | `integer` | 必填 / 必有；补跑窗口（秒），默认 300，仅定时触发器适用：到点时若已延迟超过该值（宕机、暂停期间），记为 missed 且不补跑。 default: 300；minimum: 0 |
| webhook | `object` / `null` | 必填 / 必有；webhook 设置，kind=webhook 时有值；schedule 触发器为 null。 |
| webhook（分支1).input_mode | `"body"` / `"envelope"` | 必填 / 必有；webhook 触发时传给目标的输入形态。body（默认）只传请求体；envelope 传含 body、raw_body、raw_body_encoding、headers、webhook_id、received_at 的信封对象。 |
| webhook（分支1).url_hint | `string` | 必填 / 必有；webhook 地址的掩码提示，省略号代替私密 token，不能用于调用。新建触发器为公开完整 URL；历史记录可能为 /automation/v1/hooks/&#123;id&#125;/… 相对路径。 |
| id | `string` | 必填 / 必有；触发器 ID，前缀 trg_；用于 webhook 地址以及触发器的所有接口。 |
| owner | `string` | 必填 / 必有；所属租户，由网关注入；按不透明字符串处理。 |
| state | `"enabled"` / `"paused"` / `"expired"` | 必填 / 必有；触发器状态。enabled 启用，会按计划或请求触发；paused 已暂停，不触发；expired 已到期，一次性触发器执行完或超过 end_at 后进入，不再触发。 |
| source | `"api"` / `"definition"` | 必填 / 必有；触发器来源。api 为通过 API 创建，可修改和删除；definition 为由工作流 YAML 的 schedule 生成，只能暂停或恢复，修改返回 409 TRIGGER_MANAGED。 |
| created_by | `object` | 必填 / 必有；网关注入的主体 &#123;type, id&#125;，表示谁发起或操作；本服务不解析名字，名字由控制台批量解析。 不接受额外字段。 |
| created_by.type | `"user"` / `"api_key"` / `"agent"` / `"run"` / `"trigger"` | 必填 / 必有；主体类型。user 为登录用户；api_key 为平台 API Key；agent 为智能体；run 为由运行本身（例如父运行）执行的操作；trigger 为触发器。 |
| created_by.id | `string` | 必填 / 必有；主体标识，含义随 type 而定：用户 ID、API Key ID、智能体 ID、运行 ID 或触发器 ID；按不透明字符串处理。 |
| created_by_user_id | `string` | 必填 / 必有；创建者的真实用户 ID，由网关转发；触发器启动的运行以该用户身份取令牌，用于审计与用量归属。 |
| next_fire_times | `string[]` | 必填 / 必有；接下来最多 5 次的触发时间（RFC 3339 UTC）；webhook、已暂停或已到期的触发器为空数组。 maxItems: 5 |
| last_firing | `object` / `null` | 必填 / 必有；最近一次触发记录；从未触发为 null。 |
| last_firing（分支1).id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| last_firing（分支1).trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| last_firing（分支1).scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| last_firing（分支1).fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| last_firing（分支1).outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| last_firing（分支1).run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| last_firing（分支1).resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| last_firing（分支1).error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| last_firing（分支1).error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| last_firing（分支1).error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |
| counts | `object` | 必填 / 必有；触发结果累计次数 &#123;started, skipped, missed, failed&#125;。 不接受额外字段。 |
| counts.started | `integer` | 必填 / 必有；成功启动运行的次数。 minimum: 0 |
| counts.skipped | `integer` | 必填 / 必有；因重叠策略为 skip 且上一次运行未结束而跳过的次数。 minimum: 0 |
| counts.missed | `integer` | 必填 / 必有；因延迟超过补跑窗口而错过的次数。 minimum: 0 |
| counts.failed | `integer` | 必填 / 必有；创建运行失败的次数。 minimum: 0 |
| created_at | `string` | 必填 / 必有；创建时间（RFC 3339 UTC）。 format: "date-time" |
| updated_at | `string` | 必填 / 必有；最近一次更新的时间（RFC 3339 UTC）。 format: "date-time" |
| etag | `string` | 必填 / 必有；触发器当前修订标识，更新时作为 If-Match；不匹配返回 412。 |
| usage_30d | `object` / `null` | 可选；仅 GET /triggers/&#123;id&#125; 返回，列表省略。最近 30 天由此触发器启动的运行及子运行的归因实扣。运行本身不收费；这里是运行中调用模型、搜索等能力产生的实扣，按调用归因；未评级的用量稍后计入。汇总超时（1.5 秒）或失败时为 null，详情仍返回 200。 |
| usage_30d（分支1).currency | `"USD"` | 必填 / 必有；金额币种，固定为 USD。 |
| usage_30d（分支1).cost | `string` | 必填 / 必有；已评级实扣的美元十进制字符串，精确到 6 位小数；没有用量时为 0.000000。 pattern: "^[0-9]+\\.[0-9]&#123;6&#125;$" |
| usage_30d（分支1).pending_events | `integer` | 必填 / 必有；尚未评级的用量事件数，金额稍后才计入。 minimum: 0 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
  "owner": "tnt_3a9759864ccb4e00",
  "name": "sample-webhook-1791867412840-b05e8a",
  "description": "Sample webhook",
  "labels": {
    "namespace": "docs-samples"
  },
  "target": "docs-samples/sample-scripts-1791867412840-b05e8a@1.0.0",
  "input": {
    "n": 41
  },
  "kind": "webhook",
  "schedule": null,
  "timezone": "UTC",
  "start_at": null,
  "end_at": null,
  "overlap": "skip",
  "catchup_window_seconds": 300,
  "webhook": {
    "input_mode": "body",
    "url_hint": "https://api-develop.deepraxis.ai/automation/v1/hooks/trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e/…"
  },
  "state": "enabled",
  "source": "api",
  "created_by": {
    "type": "api_key",
    "id": "key_3e00b8984967"
  },
  "created_by_user_id": "usr_49d4fcb99517",
  "next_fire_times": [],
  "last_firing": null,
  "counts": {
    "started": 0,
    "skipped": 0,
    "missed": 0,
    "failed": 0
  },
  "created_at": "2026-10-13T04:58:09.974Z",
  "updated_at": "2026-10-13T04:58:17.058Z",
  "etag": "etag_00mv67n5gidea13751125d4ad292fb95b07fac032e"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 429 | TRIGGER_LIMIT：租户已达到 100 个启用触发器的上限。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 立即触发

立即触发一次并返回 Firing，仍受当前状态、补跑窗口和 overlap 约束；启动失败记在触发结果的 error 中。

`POST /automation/v1/triggers/{id}/fire`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；触发器 ID（trg_）。 |
| header: Idempotency-Key | `string` | 可选；可选；1–256 字符。24 小时内同一 key 重放首个响应并带 Idempotent-Replayed: true；同 key 不同请求体返回 422；处理中返回 409。 minLength: 1；maxLength: 256 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/triggers/${TRIGGER_ID}/fire" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.fire({
  "path": {
    "id": env("TRIGGER_ID")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

| 响应头 | 类型 | 说明 |
| --- | --- | --- |
| Idempotent-Replayed | `boolean` | Present and true when replaying the first response for this key. |

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "id": "frg_00mv67n833fec8a47a90904782ac1a8f1fef264379",
  "trigger_id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
  "scheduled_at": "2026-10-13T04:58:20.215Z",
  "fired_at": "2026-10-13T04:58:20.215Z",
  "outcome": "started",
  "run_id": "run_00mv67n8ao7de994212f453fdfe7def756b57ec5cdeb562a1222f554c6f3d9f428ec25480e",
  "resolved_version": "1.0.0",
  "error": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 |
| 409 | IDEMPOTENCY_IN_FLIGHT：同一幂等键的请求仍在处理中。 RUN_INVALID_STATE：当前状态不允许执行该动作。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 422 | IDEMPOTENCY_KEY_MISMATCH：同一幂等键已用于不同请求内容。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 轮换回调地址

仅适用于 webhook 触发器：立即作废旧 token，返回新的完整 webhook_url；之后的详情读取不会再次显示完整地址。

`POST /automation/v1/triggers/{id}/rotate-webhook`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；触发器 ID（trg_）。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/triggers/${TRIGGER_ID}/rotate-webhook" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.rotateWebhook({
  "path": {
    "id": env("TRIGGER_ID")
  },
  "body": {}
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| webhook_url | `string` | 必填 / 必有；新的完整 webhook 地址，含私密 token；只返回这一次，请妥善保存，丢失后需再次轮换。旧地址立即失效。 format: "uri" |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "webhook_url": "https://api-develop.deepraxis.ai/automation/v1/hooks/trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e/${WEBHOOK_TOKEN}"
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 列出触发历史

按时间倒序读取最近 30 天的触发记录。结果包括实际版本、运行 ID 与失败原因。

`GET /automation/v1/triggers/{id}/firings`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: id | `string` | 必填；触发器 ID（trg_）。 |
| query: limit | `integer` | 可选；每页条数，整数 1–100，默认 25。 minimum: 1；maximum: 100 |
| query: cursor | `string` | 可选；上一页返回的 next_cursor，不透明字符串；保持原查询条件继续翻页。 |
| query: outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"[]` | 可选；按结果筛选，多个值用逗号分隔（OR）；与 run_id 同时提供时取交集。 |
| query: run_id | `string` | 可选；仅返回关联此运行 ID 的记录。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
curl --fail-with-body -X GET "https://api.deepraxis.ai/automation/v1/triggers/${TRIGGER_ID}/firings" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.firings.list({
  "path": {
    "id": env("TRIGGER_ID")
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | `object[]` | 必填 / 必有；本页的最近 30 天的触发记录，按 created_at 倒序、id 倒序排列。 |
| data[].id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| data[].trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| data[].scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| data[].fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| data[].outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| data[].run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| data[].resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| data[].error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| data[].error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| data[].error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |
| next_cursor | `string` / `null` | 必填 / 必有；下一页游标，原样传给 cursor 参数并保持原查询条件；没有更多页为 null。接口不返回总数。 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "data": [
    {
      "id": "frg_00mv67n833fec8a47a90904782ac1a8f1fef264379",
      "trigger_id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
      "scheduled_at": "2026-10-13T04:58:20.215Z",
      "fired_at": "2026-10-13T04:58:20.215Z",
      "outcome": "started",
      "run_id": "run_00mv67n8ao7de994212f453fdfe7def756b57ec5cdeb562a1222f554c6f3d9f428ec25480e",
      "resolved_version": "1.0.0",
      "error": null
    },
    {
      "id": "frg_00mv67n6in516077a64cfc4102a4da939476a3fa78",
      "trigger_id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
      "scheduled_at": "2026-10-13T04:58:18.384Z",
      "fired_at": "2026-10-13T04:58:18.384Z",
      "outcome": "started",
      "run_id": "run_00mv67n6vvebb47a96bf4b54630d8a07786ec923a68d3b722c2f7ffca4e0a553053c4a5421",
      "resolved_version": "1.0.0",
      "error": null
    }
  ],
  "next_cursor": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 预览触发时间

校验规则与时区并预览未来触发时间。返回人读说明及最多五个未来时间，不会创建触发器或运行。

`POST /automation/v1/triggers/preview`

## 鉴权 [#鉴权]

`Authorization: Bearer $PRAXIS_API_KEY`

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| header: Accept-Language | `string` | 可选；人读描述的语言，支持中文（默认）与英文，按语言权重选择。 |

### application/json [#applicationjson]

不接受额外字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| schedule | `object` / `object` / `object` | 必填 / 必有；三选一：cron 为五段表达式（支持 L/W/#）；every 至少一分钟；at 为带时区的一次性时间。与创建使用相同校验：at 须在当前时间至一年后之间；every 须为正整数毫秒且不超过 366 天。 |
| schedule（分支1).cron | `string` | 必填 / 必有；Five fields; supports L, W, #. DST gaps skip the day and overlaps run once. |
| schedule（分支2).every | `string` / `object` | 必填 / 必有；时长：ISO 8601 字符串（如 PT5M），或 &#123;days, hours, minutes, seconds, milliseconds&#125; 对象；折算后必须是 60000 至 31622400000 毫秒（1 分钟至 366 天）的整数毫秒。 |
| schedule（分支2).every（分支2).days | `integer` | 可选；天数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).hours | `integer` | 可选；小时数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).minutes | `integer` | 可选；分钟数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).seconds | `integer` | 可选；秒数，非负整数。 minimum: 0 |
| schedule（分支2).every（分支2).milliseconds | `integer` | 可选；毫秒数，非负整数。 minimum: 0 |
| schedule（分支3).at | `string` | 必填 / 必有；一次性触发时刻，需带 Z 或 ±HH:MM 时区；必须在请求时刻至一年后之间。调用时将示例替换为该范围内的未来时间。 pattern: "(Z\|[+-]\\d\\d:\\d\\d)$"；format: "date-time" |
| timezone | `string` | 可选；IANA 时区，默认 UTC；夏令时跳过不存在的时刻，重复时刻只触发一次。 |

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

```bash
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/triggers/preview" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "schedule": {
    "cron": "0 9 * * *"
  },
  "timezone": "UTC"
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: env('PRAXIS_API_KEY'),
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.triggers.preview({
  "body": {
    "schedule": {
      "cron": "0 9 * * *"
    },
    "timezone": "UTC"
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| description | `string` | 必填 / 必有；规则的人读描述；常见 cron 为自然语言，其余回显表达式。语言由 Accept-Language 决定，默认中文。 |
| next_fire_times | `string[]` | 必填 / 必有；按该规则和时区计算的接下来最多 5 次触发时间（RFC 3339 UTC）。 maxItems: 5 |

### 实测响应 [#实测响应]

HTTP 200

```json
{
  "description": "每天 09:00 · UTC",
  "next_fire_times": [
    "2026-10-13T09:00:00.000Z",
    "2026-10-14T09:00:00.000Z",
    "2026-10-15T09:00:00.000Z",
    "2026-10-16T09:00:00.000Z",
    "2026-10-17T09:00:00.000Z"
  ]
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 SCHEDULE_INVALID：定时规则或时间边界无效。 TIMEZONE_INVALID：时区不是有效的 IANA 时区。 INTERVAL_TOO_SHORT：定时间隔短于一分钟。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 接收入站回调

无需 API Key，以 URL 中 token 鉴权；token 错误、触发器不存在、类型不符或不在时间窗口内均返回 404；触发器处于暂停状态（连续 5 次失败熔断或人工暂停）返回 409 TRIGGER_PAUSED，message 说明原因，hint 给出恢复办法 POST /automation/v1/triggers/{id}/resume。原始请求体上限 512 KiB；组装后的运行输入（含原文与解析后的副本）序列化后最多 1 MiB，超限同步返回 413，不创建触发记录；webhook-id 去重 24 小时。202 的 outcome=accepted 表示已受理，最终结果随后更新，重复请求为 deduped。JSON 解析失败时 body 为 null；其它 UTF-8 为原文，非 UTF-8 为 base64。envelope 包含 body、raw_body、raw_body_encoding、白名单 headers、webhook_id 和 received_at；raw_body 保留原始字节，raw_body_encoding 为 utf8 或 base64，可用于自行验签。

`POST /automation/v1/hooks/{trigger_id}/{token}`

## 鉴权 [#鉴权]

使用创建或轮换时返回的 webhook URL；路径中的 token 是凭据，无需 Bearer Key。

## 请求字段 [#请求字段]

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| path: trigger_id | `string` | 必填；触发器 ID（trg_）。 |
| path: token | `string` | 必填；创建或轮换时返回的私密 URL token；请勿公开。 |
| header: webhook-id | `string` | 可选；可选去重标识，同一触发器内保留 24 小时。 |

### application/json [#applicationjson]

任意 JSON 值：null、布尔、数字、字符串、数组或对象。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| （分支5).* | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |
| （分支6)[] | `null` / `string` / `number` / `boolean` / `object` / `JSON[]` | 递归 JSON 值。 |

### text/plain [#textplain]

string
### application/octet-stream

string

## 示例 [#示例]

[SDK 安装与示例环境](/docs/api/native/automation)

先设置以下环境变量，使用你自己的资源：

| 变量 | 来源 |
| --- | --- |
| TRIGGER_ID | [触发器 id；webhook 调用前需恢复启用](/docs/api/native/automation/createTrigger) |
| WEBHOOK_TOKEN | [新 webhook_url 的最后一段；不要公开](/docs/api/native/automation/rotateTriggerWebhook) |

```bash
: "${TRIGGER_ID:?Set TRIGGER_ID}"
: "${WEBHOOK_TOKEN:?Set WEBHOOK_TOKEN}"
curl --fail-with-body -X POST "https://api.deepraxis.ai/automation/v1/hooks/${TRIGGER_ID}/${WEBHOOK_TOKEN}" \
  -H "Content-Type: application/json" \
  --data '{
  "n": 41
}'
```

```typescript
import { createAutomationClient } from '@deepraxis/sdk/automation';

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name}`);
  return value;
}
const automation = createAutomationClient({
  apiKey: '',
  baseUrl: 'https://api.deepraxis.ai',
  maxRetries: 0,
  timeoutMs: 90_000,
});
const result = await automation.hooks.send({
  "path": {
    "trigger_id": env("TRIGGER_ID"),
    "token": env("WEBHOOK_TOKEN")
  },
  "body": {
    "n": 41
  }
});
console.log(result);
```

## 响应 [#响应]

### HTTP 202 [#http-202]

Success

`application/json`

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | `string` | 必填 / 必有；触发记录 ID；记录保留 30 天。 |
| trigger_id | `string` | 必填 / 必有；所属触发器 ID（trg_ 前缀）。 |
| scheduled_at | `string` | 必填 / 必有；计划触发的时间（RFC 3339 UTC）；webhook 取请求到达时间。 format: "date-time" |
| fired_at | `string` | 必填 / 必有；实际触发的时间（RFC 3339 UTC）。 format: "date-time" |
| outcome | `"accepted"` / `"started"` / `"skipped_overlap"` / `"missed"` / `"failed"` / `"deduped"` | 必填 / 必有；触发结果。accepted 已持久化等待处理；started 已创建运行；skipped_overlap 因上一次运行未结束而跳过；missed 到点时延迟超过补跑窗口，不补跑；failed 创建运行失败；deduped 与 24 小时内相同 webhook-id 的请求重复，已去重。 |
| run_id | `string` / `null` | 必填 / 必有；本次触发创建的运行 ID（run_ 前缀）；未创建运行为 null。 |
| resolved_version | `string` / `null` | 必填 / 必有；本次触发实际解析到的精确版本号；尚未解析或失败时为 null。 |
| error | `object` / `null` | 必填 / 必有；触发失败时的原因 &#123;code, message&#125;；没有失败为 null。 |
| error（分支1).code | `string` | 必填 / 必有；失败的错误码。 |
| error（分支1).message | `string` | 必填 / 必有；失败的说明文字。 |

### 实测响应 [#实测响应]

HTTP 202

```json
{
  "id": "frg_00mv67n6in516077a64cfc4102a4da939476a3fa78",
  "trigger_id": "trg_00mv67mzzqa0d63b98d72446dd9d1331051a3e100e",
  "scheduled_at": "2026-10-13T04:58:18.384Z",
  "fired_at": "2026-10-13T04:58:18.384Z",
  "outcome": "accepted",
  "run_id": null,
  "resolved_version": null,
  "error": null
}
```

## 错误码 [#错误码]

| HTTP | 错误码与说明 |
| --- | --- |
| 400 | INVALID_PARAMS：请求参数、路径、游标或请求体格式无效。 |
| 404 | TRIGGER_NOT_FOUND：触发器不存在或不可访问，回调鉴权失败也使用此错误。 |
| 405 | METHOD_NOT_ALLOWED：仅支持 POST；其它方法无需鉴权即返回 405，Allow 为 POST。 |
| 409 | TRIGGER_PAUSED：触发器处于暂停状态：连续 5 次触发失败触发熔断自动暂停，或被人工暂停；响应 message 说明原因，hint 给出恢复办法：恢复该触发器（triggers.resume）。 |
| 412 | PRECONDITION_FAILED：修订、源码摘要或并发写入条件不匹配。 |
| 413 | PAYLOAD_TOO_LARGE：请求内容超过本操作允许的大小。 |
| default | RFC 9457 automation problem. 429 includes Retry-After. |

[鉴权错误与通用错误](/docs/api/errors) · 排查时保留响应头 `X-Request-Id`。

# 组织 API

## 基础地址 [#基础地址]

## 接入 [#接入]

## 事实与边界 [#事实与边界]

| 事实             | 说明                                                                                                            |
| -------------- | ------------------------------------------------------------------------------------------------------------- |
| 组织由 Key 决定     | 调用方的 API Key 解析出唯一的组织；路径里没有组织 ID，组织的任何有效 API Key 都可读本域                                                        |
| 只覆盖实际扣费        | 统计组织实际被扣的费用，按结算币种（人民币 CNY 或美元 USD）计；组织的赠送额度先于现金被扣，也在其中                                                        |
| 字段名按 FOCUS 1.3 | BilledCost、ServiceName、ConsumedQuantity 等列名与 [FOCUS 1.3 规范](https://focus.finops.org/)逐字一致                    |
| 时间一律 UTC       | 窗口边界与时间桶都是 UTC ISO 8601；桶对齐到整点或自然日                                                                            |
| 查询窗口上限 93 天    | 查询费用 / 查询用量 / 用量事件一次最多查 93 天；更久的账用[费用明细导出](/docs/api/native/organization/exportOrganizationCharges)，它按天在服务端分页 |
| 分页是不透明游标       | 列表带 `has_more` 与 `next_page`；把 `next_page` 原样放进 `page` 参数取下一页                                                 |

金额都是十进制字符串（如 `"0.001234"`），币种见同一行的 `BillingCurrency`（CNY 或 USD）；不要用浮点数相加——对账请按字符串精确十进制求和，且不同币种不要相加。

这里只统计从资金账户以美元扣费的用量；Credits 余额不在这个域。鉴权方式见[鉴权](/docs/api/authentication)。

## 端点 [#端点]

| 方法  | 路径                                                                       | 说明       | 支持   |
| --- | ------------------------------------------------------------------------ | -------- | ---- |
| GET | [`/v1/costs`](/docs/api/native/organization/listOrganizationCosts)       | 查询费用     | ● 支持 |
| GET | [`/v1/usage`](/docs/api/native/organization/listOrganizationUsage)       | 查询用量     | ● 支持 |
| GET | [`/v1/events`](/docs/api/native/organization/listOrganizationEvents)     | 列出用量事件   | ● 支持 |
| GET | [`/v1/events/{id}`](/docs/api/native/organization/getOrganizationEvent)  | 查看单个用量事件 | ● 支持 |
| GET | [`/v1/charges`](/docs/api/native/organization/exportOrganizationCharges) | 导出费用明细   | ● 支持 |

## 与官方的差异 [#与官方的差异]

* 聚合信封照 OpenAI organization usage/costs、分桶与 estimated 标记照 AWS GetCostAndUsage、列名按 FOCUS 1.3、明细导出照 Vercel charges 的 JSONL。只给原始事实：占比、环比、前 N 名等派生视图不在本域，请在调用方自行计算。

参数与字段的权威定义以本站 [`/meta/v1/openapi.yaml`](/docs/api/native/meta/healthCheck) 公开的规范与 [FOCUS 1.3 规范](https://focus.finops.org/)为准。

错误按 problem+json 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 查询费用

## 响应 [#响应]

### HTTP 200 [#http-200]

Cost page

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;page&#96;. |
| data | array&lt;object&gt; | Cost buckets in time order, one per hour or day of the requested window. |
| data[].object | string | Object type; always &#96;bucket&#96;. |
| data[].starting_at | string | Start of the bucket, UTC, inclusive. |
| data[].ending_at | string | End of the bucket, UTC, exclusive. |
| data[].estimated | boolean | Always false; kept for the AWS GetCostAndUsage shape. |
| data[].results | array&lt;object&gt; | Aggregates of the bucket, one entry per group requested with group_by. |
| has_more | boolean | Whether more results exist beyond this page; request again with &#96;page&#96; set to &#96;next_page&#96; to read them. |
| next_page | string &#124; null | Opaque cursor for the next page; null on the last page. Pass it unchanged as &#96;page&#96;. |

## 响应字段 [#响应字段]

| 字段                                                            | 说明                                                            |
| ------------------------------------------------------------- | ------------------------------------------------------------- |
| `object`                                                      | 固定 "page"                                                     |
| `data[].object`                                               | 固定 "bucket"                                                   |
| `data[].starting_at / data[].ending_at`                       | 桶的起止时间（UTC，整点或自然日对齐）                                          |
| `data[].estimated`                                            | 恒为 false：费用入账即为最终金额；保留该字段是为了与 AWS GetCostAndUsage 的形状一致       |
| `data[].results[].ServiceName`                                | 产生用量的服务名（仅在请求 group\_by 含 ServiceName 时出现）                    |
| `data[].results[].ServiceCategory`                            | FOCUS 服务类别（仅按请求出现）                                            |
| `data[].results[].ResourceId / data[].results[].ResourceName` | 资源 ID 与显示名；ResourceName 随 ResourceId 附带，解析不到显示名时等于 ResourceId |
| `data[].results[].BilledCost`                                 | 该桶该组的费用，十进制字符串，币种见 BillingCurrency                            |
| `data[].results[].BillingCurrency`                            | 扣费币种，CNY 或 USD；同一组在一个桶里用过两种币种时分成两行                            |
| `has_more / next_page`                                        | 是否还有下一页；下一页的不透明游标（null 表示没有更多）                                |

支付一个事件的交易明细见[查看单个用量事件](/docs/api/native/organization/getOrganizationEvent)。

# 查询用量

## 响应 [#响应]

### HTTP 200 [#http-200]

Usage page

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;page&#96;. |
| data | array&lt;object&gt; | Usage buckets in time order, one per hour or day of the requested window. |
| data[].object | string | Object type; always &#96;bucket&#96;. |
| data[].starting_at | string | Start of the bucket, UTC, inclusive. |
| data[].ending_at | string | End of the bucket, UTC, exclusive. |
| data[].estimated | boolean | Always false; kept for the AWS GetCostAndUsage shape. |
| data[].results | array&lt;object&gt; | Aggregates of the bucket, one entry per group requested with group_by. |
| has_more | boolean | Whether more results exist beyond this page; request again with &#96;page&#96; set to &#96;next_page&#96; to read them. |
| next_page | string &#124; null | Opaque cursor for the next page; null on the last page. Pass it unchanged as &#96;page&#96;. |

## 响应字段 [#响应字段]

| 字段                                                            | 说明                                        |
| ------------------------------------------------------------- | ----------------------------------------- |
| `object / data[].object`                                      | 固定 "page" / 固定 "bucket"                   |
| `data[].starting_at / data[].ending_at / data[].estimated`    | 桶的起止（UTC）与 estimated 标记（恒为 false），与查询费用相同 |
| `data[].results[].ServiceName / ServiceCategory`              | 服务列（仅按请求出现）                               |
| `data[].results[].ResourceId / data[].results[].ResourceName` | 资源列；ResourceName 随 ResourceId 附带          |
| `data[].results[].ConsumedQuantity`                           | 该桶该组的消耗数量，十进制字符串                          |
| `data[].results[].ConsumedUnit`                               | 计量单位；不同单位各成一行，永远不会相加                      |
| `has_more / next_page`                                        | 游标分页，与查询费用相同                              |

支付一个事件的交易明细见[查看单个用量事件](/docs/api/native/organization/getOrganizationEvent)。

# 列出用量事件

## 响应 [#响应]

### HTTP 200 [#http-200]

Event page

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;page&#96;. |
| data | array&lt;object&gt; | Usage events, newest first. |
| data[].object | string | Object type; always &#96;usage.event&#96;. |
| data[].id | string | Id of the usage event; pass it to getOrganizationEvent. |
| data[].occurred_at | string | Time at which the usage happened, UTC. |
| data[].ServiceName | string | Name of the platform service that produced the usage (the source service of the usage event). |
| data[].ServiceCategory | string | Category of the service; a service without a registered category reports its own name. |
| data[].ResourceId | string | Id of the resource that the usage belongs to. |
| data[].ResourceName | string | Display name of the resource; falls back to ResourceId when no name is known. |
| data[].BilledCost | string | Amount billed in USD as an exact decimal string; unsettled usage counts as 0 until it settles. |
| data[].BillingCurrency | string | Currency of BilledCost; always &#96;USD&#96;. |
| data[].ChargeClass | string &#124; null | &#96;Correction&#96; for an event that corrects an earlier charge (its BilledCost is negative); null for ordinary usage. |
| data[].request_id | string &#124; null | X-Request-Id of the API call that produced the usage; null for usage that does not come from a request. |
| data[].settlement | object | How the usage was charged: settlement state, any shortfall, and why nothing was charged. |
| data[].lines | array&lt;object&gt; | Metering lines mapped from the billing measurements; the priced split (ListUnitPrice, PricingUnit, BilledCost) rides only GET /events/&#123;id&#125;.  |
| has_more | boolean | Whether more results exist beyond this page; request again with &#96;page&#96; set to &#96;next_page&#96; to read them. |
| next_page | string &#124; null | Opaque cursor for the next page; null on the last page. Pass it unchanged as &#96;page&#96;. |

## 响应字段 [#响应字段]

| 字段                                                                 | 说明                                                     |
| ------------------------------------------------------------------ | ------------------------------------------------------ |
| `object`                                                           | 固定 "page"                                              |
| `data[].object`                                                    | 固定 "usage.event"                                       |
| `data[].id`                                                        | 事件 id；查单条明细、对账都用它                                      |
| `data[].occurred_at`                                               | 事件发生时间（UTC）                                            |
| `data[].ServiceName / ServiceCategory / ResourceId / ResourceName` | FOCUS 服务与资源列                                           |
| `data[].BilledCost / BillingCurrency`                              | 事件费用（十进制字符串）与扣费币种（CNY 或 USD）                           |
| `data[].ChargeClass`                                               | 更正事件为 "Correction"（费用为负数），普通事件为 null                   |
| `data[].request_id`                                                | 产生这次用量的那次 API 调用响应头 X-Request-Id 的值，可拿去调用日志里查同一次请求     |
| `data[].settlement.status`                                         | settled（已扣费）/ no\_charge（已记录，不收费）/ rejected（计费拒绝了这次扣费） |
| `data[].settlement.shortfall / data[].settlement.zero_reason`      | 目前恒为 null，保留给之后的结算细节                                   |
| `has_more / next_page`                                             | 按发生时间倒序逐页；游标不透明，不重复、不遗漏                                |

支付一个事件的交易明细见[查看单个用量事件](/docs/api/native/organization/getOrganizationEvent)。

# 查看单个用量事件

## 响应 [#响应]

### HTTP 200 [#http-200]

The usage event

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;usage.event&#96;. |
| id | string | Id of the usage event; pass it to getOrganizationEvent. |
| occurred_at | string | Time at which the usage happened, UTC. |
| ServiceName | string | Name of the platform service that produced the usage (the source service of the usage event). |
| ServiceCategory | string | Category of the service; a service without a registered category reports its own name. |
| ResourceId | string | Id of the resource that the usage belongs to. |
| ResourceName | string | Display name of the resource; falls back to ResourceId when no name is known. |
| BilledCost | string | Amount billed in USD as an exact decimal string; unsettled usage counts as 0 until it settles. |
| BillingCurrency | string | Currency of BilledCost; always &#96;USD&#96;. |
| ChargeClass | string &#124; null | &#96;Correction&#96; for an event that corrects an earlier charge (its BilledCost is negative); null for ordinary usage. |
| request_id | string &#124; null | X-Request-Id of the API call that produced the usage; null for usage that does not come from a request. |
| settlement | object | How the usage was charged: settlement state, any shortfall, and why nothing was charged. |
| settlement.status | string | Settlement state of the event. |
| settlement.shortfall | string &#124; null | USD amount that could not be charged, as a decimal string, when status is settled_with_shortfall; null otherwise. |
| settlement.zero_reason | string &#124; null | Why nothing was charged for the event: &#96;byok&#96; when the caller used its own provider key; null when a charge applies. |
| lines | array&lt;object&gt; | Priced lines of the event; their BilledCost values add up to the event's BilledCost. |
| lines[].meter | string | Key of the meter that measured the line. |
| lines[].display_name | string | English label of the meter; falls back to the meter key in list pages. |
| lines[].ConsumedQuantity | string | Quantity consumed, an exact decimal string in ConsumedUnit. |
| lines[].ConsumedUnit | string | Unit of ConsumedQuantity as reported by the metering line; quantities of different units are never added together. |
| lines[].ListUnitPrice | string &#124; null | List price in USD per PricingUnit as a decimal string; null when the line is not priced. |
| lines[].PricingUnit | string &#124; null | Unit that ListUnitPrice applies to; null when the line is not priced. |
| lines[].BilledCost | string | Amount billed for this line in USD as a decimal string. |
| x_Charges | array&lt;object&gt; | The transactions that paid this event; their BilledCost sums to the event's BilledCost. |
| x_Charges[].transaction_id | string | The id of the billing transaction that paid part of this event. |
| x_Charges[].BilledCost | string | Amount billed in USD as an exact decimal string; unsettled usage counts as 0 until it settles. |
| x_Charges[].BillingCurrency | string | Currency of BilledCost; always &#96;USD&#96;. |
| x_Charges[].sub_account | string | Which balance the transaction was taken from. |

## 响应字段 [#响应字段]

| 字段                                                                                                                                 | 说明                                                                                                                          |
| ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `object / id / occurred_at`                                                                                                        | 固定 "usage.event"、事件 id、发生时间（UTC）                                                                                            |
| `ServiceName / ServiceCategory / ResourceId / ResourceName / BilledCost / BillingCurrency / ChargeClass / request_id / settlement` | 与用量事件列表中同一事件完全相同的字段                                                                                                         |
| `lines[].meter / lines[].display_name`                                                                                             | 计量项标识与其英文显示名                                                                                                                |
| `lines[].ConsumedQuantity / ConsumedUnit`                                                                                          | 该计量项的消耗数量与单位                                                                                                                |
| `lines[].ListUnitPrice / PricingUnit`                                                                                              | 恒为 null：计费按整个事件定价，没有逐计量项的单价                                                                                                 |
| `lines[].BilledCost`                                                                                                               | 该计量项的费用，等于事件的 BilledCost                                                                                                    |
| `x_Charges[]`                                                                                                                      | 支付这个事件的交易：transaction\_id、BilledCost、BillingCurrency，以及 sub\_account（promotional 赠送额度或 cash 现金；赠送额度先扣）。各笔相加等于事件的 BilledCost |

支付一个事件的交易明细见[查看单个用量事件](/docs/api/native/organization/getOrganizationEvent)。

# 导出费用明细

## 响应 [#响应]

### HTTP 200 [#http-200]

FOCUS 1.3 JSONL stream

**application/x-ndjson**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| ChargePeriodStart | string | Start of the charge period (the event time), UTC. |
| ChargePeriodEnd | string | End of the charge period (the event time), UTC. |
| BilledCost | string | Amount billed in USD as an exact decimal string; unsettled usage counts as 0 until it settles. |
| BillingCurrency | string | Currency of BilledCost; always &#96;USD&#96;. |
| ServiceName | string | Name of the platform service that produced the usage (the source service of the usage event). |
| ServiceCategory | string | Category of the service; a service without a registered category reports its own name. |
| ResourceId | string | Id of the resource that the usage belongs to. |
| ResourceName | string | Display name of the resource; falls back to ResourceId when no name is known. |
| ConsumedQuantity | string | Quantity consumed, an exact decimal string in ConsumedUnit. |
| ConsumedUnit | string | Unit of ConsumedQuantity as reported by the metering line; quantities of different units are never added together. |
| ChargeCategory | string | Kind of charge. |
| ChargeClass | string &#124; null | &#96;Correction&#96; for an event that corrects an earlier charge (its BilledCost is negative); null for ordinary usage. |
| ChargeDescription | string | Text such as &#96;&lt;service&gt;/&lt;offering&gt; usage&#96; that says what was charged. |
| x_RequestId | string &#124; null | Always null in the export; look up the request id of an event with getOrganizationEvent. |
| x_EventId | string | Id of the usage event this record comes from; pass it to getOrganizationEvent. |

## 响应字段 [#响应字段]

| 字段                                                          | 说明                                      |
| ----------------------------------------------------------- | --------------------------------------- |
| `ChargePeriodStart / ChargePeriodEnd`                       | 计费周期起止（UTC）                             |
| `BilledCost / BillingCurrency`                              | 该事件费用（十进制字符串）与扣费币种（CNY 或 USD）           |
| `ServiceName / ServiceCategory / ResourceId / ResourceName` | FOCUS 服务与资源列                            |
| `ConsumedQuantity / ConsumedUnit`                           | 消耗数量与计量单位                               |
| `ChargeCategory`                                            | Usage（用量）或 Adjustment（调整）               |
| `ChargeClass`                                               | 更正记录为 "Correction"，普通记录为 null           |
| `ChargeDescription`                                         | 计量项的人类可读描述                              |
| `x_RequestId / x_EventId`                                   | 产生这条记录的 API 调用的 X-Request-Id；对应的用量事件 id |

支付一个事件的交易明细见[查看单个用量事件](/docs/api/native/organization/getOrganizationEvent)。

# Meta API

## 基础地址 [#基础地址]

## 接入 [#接入]

## 端点 [#端点]

| 方法  | 路径                                                                | 说明   | 支持   |
| --- | ----------------------------------------------------------------- | ---- | ---- |
| GET | [`/v1/health`](/docs/api/native/meta/healthCheck)                 | 健康检查 | ● 支持 |
| GET | [`/v1/methods`](/docs/api/native/meta/metaMethodsSearch)          | 搜索方法 | ● 支持 |
| GET | [`/v1/methods/{name}`](/docs/api/native/meta/metaMethodsRetrieve) | 读取方法 | ● 支持 |

## 与官方的差异 [#与官方的差异]

* 本面是平台自描述面，不对应任何第三方官方 API；healthCheck 与方法目录都无需鉴权，healthCheck 返回纯文本 `ok`。
* <a href="/docs/api/native/meta/metaMethodsSearch">搜索方法</a>：非空 q 按方法名、摘要和描述的相关度搜索，词序和大小写不影响匹配；limit 为 1 到 50 的整数，默认 20。不带 q 或 q 全为空白时按方法名排序列出，limit 为 1 到 200 的整数，默认 50；has\_more 为 true 时将 last\_id 原样作为 after\_id 取下一页。搜索时忽略 after\_id。limit 越界返回 400 INVALID\_PARAMS。目录只包含平台方法（praxis.\*），不含会话里的 MCP 工具。
* <a href="/docs/api/native/meta/metaMethodsRetrieve">读取方法</a>：name 取自搜索结果，必须与方法名完全一致。声明不会被截断，字段名和枚举值请直接从中复制。未知名称返回 404 METHOD\_NOT\_FOUND，hint 列出最多三个相近的名称。

Meta 是平台自描述面：`/meta/v1/openapi.yaml` 返回当前环境的完整 OpenAPI 规范，参数与字段以它为准。

错误按 problem+json 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 健康检查

## 响应 [#响应]

### HTTP 200 [#http-200]

The API edge is up; the body is the plain text \`ok\`.

**text/plain**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string | Always the literal &#96;ok&#96;. |

# 搜索方法

## 响应 [#响应]

### HTTP 200 [#http-200]

Matching methods, best match first. An empty \`data\` array means nothing matched; try fewer or different words.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| has_more | boolean | Present without q; true when another page follows. |
| first_id | string &#124; null | Present without q; first method name in this page, or null for an empty page. |
| last_id | string &#124; null | Present without q; last method name in this page, or null for an empty page. Pass as after_id to continue. |
| data | array&lt;object&gt; | Matching methods ordered by relevance for search, or by name for unranked listing. |
| data[].params | string | Compact argument list grouped by location, for example &#96;path: database_id*, table* · query: select, order · body*&#96;. A trailing &#96;*&#96; marks a required argument; &#96;body&#96; stands for the JSON request body. Call &#96;GET /meta/v1/methods/&#123;name&#125;&#96; for each argument's type and description. |
| data[].name | string | Method name such as &#96;praxis.agent.agents.list&#96;. Pass it to &#96;GET /meta/v1/methods/&#123;name&#125;&#96; and call it as &#96;await praxis.agent.agents.list(args)&#96; in codemode or an automation script. |
| data[].summary | string | One-line statement of what the method does. |
| data[].http | string | HTTP verb the method sends, for example GET or POST. |
| data[].path | string | Public API path template the method calls, with &#96;&#123;param&#125;&#96; placeholders filled from &#96;args.path&#96;. |

# 读取方法

## 响应 [#响应]

### HTTP 200 [#http-200]

The method with its complete declaration.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| name | string | Method name, for example &#96;praxis.agent.agents.list&#96;. |
| summary | string | One-line statement of what the method does. |
| description | string | Full guidance for the method from the API reference, including when to use it, limits and error behaviour. May be empty for methods documented only by summary. |
| http | string | HTTP verb the method sends. |
| path | string | Public API path template with &#96;&#123;param&#125;&#96; placeholders. |
| declaration | string | Complete TypeScript signature, &#96;name(args): Promise&lt;Result&gt;&#96;. &#96;args&#96; carries &#96;path&#96;, &#96;query&#96;, &#96;headers&#96; and &#96;body&#96; members exactly as declared. Never truncated. |
| parameters | array&lt;object&gt; | Path, query and header parameters of the operation. |
| parameters[].name | string | Parameter name as sent on the wire. |
| parameters[].in | string | Where the parameter goes, one of &#96;path&#96;, &#96;query&#96; or &#96;header&#96;; maps to the matching member of &#96;args&#96;. |
| parameters[].required | boolean | Whether the call is rejected when the parameter is missing. |
| parameters[].description | string | Meaning, format and allowed values of the parameter. |
| parameters[].type | string | TypeScript type of the parameter value. |
| request_body | object | Request body expectations; null when the method takes no body. |
| request_body.required | boolean | Whether &#96;args.body&#96; must be supplied. |
| request_body.description | string | What the body carries. |
| request_body.content_types | array&lt;string&gt; | Media types the body may use; the first is the default. |
| responses | array&lt;object&gt; | Documented responses, successful and failed. |
| responses[].status | string | HTTP status code or &#96;default&#96;. |
| responses[].description | string | What the response means and what to do next. |
| responses[].content_types | array&lt;string&gt; | Media types the response may use. |

# 云端浏览器 API

[连接与使用指南](/docs/cloud/services/browser)

基础地址: `https://api-develop.deepraxis.ai/browser`

请求头: `Authorization: Bearer $PRAXIS_API_KEY`

请求 ID 响应头: `X-Request-Id`

| 操作                                                                       | 方法与路径                                                    |
| ------------------------------------------------------------------------ | -------------------------------------------------------- |
| [创建浏览器会话](/docs/api/native/browser/browserCreateSession)                 | `POST /browser/v1/sessions`                              |
| [列出浏览器会话](/docs/api/native/browser/browserListSessions)                  | `GET /browser/v1/sessions`                               |
| [读取浏览器会话](/docs/api/native/browser/browserGetSession)                    | `GET /browser/v1/sessions/{sessionId}`                   |
| [关闭浏览器会话](/docs/api/native/browser/browserCloseSession)                  | `POST /browser/v1/sessions/{sessionId}`                  |
| [读取调试地址](/docs/api/native/browser/browserGetDebug)                       | `GET /browser/v1/sessions/{sessionId}/debug`             |
| [列出会话事件](/docs/api/native/browser/browserListEvents)                     | `GET /browser/v1/sessions/{sessionId}/events`            |
| [请求人工接管](/docs/api/native/browser/browserRequestHandoff)                 | `POST /browser/v1/sessions/{sessionId}/handoff`          |
| [完成人工接管](/docs/api/native/browser/browserCompleteHandoff)                | `POST /browser/v1/sessions/{sessionId}/handoff/complete` |
| [更新查看者心跳](/docs/api/native/browser/browserViewerHeartbeat)               | `POST /browser/v1/sessions/{sessionId}/viewer`           |
| [创建登录态](/docs/api/native/browser/browserCreateContext)                   | `POST /browser/v1/contexts`                              |
| [列出登录态](/docs/api/native/browser/browserListContexts)                    | `GET /browser/v1/contexts`                               |
| [读取登录态](/docs/api/native/browser/browserGetContext)                      | `GET /browser/v1/contexts/{contextId}`                   |
| [更新登录态](/docs/api/native/browser/browserUpdateContext)                   | `PUT /browser/v1/contexts/{contextId}`                   |
| [删除登录态](/docs/api/native/browser/browserDeleteContext)                   | `DELETE /browser/v1/contexts/{contextId}`                |
| [连接云端浏览器](/docs/api/native/browser/browserConnect)                       | `GET /browser/v1/connect`                                |
| [打开实时浏览器画面](/docs/api/native/browser/browserLiveView)                    | `GET /browser/v1/live/{sessionId}/{pageId}`              |
| [订阅会话动态](/docs/api/native/browser/browserStreamSession)                  | `GET /browser/v1/sessions/{sessionId}/stream`            |
| [读取 Selenium 不支持提示](/docs/api/native/browser/browserSeleniumUnsupported) | `GET /browser/v1/selenium-unsupported`                   |

# 创建浏览器会话

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 201 [#http-201]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 浏览器会话 ID；使用创建或列出会话返回的 id，以 bss_ 开头。 |
| projectId | string | 兼容项目标识，当前账户的会话固定返回 default。 |
| status | string | 会话生命周期状态；释放中的会话仍显示 RUNNING，但已不能建立新连接。 |
| keepAlive | boolean | API 创建的会话是否在客户端断开后保留；true 不因空闲释放，仍受最长寿命限制。 |
| region | string | 兼容字段，不代表可选择部署区域。 |
| proxyBytes | integer | 兼容的代理流量字节数；当前未使用代理，固定返回 0。 |
| createdAt | string | 会话创建时刻，UTC ISO 8601 时间。 |
| updatedAt | string | 会话状态最近一次更新的时刻，UTC ISO 8601 时间。 |
| startedAt | string | 浏览器开始运行的时刻；尚未开始运行时返回创建时刻，UTC ISO 8601 时间。 |
| expiresAt | string | 会话最长寿命的到期时刻，等于创建时刻加 timeout 秒，UTC ISO 8601 时间。 |
| endedAt | string | 浏览器使用区间的结束时刻，UTC ISO 8601 时间；尚未记录结束时刻时省略。 |
| contextId | string | 登录态 ID；使用创建或列出登录态返回的 id，以 bsc_ 开头。 |
| userMetadata | object | 创建会话时传入的自定义 JSON 元数据；未设置时为空对象。 |
| name | string | 会话名称；1–128 个 ASCII 字母、数字或 . _ : -，可用于筛选会话。 |
| labels | object | 自定义字符串标签；最多 32 项，键最多 128 个 UTF-8 字节，值最多 1024 个 UTF-8 字节。 |
| origin | string | 会话创建入口；api 为 API 创建，connect 为一步连接创建，console 为 Console 创建。 |
| closeReason | string | 会话释放原因；未开始释放时省略。 |
| viewport | object | 浏览器视口尺寸；创建时省略整个对象则使用宽 1280、高 800 像素。 |
| viewport.width | integer | 浏览器视口宽度，单位为像素，必须为正整数。 |
| viewport.height | integer | 浏览器视口高度，单位为像素，必须为正整数。 |
| billedSeconds | number | 会话计费时长，单位为秒；运行时随时长增长，结束后为最终计费时长，可含小数。 |
| currentUrl | string | 最近观察到的页面导航地址；尚未观察到导航时省略。 |
| clients | integer | 当前连接的 CDP 客户端数量；不包含仅观看页面的用户。 |
| handoff | object &#124; null | 待完成的人工接管请求；没有请求、已完成或已过期时为 null。 |
| handoff.message | string | 请求人工接管时提供给操作者的说明文字。 |
| handoff.requestedAt | string | 人工接管请求的发起时刻，UTC ISO 8601 时间。 |
| handoff.expiresAt | string | 人工接管请求的失效时刻，UTC ISO 8601 时间。 |
| connectUrl | string | 自带凭证的 CDP WebSocket 地址，有效期覆盖会话寿命；连接无需额外 API Key。 |
| signingKey | string | connectUrl 内的连接凭证，请勿公开。 |
| seleniumRemoteUrl | string | 该地址返回 501；不支持 Selenium。 |

# 列出浏览器会话

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | 本页查询匹配的记录；没有匹配项时为空数组。 |
| data[].id | string | 浏览器会话 ID；使用创建或列出会话返回的 id，以 bss_ 开头。 |
| data[].projectId | string | 兼容项目标识，当前账户的会话固定返回 default。 |
| data[].status | string | 会话生命周期状态；释放中的会话仍显示 RUNNING，但已不能建立新连接。 |
| data[].keepAlive | boolean | API 创建的会话是否在客户端断开后保留；true 不因空闲释放，仍受最长寿命限制。 |
| data[].region | string | 兼容字段，不代表可选择部署区域。 |
| data[].proxyBytes | integer | 兼容的代理流量字节数；当前未使用代理，固定返回 0。 |
| data[].createdAt | string | 会话创建时刻，UTC ISO 8601 时间。 |
| data[].updatedAt | string | 会话状态最近一次更新的时刻，UTC ISO 8601 时间。 |
| data[].startedAt | string | 浏览器开始运行的时刻；尚未开始运行时返回创建时刻，UTC ISO 8601 时间。 |
| data[].expiresAt | string | 会话最长寿命的到期时刻，等于创建时刻加 timeout 秒，UTC ISO 8601 时间。 |
| data[].endedAt | string | 浏览器使用区间的结束时刻，UTC ISO 8601 时间；尚未记录结束时刻时省略。 |
| data[].contextId | string | 登录态 ID；使用创建或列出登录态返回的 id，以 bsc_ 开头。 |
| data[].userMetadata | object | 创建会话时传入的自定义 JSON 元数据；未设置时为空对象。 |
| data[].name | string | 会话名称；1–128 个 ASCII 字母、数字或 . _ : -，可用于筛选会话。 |
| data[].labels | object | 自定义字符串标签；最多 32 项，键最多 128 个 UTF-8 字节，值最多 1024 个 UTF-8 字节。 |
| data[].origin | string | 会话创建入口；api 为 API 创建，connect 为一步连接创建，console 为 Console 创建。 |
| data[].closeReason | string | 会话释放原因；未开始释放时省略。 |
| data[].viewport | object | 浏览器视口尺寸；创建时省略整个对象则使用宽 1280、高 800 像素。 |
| data[].billedSeconds | number | 会话计费时长，单位为秒；运行时随时长增长，结束后为最终计费时长，可含小数。 |
| data[].currentUrl | string | 最近观察到的页面导航地址；尚未观察到导航时省略。 |
| data[].clients | integer | 当前连接的 CDP 客户端数量；不包含仅观看页面的用户。 |
| data[].handoff | object &#124; null | 待完成的人工接管请求；没有请求、已完成或已过期时为 null。 |
| nextCursor | string &#124; null | 下一页游标；原样传入 cursor，null 表示没有更多结果。 |

# 读取浏览器会话

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 浏览器会话 ID；使用创建或列出会话返回的 id，以 bss_ 开头。 |
| projectId | string | 兼容项目标识，当前账户的会话固定返回 default。 |
| status | string | 会话生命周期状态；释放中的会话仍显示 RUNNING，但已不能建立新连接。 |
| keepAlive | boolean | API 创建的会话是否在客户端断开后保留；true 不因空闲释放，仍受最长寿命限制。 |
| region | string | 兼容字段，不代表可选择部署区域。 |
| proxyBytes | integer | 兼容的代理流量字节数；当前未使用代理，固定返回 0。 |
| createdAt | string | 会话创建时刻，UTC ISO 8601 时间。 |
| updatedAt | string | 会话状态最近一次更新的时刻，UTC ISO 8601 时间。 |
| startedAt | string | 浏览器开始运行的时刻；尚未开始运行时返回创建时刻，UTC ISO 8601 时间。 |
| expiresAt | string | 会话最长寿命的到期时刻，等于创建时刻加 timeout 秒，UTC ISO 8601 时间。 |
| endedAt | string | 浏览器使用区间的结束时刻，UTC ISO 8601 时间；尚未记录结束时刻时省略。 |
| contextId | string | 登录态 ID；使用创建或列出登录态返回的 id，以 bsc_ 开头。 |
| userMetadata | object | 创建会话时传入的自定义 JSON 元数据；未设置时为空对象。 |
| name | string | 会话名称；1–128 个 ASCII 字母、数字或 . _ : -，可用于筛选会话。 |
| labels | object | 自定义字符串标签；最多 32 项，键最多 128 个 UTF-8 字节，值最多 1024 个 UTF-8 字节。 |
| origin | string | 会话创建入口；api 为 API 创建，connect 为一步连接创建，console 为 Console 创建。 |
| closeReason | string | 会话释放原因；未开始释放时省略。 |
| viewport | object | 浏览器视口尺寸；创建时省略整个对象则使用宽 1280、高 800 像素。 |
| viewport.width | integer | 浏览器视口宽度，单位为像素，必须为正整数。 |
| viewport.height | integer | 浏览器视口高度，单位为像素，必须为正整数。 |
| billedSeconds | number | 会话计费时长，单位为秒；运行时随时长增长，结束后为最终计费时长，可含小数。 |
| currentUrl | string | 最近观察到的页面导航地址；尚未观察到导航时省略。 |
| clients | integer | 当前连接的 CDP 客户端数量；不包含仅观看页面的用户。 |
| handoff | object &#124; null | 待完成的人工接管请求；没有请求、已完成或已过期时为 null。 |
| handoff.message | string | 请求人工接管时提供给操作者的说明文字。 |
| handoff.requestedAt | string | 人工接管请求的发起时刻，UTC ISO 8601 时间。 |
| handoff.expiresAt | string | 人工接管请求的失效时刻，UTC ISO 8601 时间。 |
| debug | object | 会话和标签页的实时观看地址，以及当前会话的 CDP 连接地址。 |
| debug.debuggerFullscreenUrl | string | 会话实时画面的完整跳转地址，携带观看凭证；与 debuggerUrl 相同。 |
| debug.debuggerUrl | string | 会话实时画面的完整跳转地址；直接打开，勿移除查询凭证。 |
| debug.wsUrl | string | 连接当前会话的 CDP WebSocket 地址，自带 signingKey，无需额外 API Key。 |
| debug.pages | array&lt;object&gt; | 当前浏览器标签页及各页的实时观看地址；会话不在运行状态时为空数组。 |
| events | object | expand 包含 events 时返回的会话事件首页；后续页通过事件列表读取。 |
| events.data | array&lt;object&gt; | 本页查询匹配的记录；没有匹配项时为空数组。 |
| events.nextCursor | string &#124; null | 下一页游标；原样传入 cursor，null 表示没有更多结果。 |

# 关闭浏览器会话

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 浏览器会话 ID；使用创建或列出会话返回的 id，以 bss_ 开头。 |
| projectId | string | 兼容项目标识，当前账户的会话固定返回 default。 |
| status | string | 会话生命周期状态；释放中的会话仍显示 RUNNING，但已不能建立新连接。 |
| keepAlive | boolean | API 创建的会话是否在客户端断开后保留；true 不因空闲释放，仍受最长寿命限制。 |
| region | string | 兼容字段，不代表可选择部署区域。 |
| proxyBytes | integer | 兼容的代理流量字节数；当前未使用代理，固定返回 0。 |
| createdAt | string | 会话创建时刻，UTC ISO 8601 时间。 |
| updatedAt | string | 会话状态最近一次更新的时刻，UTC ISO 8601 时间。 |
| startedAt | string | 浏览器开始运行的时刻；尚未开始运行时返回创建时刻，UTC ISO 8601 时间。 |
| expiresAt | string | 会话最长寿命的到期时刻，等于创建时刻加 timeout 秒，UTC ISO 8601 时间。 |
| endedAt | string | 浏览器使用区间的结束时刻，UTC ISO 8601 时间；尚未记录结束时刻时省略。 |
| contextId | string | 登录态 ID；使用创建或列出登录态返回的 id，以 bsc_ 开头。 |
| userMetadata | object | 创建会话时传入的自定义 JSON 元数据；未设置时为空对象。 |
| name | string | 会话名称；1–128 个 ASCII 字母、数字或 . _ : -，可用于筛选会话。 |
| labels | object | 自定义字符串标签；最多 32 项，键最多 128 个 UTF-8 字节，值最多 1024 个 UTF-8 字节。 |
| origin | string | 会话创建入口；api 为 API 创建，connect 为一步连接创建，console 为 Console 创建。 |
| closeReason | string | 会话释放原因；未开始释放时省略。 |
| viewport | object | 浏览器视口尺寸；创建时省略整个对象则使用宽 1280、高 800 像素。 |
| viewport.width | integer | 浏览器视口宽度，单位为像素，必须为正整数。 |
| viewport.height | integer | 浏览器视口高度，单位为像素，必须为正整数。 |
| billedSeconds | number | 会话计费时长，单位为秒；运行时随时长增长，结束后为最终计费时长，可含小数。 |
| currentUrl | string | 最近观察到的页面导航地址；尚未观察到导航时省略。 |
| clients | integer | 当前连接的 CDP 客户端数量；不包含仅观看页面的用户。 |
| handoff | object &#124; null | 待完成的人工接管请求；没有请求、已完成或已过期时为 null。 |
| handoff.message | string | 请求人工接管时提供给操作者的说明文字。 |
| handoff.requestedAt | string | 人工接管请求的发起时刻，UTC ISO 8601 时间。 |
| handoff.expiresAt | string | 人工接管请求的失效时刻，UTC ISO 8601 时间。 |

# 读取调试地址

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| debuggerFullscreenUrl | string | 会话实时画面的完整跳转地址，携带观看凭证；与 debuggerUrl 相同。 |
| debuggerUrl | string | 会话实时画面的完整跳转地址；直接打开，勿移除查询凭证。 |
| wsUrl | string | 连接当前会话的 CDP WebSocket 地址，自带 signingKey，无需额外 API Key。 |
| pages | array&lt;object&gt; | 当前浏览器标签页及各页的实时观看地址；会话不在运行状态时为空数组。 |
| pages[].id | string | 浏览器标签页的目标 ID，可用于实时画面地址中的 pageId。 |
| pages[].url | string | 该浏览器标签页当前报告的页面地址。 |
| pages[].title | string | 该浏览器标签页当前报告的页面标题。 |
| pages[].faviconUrl | string | 兼容的页面图标地址字段，当前固定返回空字符串。 |
| pages[].debuggerUrl | string | 此标签页实时画面的完整跳转地址，包含观看凭证。 |
| pages[].debuggerFullscreenUrl | string | 此标签页实时画面的完整跳转地址，与该页 debuggerUrl 相同。 |

# 列出会话事件

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | 本页查询匹配的记录；没有匹配项时为空数组。 |
| data[].seq | integer | 当前会话内递增的事件序号，用于事件排序及分页。 |
| data[].id | string | 服务生成的事件唯一标识，使用 UUID 格式。 |
| data[].type | string | 会话账本中的事件类型，用于区分状态变化和会话操作。 |
| data[].processed_at | string | 事件记录时刻，UTC ISO 8601 时间。 |
| data[].session_id | string | 浏览器会话 ID；使用创建或列出会话返回的 id，以 bss_ 开头。 |
| data[].reason | string | 事件发生原因；关闭相关事件记录对应的会话释放原因。 |
| data[].payload | object | 事件附加数据，内容取决于事件类型；没有附加数据时省略。 |
| nextCursor | string &#124; null | 下一页游标；原样传入 cursor，null 表示没有更多结果。 |

# 请求人工接管

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| seq | integer | 当前会话内递增的事件序号，用于事件排序及分页。 |
| id | string | 服务生成的事件唯一标识，使用 UUID 格式。 |
| type | string | 会话账本中的事件类型，用于区分状态变化和会话操作。 |
| processed_at | string | 事件记录时刻，UTC ISO 8601 时间。 |
| session_id | string | 浏览器会话 ID；使用创建或列出会话返回的 id，以 bss_ 开头。 |
| reason | string | 事件发生原因；关闭相关事件记录对应的会话释放原因。 |
| payload | object | 事件附加数据，内容取决于事件类型；没有附加数据时省略。 |

# 完成人工接管

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| seq | integer | 当前会话内递增的事件序号，用于事件排序及分页。 |
| id | string | 服务生成的事件唯一标识，使用 UUID 格式。 |
| type | string | 会话账本中的事件类型，用于区分状态变化和会话操作。 |
| processed_at | string | 事件记录时刻，UTC ISO 8601 时间。 |
| session_id | string | 浏览器会话 ID；使用创建或列出会话返回的 id，以 bss_ 开头。 |
| reason | string | 事件发生原因；关闭相关事件记录对应的会话释放原因。 |
| payload | object | 事件附加数据，内容取决于事件类型；没有附加数据时省略。 |

# 更新查看者心跳

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| ok | boolean | 心跳已被接受，成功时固定返回 true。 |

# 创建登录态

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 201 [#http-201]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 登录态 ID；使用创建或列出登录态返回的 id，以 bsc_ 开头。 |
| projectId | string | 兼容项目标识，当前账户的登录态固定返回 default。 |
| createdAt | string | 登录态创建时刻，UTC ISO 8601 时间。 |
| updatedAt | string | 登录态名称、标签或保存内容最近一次更新的时刻，UTC ISO 8601 时间。 |
| name | string | 登录态名称；非空时为 1–128 个 ASCII 字母、数字或 . _ : -，在当前账户内唯一；空字符串表示不设名称或清除名称。 |
| labels | object | 自定义字符串标签；最多 32 项，键最多 128 个 UTF-8 字节，值最多 1024 个 UTF-8 字节。 |
| sites | array&lt;string&gt; | 已保存的 localStorage 主机名和 cookie 域名，去掉 cookie 域名前导点后去重排序。 |
| cookieCount | integer | 登录态中已保存的 cookie 条目数量；新登录态为 0。 |
| bytes | integer | 登录态加密后保存内容的大小，单位为 UTF-8 字节。 |
| lockedBy | string | 当前登录态写入租约的持有者标识；无有效租约时省略。 |
| lastUsedAt | string |  |
| publicKey | string |  |
| cipherAlgorithm | string |  |
| initializationVectorSize | integer |  |

# 列出登录态

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | 本页查询匹配的记录；没有匹配项时为空数组。 |
| data[].id | string | 登录态 ID；使用创建或列出登录态返回的 id，以 bsc_ 开头。 |
| data[].projectId | string | 兼容项目标识，当前账户的登录态固定返回 default。 |
| data[].createdAt | string | 登录态创建时刻，UTC ISO 8601 时间。 |
| data[].updatedAt | string | 登录态名称、标签或保存内容最近一次更新的时刻，UTC ISO 8601 时间。 |
| data[].name | string | 登录态名称；非空时为 1–128 个 ASCII 字母、数字或 . _ : -，在当前账户内唯一；空字符串表示不设名称或清除名称。 |
| data[].labels | object | 自定义字符串标签；最多 32 项，键最多 128 个 UTF-8 字节，值最多 1024 个 UTF-8 字节。 |
| data[].sites | array&lt;string&gt; | 已保存的 localStorage 主机名和 cookie 域名，去掉 cookie 域名前导点后去重排序。 |
| data[].cookieCount | integer | 登录态中已保存的 cookie 条目数量；新登录态为 0。 |
| data[].bytes | integer | 登录态加密后保存内容的大小，单位为 UTF-8 字节。 |
| data[].lockedBy | string | 当前登录态写入租约的持有者标识；无有效租约时省略。 |
| data[].lastUsedAt | string |  |
| nextCursor | string &#124; null | 下一页游标；原样传入 cursor，null 表示没有更多结果。 |

# 读取登录态

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 登录态 ID；使用创建或列出登录态返回的 id，以 bsc_ 开头。 |
| projectId | string | 兼容项目标识，当前账户的登录态固定返回 default。 |
| createdAt | string | 登录态创建时刻，UTC ISO 8601 时间。 |
| updatedAt | string | 登录态名称、标签或保存内容最近一次更新的时刻，UTC ISO 8601 时间。 |
| name | string | 登录态名称；非空时为 1–128 个 ASCII 字母、数字或 . _ : -，在当前账户内唯一；空字符串表示不设名称或清除名称。 |
| labels | object | 自定义字符串标签；最多 32 项，键最多 128 个 UTF-8 字节，值最多 1024 个 UTF-8 字节。 |
| sites | array&lt;string&gt; | 已保存的 localStorage 主机名和 cookie 域名，去掉 cookie 域名前导点后去重排序。 |
| cookieCount | integer | 登录态中已保存的 cookie 条目数量；新登录态为 0。 |
| bytes | integer | 登录态加密后保存内容的大小，单位为 UTF-8 字节。 |
| lockedBy | string | 当前登录态写入租约的持有者标识；无有效租约时省略。 |
| lastUsedAt | string |  |

# 更新登录态

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 登录态 ID；使用创建或列出登录态返回的 id，以 bsc_ 开头。 |
| projectId | string | 兼容项目标识，当前账户的登录态固定返回 default。 |
| createdAt | string | 登录态创建时刻，UTC ISO 8601 时间。 |
| updatedAt | string | 登录态名称、标签或保存内容最近一次更新的时刻，UTC ISO 8601 时间。 |
| name | string | 登录态名称；非空时为 1–128 个 ASCII 字母、数字或 . _ : -，在当前账户内唯一；空字符串表示不设名称或清除名称。 |
| labels | object | 自定义字符串标签；最多 32 项，键最多 128 个 UTF-8 字节，值最多 1024 个 UTF-8 字节。 |
| sites | array&lt;string&gt; | 已保存的 localStorage 主机名和 cookie 域名，去掉 cookie 域名前导点后去重排序。 |
| cookieCount | integer | 登录态中已保存的 cookie 条目数量；新登录态为 0。 |
| bytes | integer | 登录态加密后保存内容的大小，单位为 UTF-8 字节。 |
| lockedBy | string | 当前登录态写入租约的持有者标识；无有效租约时省略。 |
| lastUsedAt | string |  |

# 删除登录态

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

请求成功。

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| deleted | boolean | 登录态及保存内容已删除，成功时固定返回 true。 |

# 连接云端浏览器

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

此端点没有声明成功响应。

# 打开实时浏览器画面

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

此端点没有声明成功响应。

# 订阅会话动态

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

### HTTP 200 [#http-200]

持续推送会话状态。

**text/event-stream — chunk / 事件对象**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string | event: &lt;事件名&gt;\ndata: &lt;JSON&gt;\n\n |

# 

[连接与使用指南](/docs/cloud/services/browser)

## 响应 [#响应]

此端点没有声明成功响应。

# 文件 API

（待译）

File stores uploads for conversations and knowledge bases, with metadata, downloads and deletion. Concepts and behavior follow OpenAI Files (multipart uploads, purposes and file IDs), so OpenAI Files experience applies. Differences: uploads are limited to 104857600 bytes; only user\_data, assistants and vision purposes are accepted, and conversation images require user\_data; praxis\[expires\_in\_seconds] allows expiry up to 90 days, while expires\_after allows up to 30 days. Start with `praxis.file.files.create` to upload bytes and obtain a reusable file ID.

## 基础地址 [#基础地址]

## 接入 [#接入]

单文件上限 100 MB（104857600 字节），上传与下载全程流式。不提供 Uploads 分片。文件按内容识别类型；支持格式见上传端点。组织之间的文件互不可见。

## 端点 [#端点]

| 方法     | 路径                                                                         | 说明   | 支持     |
| ------ | -------------------------------------------------------------------------- | ---- | ------ |
| POST   | [`/v1/files`](/docs/api/native/file/createFile)                            | 上传文件 | ◐ 部分支持 |
| GET    | [`/v1/files`](/docs/api/native/file/listFiles)                             | 列出文件 | ● 支持   |
| GET    | [`/v1/files/{file_id}`](/docs/api/native/file/retrieveFile)                | 查看文件 | ● 支持   |
| GET    | [`/v1/files/{file_id}/content`](/docs/api/native/file/retrieveFileContent) | 下载文件 | ● 支持   |
| DELETE | [`/v1/files/{file_id}`](/docs/api/native/file/deleteFile)                  | 删除文件 | ● 支持   |

## 与官方的差异 [#与官方的差异]

* 沿用 OpenAI 的文件和分页形状，增加 mime\_type、downloadable，以及 before 查询游标。仅自有面支持请求体 praxis.expires\_in\_seconds（3600–7776000 秒），不可与 expires\_after 同时使用；multipart 编码为 praxis\[expires\_in\_seconds]。
* <a href="/docs/api/native/file/createFile">上传文件</a>：支持 PDF、DOCX / XLSX / PPTX、PNG / JPEG / GIF / WebP、MP3 / WAV / FLAC / OGG / M4A、MP4 / WebM，以及 UTF-8 JSON / NDJSON / CSV / Markdown / 纯文本。purpose 支持 user\_data / assistants / vision。上限 104857600 字节；空文件、类型不支持、用途不支持、超限均返回 400。不提供 Uploads 分片。可用 expires\_after\[anchor] 与 expires\_after\[seconds] 或 praxis\[expires\_in\_seconds] 设置有效期，两组互斥。

参数与字段的权威定义以 [OpenAI 官方文档](https://platform.openai.com/docs/api-reference)为准。

错误按 OpenAI 格式返回，参见[错误](/docs/api/errors)；额度与响应头参见[限流](/docs/api/rate-limits)。

# 

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | File identifier: file_dp_ followed by a 26-character uppercase Crockford ULID. Use the ID returned by upload or list. |
| bytes | integer | The size of the file, in bytes. |
| created_at | integer | The Unix timestamp (in seconds) for when the file was created. |
| expires_at | integer | The Unix timestamp (in seconds) for when the file will expire. |
| filename | string | The name of the file. |
| object | string | The object type, which is always &#96;file&#96;. |
| purpose | string | Upload purpose. Image references in conversations require user_data. |
| status | string | Deprecated. The current status of the file, which can be either &#96;uploaded&#96;, &#96;processed&#96;, or &#96;error&#96;. |
| status_details | string &#124; null | Deprecated; always null or absent. |
| mime_type | string | Content-detected MIME type. |
| downloadable | boolean | Tenant-owned live files can be downloaded through this face. |
| scope | object | Present for session output files. |
| scope.type | string | Kind of scope; always &#96;session&#96;. |
| scope.id | string | Id of the session the file belongs to. |
| relative_path | string | Path within the session output directory; present for session outputs. |
| revision | integer | Session output revision; present for session outputs. |

# 列出文件

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| object | string | Object type; always &#96;list&#96;. |
| data | array&lt;object&gt; | Files of the page, in the requested order. |
| data[].id | string | File identifier: file_dp_ followed by a 26-character uppercase Crockford ULID. Use the ID returned by upload or list. |
| data[].bytes | integer | The size of the file, in bytes. |
| data[].created_at | integer | The Unix timestamp (in seconds) for when the file was created. |
| data[].expires_at | integer | The Unix timestamp (in seconds) for when the file will expire. |
| data[].filename | string | The name of the file. |
| data[].object | string | The object type, which is always &#96;file&#96;. |
| data[].purpose | string | Upload purpose. Image references in conversations require user_data. |
| data[].status | string | Deprecated. The current status of the file, which can be either &#96;uploaded&#96;, &#96;processed&#96;, or &#96;error&#96;. |
| data[].status_details | string &#124; null | Deprecated; always null or absent. |
| data[].mime_type | string | Content-detected MIME type. |
| data[].downloadable | boolean | Tenant-owned live files can be downloaded through this face. |
| data[].scope | object | Present for session output files. |
| data[].relative_path | string | Path within the session output directory; present for session outputs. |
| data[].revision | integer | Session output revision; present for session outputs. |
| first_id | string | Id of the first file of the page; usable as &#96;before&#96; to read the preceding page. |
| last_id | string | Id of the last file of the page; usable as &#96;after&#96; to read the next page. |
| has_more | boolean | Whether more files exist beyond this page. |

# 查看文件

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | File identifier: file_dp_ followed by a 26-character uppercase Crockford ULID. Use the ID returned by upload or list. |
| bytes | integer | The size of the file, in bytes. |
| created_at | integer | The Unix timestamp (in seconds) for when the file was created. |
| expires_at | integer | The Unix timestamp (in seconds) for when the file will expire. |
| filename | string | The name of the file. |
| object | string | The object type, which is always &#96;file&#96;. |
| purpose | string | Upload purpose. Image references in conversations require user_data. |
| status | string | Deprecated. The current status of the file, which can be either &#96;uploaded&#96;, &#96;processed&#96;, or &#96;error&#96;. |
| status_details | string &#124; null | Deprecated; always null or absent. |
| mime_type | string | Content-detected MIME type. |
| downloadable | boolean | Tenant-owned live files can be downloaded through this face. |
| scope | object | Present for session output files. |
| scope.type | string | Kind of scope; always &#96;session&#96;. |
| scope.id | string | Id of the session the file belongs to. |
| relative_path | string | Path within the session output directory; present for session outputs. |
| revision | integer | Session output revision; present for session outputs. |

# 下载文件

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/octet-stream**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| $ | string (binary) |  |

# 删除文件

先调用「上传文件」，用返回的文件 ID 替换示例文件 ID。

## 响应 [#响应]

### HTTP 200 [#http-200]

OK

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | File identifier: file_dp_ followed by a 26-character uppercase Crockford ULID. Use the ID returned by upload or list. |
| object | string | Object type; always &#96;file&#96;. |
| deleted | boolean | Always true; the file can no longer be read, though downloads already authorized may finish. |

# Media API

使用 API Key 作为 Bearer 凭据访问素材库。

`https://api.deepraxis.ai/media/v1`

[指南 →](/docs/cloud/services/media/quickstart)

| 资源 | 参考 |
| --- | --- |
| 素材库 | [素材库](/docs/api/native/media/libraries) |
| 素材 | [素材](/docs/api/native/media/assets) |
| 理解结果 | [理解结果](/docs/api/native/media/understandings) |
| 检索 | [检索](/docs/api/native/media/search) |
| 文件夹 | [文件夹](/docs/api/native/media/folders) |
| 批量操作 | [批量操作](/docs/api/native/media/batches) |
| 事件 | [事件](/docs/api/native/media/events) |

[错误码](/docs/api/native/media/errors)

# 素材库

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/native/media)

## 创建库 [#创建库]

`POST /media/v1/libraries`

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| models | MediaModelsInput | 否 | 各角色的模型调用 ID；局部更新，null 恢复默认 |
| name | string | 是 | 名称，1–64 个字符；允许重名 |
| labels | object | 否 | 标签对象；GET 时传 JSON 字符串；PATCH 整体替换，传 &#123;&#125; 清空 |
| understanding | object | 否 | 视觉、转写与语义理解开关 |

返回: `Library`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| search | object | Search capabilities of this library’s embedding model. |
| search.image | boolean | Whether this library’s embedding model supports image-based visual search. |
| models | object | Resolved model call IDs used for new uploads and reprocessing. |
| models.vision | string | Model call ID for visual descriptions; the model must support image input. |
| models.embedding | string | Model call ID for search embeddings; must produce compatible vectors and cannot change while assets exist. |
| models.transcription | string | Model call ID for speech transcription. |
| id | string | Generated library identifier: lib_ followed by 32 lowercase hexadecimal characters. |
| name | string | Display name of the library; duplicate names are allowed. |
| labels | object | Caller-defined string labels used to organize and filter libraries. |
| status | string | Library lifecycle: provisioning initializes the library; active permits asset operations; deleting awaits purge and may be restored before purge_at; deleted has been purged; failed indicates initialization failure. |
| asset_count | number | Number of assets currently stored in the library. |
| bytes | number | Total source-content size of the library’s assets, in bytes. |
| understanding | object | Settings controlling understanding tasks for new uploads. |
| understanding.visual | boolean | Enable captions, tags and OCR for images and video frames. |
| understanding.transcript | boolean | Enable speech transcription for audio and video soundtracks. |
| understanding.embedding | boolean | Enable generation of vectors for semantic search. |
| created_at | string | Time the library was created, in UTC. |
| updated_at | string | Time library settings, lifecycle or usage were last updated, in UTC. |
| deleted_at | string &#124; null | Time the library entered deleting, or null when active or restored. |
| purge_at | string &#124; null | Scheduled purge time while the library is deleting; null for an active or restored library. |

```bash
curl -X POST "https://api.deepraxis.ai/media/v1/libraries" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"name":"walk-lib-r1-MDP-1791733789929","labels":{"sample":"walk-lib-r1-MDP-1791733789929"}}'
```

HTTP 200

```json
{
  "id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "name": "walk-lib-r1-MDP-1791733789929",
  "labels": {
    "sample": "walk-lib-r1-MDP-1791733789929"
  },
  "status": "active",
  "asset_count": 0,
  "bytes": 0,
  "models": {
    "vision": "qwen3.8-flash",
    "embedding": "qwen3-vl-embedding",
    "transcription": "whisper-large-v3-turbo"
  },
  "search": {
    "image": true
  },
  "understanding": {
    "visual": true,
    "transcript": true,
    "embedding": true
  },
  "created_at": "2026-10-11T15:50:04.230Z",
  "updated_at": "2026-10-11T15:50:04.931Z",
  "deleted_at": null,
  "purge_at": null
}
```

## 列出库 [#列出库]

`GET /media/v1/libraries`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| cursor | query | string | 上一页的 next_cursor |
| limit | query | integer | 每页 1–200 条，默认 50 |
| labels | query | string | 标签对象；GET 时传 JSON 字符串；PATCH 整体替换，传 &#123;&#125; 清空 |
| status | query | active / deleting | 资源状态 |

返回: `LibraryPage`.

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Libraries in this page, ordered by creation time descending. |
| data[].search | object | Search capabilities of this library’s embedding model. |
| data[].models | object | Resolved model call IDs used for new uploads and reprocessing. |
| data[].id | string | Generated library identifier: lib_ followed by 32 lowercase hexadecimal characters. |
| data[].name | string | Display name of the library; duplicate names are allowed. |
| data[].labels | object | Caller-defined string labels used to organize and filter libraries. |
| data[].status | string | Library lifecycle: provisioning initializes the library; active permits asset operations; deleting awaits purge and may be restored before purge_at; deleted has been purged; failed indicates initialization failure. |
| data[].asset_count | number | Number of assets currently stored in the library. |
| data[].bytes | number | Total source-content size of the library’s assets, in bytes. |
| data[].understanding | object | Settings controlling understanding tasks for new uploads. |
| data[].created_at | string | Time the library was created, in UTC. |
| data[].updated_at | string | Time library settings, lifecycle or usage were last updated, in UTC. |
| data[].deleted_at | string &#124; null | Time the library entered deleting, or null when active or restored. |
| data[].purge_at | string &#124; null | Scheduled purge time while the library is deleting; null for an active or restored library. |
| next_cursor | string &#124; null | Opaque token to pass as cursor to listLibraries; null means no further page. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries?labels=%7B%22sample%22%3A%22walk-lib-r1-MDP-1791733789929%22%7D" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "data": [
    {
      "id": "lib_d3881a2f54a34cd79121b9d659e8378c",
      "name": "walk-lib-r1-MDP-1791733789929",
      "status": "active",
      "asset_count": 0,
      "bytes": 0,
      "created_at": "2026-10-11T15:50:04.230Z",
      "updated_at": "2026-10-11T15:50:04.931Z",
      "deleted_at": null,
      "purge_at": null,
      "search": {
        "image": true
      },
      "models": {
        "vision": "qwen3.8-flash",
        "embedding": "qwen3-vl-embedding",
        "transcription": "whisper-large-v3-turbo"
      },
      "labels": {
        "sample": "walk-lib-r1-MDP-1791733789929"
      },
      "understanding": {
        "visual": true,
        "transcript": true,
        "embedding": true
      }
    }
  ],
  "next_cursor": null
}
```

## 读取库 [#读取库]

`GET /media/v1/libraries/{library_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

返回: `Library`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| search | object | Search capabilities of this library’s embedding model. |
| search.image | boolean | Whether this library’s embedding model supports image-based visual search. |
| models | object | Resolved model call IDs used for new uploads and reprocessing. |
| models.vision | string | Model call ID for visual descriptions; the model must support image input. |
| models.embedding | string | Model call ID for search embeddings; must produce compatible vectors and cannot change while assets exist. |
| models.transcription | string | Model call ID for speech transcription. |
| id | string | Generated library identifier: lib_ followed by 32 lowercase hexadecimal characters. |
| name | string | Display name of the library; duplicate names are allowed. |
| labels | object | Caller-defined string labels used to organize and filter libraries. |
| status | string | Library lifecycle: provisioning initializes the library; active permits asset operations; deleting awaits purge and may be restored before purge_at; deleted has been purged; failed indicates initialization failure. |
| asset_count | number | Number of assets currently stored in the library. |
| bytes | number | Total source-content size of the library’s assets, in bytes. |
| understanding | object | Settings controlling understanding tasks for new uploads. |
| understanding.visual | boolean | Enable captions, tags and OCR for images and video frames. |
| understanding.transcript | boolean | Enable speech transcription for audio and video soundtracks. |
| understanding.embedding | boolean | Enable generation of vectors for semantic search. |
| created_at | string | Time the library was created, in UTC. |
| updated_at | string | Time library settings, lifecycle or usage were last updated, in UTC. |
| deleted_at | string &#124; null | Time the library entered deleting, or null when active or restored. |
| purge_at | string &#124; null | Scheduled purge time while the library is deleting; null for an active or restored library. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "name": "walk-lib-r1-MDP-1791733789929",
  "status": "active",
  "asset_count": 0,
  "bytes": 0,
  "created_at": "2026-10-11T15:50:04.230Z",
  "updated_at": "2026-10-11T15:50:04.931Z",
  "deleted_at": null,
  "purge_at": null,
  "search": {
    "image": true
  },
  "models": {
    "vision": "qwen3.8-flash",
    "embedding": "qwen3-vl-embedding",
    "transcription": "whisper-large-v3-turbo"
  },
  "labels": {
    "sample": "walk-lib-r1-MDP-1791733789929"
  },
  "understanding": {
    "visual": true,
    "transcript": true,
    "embedding": true
  }
}
```

## 更新库 [#更新库]

`PATCH /media/v1/libraries/{library_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| models | MediaModelsInput | 否 | 各角色的模型调用 ID；局部更新，null 恢复默认 |
| name | string | 否 | 名称，1–64 个字符；允许重名 |
| labels | object | 否 | 标签对象；GET 时传 JSON 字符串；PATCH 整体替换，传 &#123;&#125; 清空 |
| understanding | object | 否 | 视觉、转写与语义理解开关 |

返回: `Library`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| search | object | Search capabilities of this library’s embedding model. |
| search.image | boolean | Whether this library’s embedding model supports image-based visual search. |
| models | object | Resolved model call IDs used for new uploads and reprocessing. |
| models.vision | string | Model call ID for visual descriptions; the model must support image input. |
| models.embedding | string | Model call ID for search embeddings; must produce compatible vectors and cannot change while assets exist. |
| models.transcription | string | Model call ID for speech transcription. |
| id | string | Generated library identifier: lib_ followed by 32 lowercase hexadecimal characters. |
| name | string | Display name of the library; duplicate names are allowed. |
| labels | object | Caller-defined string labels used to organize and filter libraries. |
| status | string | Library lifecycle: provisioning initializes the library; active permits asset operations; deleting awaits purge and may be restored before purge_at; deleted has been purged; failed indicates initialization failure. |
| asset_count | number | Number of assets currently stored in the library. |
| bytes | number | Total source-content size of the library’s assets, in bytes. |
| understanding | object | Settings controlling understanding tasks for new uploads. |
| understanding.visual | boolean | Enable captions, tags and OCR for images and video frames. |
| understanding.transcript | boolean | Enable speech transcription for audio and video soundtracks. |
| understanding.embedding | boolean | Enable generation of vectors for semantic search. |
| created_at | string | Time the library was created, in UTC. |
| updated_at | string | Time library settings, lifecycle or usage were last updated, in UTC. |
| deleted_at | string &#124; null | Time the library entered deleting, or null when active or restored. |
| purge_at | string &#124; null | Scheduled purge time while the library is deleting; null for an active or restored library. |

```bash
curl -X PATCH "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"name":"walk-lib-r1-MDP-1791733789929-updated"}'
```

HTTP 200

```json
{
  "id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "name": "walk-lib-r1-MDP-1791733789929-updated",
  "status": "active",
  "asset_count": 0,
  "bytes": 0,
  "created_at": "2026-10-11T15:50:04.230Z",
  "updated_at": "2026-10-11T15:50:07.147Z",
  "deleted_at": null,
  "purge_at": null,
  "search": {
    "image": true
  },
  "models": {
    "vision": "qwen3.8-flash",
    "embedding": "qwen3-vl-embedding",
    "transcription": "whisper-large-v3-turbo"
  },
  "labels": {
    "sample": "walk-lib-r1-MDP-1791733789929"
  },
  "understanding": {
    "visual": true,
    "transcript": true,
    "embedding": true
  }
}
```

## 删除库 [#删除库]

`DELETE /media/v1/libraries/{library_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

返回: `Library`.

### 响应 [#响应-4]

#### HTTP 200 [#http-200-4]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| search | object | Search capabilities of this library’s embedding model. |
| search.image | boolean | Whether this library’s embedding model supports image-based visual search. |
| models | object | Resolved model call IDs used for new uploads and reprocessing. |
| models.vision | string | Model call ID for visual descriptions; the model must support image input. |
| models.embedding | string | Model call ID for search embeddings; must produce compatible vectors and cannot change while assets exist. |
| models.transcription | string | Model call ID for speech transcription. |
| id | string | Generated library identifier: lib_ followed by 32 lowercase hexadecimal characters. |
| name | string | Display name of the library; duplicate names are allowed. |
| labels | object | Caller-defined string labels used to organize and filter libraries. |
| status | string | Library lifecycle: provisioning initializes the library; active permits asset operations; deleting awaits purge and may be restored before purge_at; deleted has been purged; failed indicates initialization failure. |
| asset_count | number | Number of assets currently stored in the library. |
| bytes | number | Total source-content size of the library’s assets, in bytes. |
| understanding | object | Settings controlling understanding tasks for new uploads. |
| understanding.visual | boolean | Enable captions, tags and OCR for images and video frames. |
| understanding.transcript | boolean | Enable speech transcription for audio and video soundtracks. |
| understanding.embedding | boolean | Enable generation of vectors for semantic search. |
| created_at | string | Time the library was created, in UTC. |
| updated_at | string | Time library settings, lifecycle or usage were last updated, in UTC. |
| deleted_at | string &#124; null | Time the library entered deleting, or null when active or restored. |
| purge_at | string &#124; null | Scheduled purge time while the library is deleting; null for an active or restored library. |

```bash
curl -X DELETE "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "name": "walk-lib-r1-MDP-1791733789929-updated",
  "status": "deleting",
  "asset_count": 2,
  "bytes": 140,
  "created_at": "2026-10-11T15:50:04.230Z",
  "updated_at": "2026-10-11T15:50:30.664Z",
  "deleted_at": "2026-10-11T15:50:30.664Z",
  "purge_at": "2026-10-18T15:50:30.664Z",
  "search": {
    "image": true
  },
  "models": {
    "vision": "qwen3.8-flash",
    "embedding": "qwen3-vl-embedding",
    "transcription": "whisper-large-v3-turbo"
  },
  "labels": {
    "sample": "walk-lib-r1-MDP-1791733789929"
  },
  "understanding": {
    "visual": true,
    "transcript": true,
    "embedding": true
  }
}
```

## 恢复库 [#恢复库]

`POST /media/v1/libraries/{library_id}/restore`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

返回: `Library`.

### 响应 [#响应-5]

#### HTTP 200 [#http-200-5]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| search | object | Search capabilities of this library’s embedding model. |
| search.image | boolean | Whether this library’s embedding model supports image-based visual search. |
| models | object | Resolved model call IDs used for new uploads and reprocessing. |
| models.vision | string | Model call ID for visual descriptions; the model must support image input. |
| models.embedding | string | Model call ID for search embeddings; must produce compatible vectors and cannot change while assets exist. |
| models.transcription | string | Model call ID for speech transcription. |
| id | string | Generated library identifier: lib_ followed by 32 lowercase hexadecimal characters. |
| name | string | Display name of the library; duplicate names are allowed. |
| labels | object | Caller-defined string labels used to organize and filter libraries. |
| status | string | Library lifecycle: provisioning initializes the library; active permits asset operations; deleting awaits purge and may be restored before purge_at; deleted has been purged; failed indicates initialization failure. |
| asset_count | number | Number of assets currently stored in the library. |
| bytes | number | Total source-content size of the library’s assets, in bytes. |
| understanding | object | Settings controlling understanding tasks for new uploads. |
| understanding.visual | boolean | Enable captions, tags and OCR for images and video frames. |
| understanding.transcript | boolean | Enable speech transcription for audio and video soundtracks. |
| understanding.embedding | boolean | Enable generation of vectors for semantic search. |
| created_at | string | Time the library was created, in UTC. |
| updated_at | string | Time library settings, lifecycle or usage were last updated, in UTC. |
| deleted_at | string &#124; null | Time the library entered deleting, or null when active or restored. |
| purge_at | string &#124; null | Scheduled purge time while the library is deleting; null for an active or restored library. |

```bash
curl -X POST "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/restore" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{}'
```

HTTP 200

```json
{
  "id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "name": "walk-lib-r1-MDP-1791733789929-updated",
  "status": "active",
  "asset_count": 2,
  "bytes": 140,
  "created_at": "2026-10-11T15:50:04.230Z",
  "updated_at": "2026-10-11T15:50:31.379Z",
  "deleted_at": null,
  "purge_at": null,
  "search": {
    "image": true
  },
  "models": {
    "vision": "qwen3.8-flash",
    "embedding": "qwen3-vl-embedding",
    "transcription": "whisper-large-v3-turbo"
  },
  "labels": {
    "sample": "walk-lib-r1-MDP-1791733789929"
  },
  "understanding": {
    "visual": true,
    "transcript": true,
    "embedding": true
  }
}
```

## 立即清除库 [#立即清除库]

`POST /media/v1/libraries/{library_id}/purge`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

返回: `PurgedLibrary`.

### 响应 [#响应-6]

#### HTTP 200 [#http-200-6]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Identifier of the library that was permanently purged. |
| object | string | Resource discriminator identifying a library receipt. |
| purged | boolean | True when permanent library cleanup has completed. |

```bash
curl -X POST "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/purge" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{}'
```

HTTP 200

```json
{
  "id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "object": "library",
  "purged": true
}
```

## Library [#library]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| search | object | 是 | 检索能力；search.image 为 true 时支持以图搜图 |
| models | MediaModels | 是 | 各角色的模型调用 ID；局部更新，null 恢复默认 |
| id | LibraryId | 是 | 资源 ID |
| name | string | 是 | 名称，1–64 个字符；允许重名 |
| labels | object | 是 | 标签对象；GET 时传 JSON 字符串；PATCH 整体替换，传 &#123;&#125; 清空 |
| status | LibraryStatus | 是 | 资源状态 |
| asset_count | number | 是 | 素材数量 |
| bytes | number | 是 | 文件字节数 |
| understanding | UnderstandingSettings | 是 | 视觉、转写与语义理解开关 |
| created_at | IsoTimestamp | 是 | 创建时间 |
| updated_at | IsoTimestamp | 是 | 更新时间 |
| deleted_at | IsoTimestamp / null | 是 | 删除时间；未删除为 null |
| purge_at | IsoTimestamp / null | 是 | 恢复截止时间 |

## LibraryPage [#librarypage]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | Library[] | 是 | 本页结果 |
| next_cursor | string / null | 是 | 下一页游标；没有时为 null 或省略 |

## PurgedLibrary [#purgedlibrary]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | LibraryId | 是 | 资源 ID |
| object | "library" | 是 | — |
| purged | true | 是 | — |

## Page [#page]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | JSON[] | 是 | 本页结果 |
| next_cursor | string / null | 是 | 下一页游标；没有时为 null 或省略 |

## UnderstandingSettings [#understandingsettings]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| visual | boolean | 是 | 视觉理解开关 |
| transcript | boolean | 是 | 转写开关 |
| embedding | boolean | 是 | 语义理解开关 |

## 模型角色 [#模型角色]

`models` 指定三个角色使用的模型调用 ID（callModelId）。创建库时省略它会使用下表默认值；更新时只改传入的角色，未传的角色保持不变。某个角色传 `null` 恢复该角色默认值，`models: null` 恢复全部默认值。

| 角色 | 用途 | 默认值 |
| --- | --- | --- |
| vision | 图片与视频帧的视觉理解 | `qwen3.8-flash` |
| embedding | 将内容和检索查询生成向量，用于语义检索 | `qwen3-vl-embedding` |
| transcription | 音频转写 | `whisper-large-v3-turbo` |

写入时查询模型目录，校验传入的模型调用 ID。模型不存在返回 400 `INVALID_PARAMS`，消息为 `Model <id> is not available`；目录查询失败返回 502 `UPSTREAM_FAILED`。vision 必须支持图片输入，否则返回 400 `INVALID_PARAMS`。未知角色、空白 ID 或不合法的值也返回 400。

库中已有素材时不能更换 embedding，返回 409 `LIBRARY_INVALID_STATE`，消息为「库中已有素材时不能更换嵌入模型」。同一个向量空间必须由同一个模型生成，才能比较已有素材与查询向量；恢复默认值如果改变了 embedding，也受此限制。

修改 vision 或 transcription 只对新上传或重新处理（reprocess）的素材生效，不会自动重跑已有素材。reprocess 不带 kinds 时只重试失败项；显式指定 kinds 时，会强制重跑所选的已成功、失败或不支持项并替换结果。例如，修改 vision 后传入 `{ kinds: ["visual"] }`，修改 transcription 后传入 `{ kinds: ["transcript"] }`。

以下 PATCH 只将 vision 恢复默认，保留其他角色：

```bash
curl -X PATCH "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"models":{"vision":null}}'
```

新建库默认使用 qwen3-vl-embedding，支持以图搜图；旧库保留 bge-m3。只读字段 `search.image` 表示当前库是否支持以图搜图。选择其他模型时，会验证它能否输出 1024 维向量；无法输出则返回 INVALID\_PARAMS，探测不可用或缺少调用者身份返回 UPSTREAM\_FAILED。

# 素材

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/native/media)

## 列出素材 [#列出素材]

`GET /media/v1/libraries/{library_id}/assets`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| asset_folder | query | string | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| resource_type | query | image / video / raw | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| cursor | query | string | 上一页的 next_cursor |
| limit | query | integer | 每页 1–200 条，默认 50 |

返回: `AssetPage`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Assets in this page, ordered by creation time descending. |
| data[].asset_id | string | Generated asset identifier: 32 lowercase hexadecimal characters, preserved across overwrites. |
| data[].public_id | string | Delivery identifier unique within this library, used in asset URLs. |
| data[].display_name | string | Human-readable asset name, independent of its delivery identifier. |
| data[].asset_folder | string | Organizational folder path; the empty string denotes the root folder. |
| data[].resource_type | string | Stored media category: image for images, video for video or audio, and raw for other files. Upload also accepts auto for detection. |
| data[].type | string | Public asset delivery mode; upload is the only supported value. |
| data[].format | string | Detected file format used as the delivery URL extension. |
| data[].version | number | Monotonically increasing asset version used in delivery URLs; based on upload time in Unix seconds and advanced on overwrite. |
| data[].version_id | string | Identifier for this asset version, regenerated on overwrite. |
| data[].bytes | number | Size of the original source content, in bytes. |
| data[].etag | string | MD5 digest of the source bytes, as 32 lowercase hexadecimal characters. |
| data[].width | number | Source image or video width in pixels, when known. |
| data[].height | number | Source image or video height in pixels, when known. |
| data[].duration | number | Source audio or video duration in seconds, when known. |
| data[].pages | number |  |
| data[].is_audio | boolean | True for audio-only media, which uses resource_type video. |
| data[].original_filename | string | Original or overridden source filename with its final extension removed. |
| data[].tags | array&lt;string&gt; | Labels attached to the asset. |
| data[].context | object | Custom string metadata; omitted when empty or excluded by the search projection. |
| data[].created_at | string | Time this asset identity was created, in UTC. |
| data[].url | string | URL for retrieving this version of the asset’s original content. |
| data[].secure_url | string | HTTPS delivery URL for this asset version; equal to url. |
| data[].placeholder | boolean | False because this response represents stored source content. |
| data[].existing | boolean |  |
| data[].processing | object | Progress of understanding and embedding tasks for the asset. |
| data[].library_id | string | Identifier of the library containing this asset. |
| data[].sha256 | string | SHA-256 digest of the source bytes, as 64 lowercase hexadecimal characters. |
| data[].status | string | Resource status; active identifies an asset that has not been deleted. |
| data[].semantic | string | Search-vector status: pending awaits vector generation or reprocessing; ready has searchable vectors; unavailable indicates disabled, unsupported or failed embedding. Existing vectors may still serve searches while reprocessing is pending. |
| data[].preview | object | Generated video previews, present once preview generation succeeds. |
| next_cursor | string &#124; null | Opaque token to pass as cursor to listAssets; null means no further page. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/assets" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "data": [
    {
      "asset_id": "9dfa312ef9bc4b00816339b598b1152c",
      "public_id": "walk-lib-r1-MDP-1791733789929-tagged",
      "display_name": "walk-lib-r1-MDP-1791733789929-tagged",
      "asset_folder": "",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791733815,
      "version_id": "26cb8171caa5431b8373ad417fd71e32",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "tags": [
        "docs"
      ],
      "processing": {
        "state": "processing",
        "kinds": {
          "embedding": "pending",
          "visual": "running",
          "tagging": "running"
        },
        "updated_at": "2026-10-11T15:50:17.571Z"
      },
      "created_at": "2026-10-11T15:50:15.996Z",
      "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
      "placeholder": false,
      "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
      "sha256": "497790947d4666760ce38f3c00e852c71fdb66cae849bae8e9ede352719e1581",
      "status": "active",
      "semantic": "pending"
    },
    {
      "asset_id": "85b7ef616a8b4719a41777a036ebc1d2",
      "public_id": "walk-lib-r1-MDP-1791733789929-plain",
      "display_name": "walk-lib-r1-MDP-1791733789929-plain",
      "asset_folder": "",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791733810,
      "version_id": "fdf3c8cd40c2424d86e8397425a69857",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "tags": [
        "docs"
      ],
      "created_at": "2026-10-11T15:50:10.842Z",
      "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
      "placeholder": false,
      "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
      "sha256": "497790947d4666760ce38f3c00e852c71fdb66cae849bae8e9ede352719e1581",
      "status": "active",
      "processing": {
        "state": "processing",
        "kinds": {
          "embedding": "pending",
          "visual": "running"
        },
        "updated_at": "2026-10-11T15:50:17.571Z"
      },
      "semantic": "pending"
    }
  ],
  "next_cursor": null
}
```

## 上传素材 [#上传素材]

`POST /media/v1/libraries/{library_id}/assets`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| X-Unique-Upload-Id | header | string | — |
| Content-Range | header | string | — |

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| file | string / string | 是 | 文件字节、HTTPS URL、data URI 或同账户 file_… |
| public_id | string | 否 | 交付地址中的素材名称，可带路径 |
| public_id_prefix | string | 否 | public_id 的路径前缀；末尾的 / 可有可无，前缀与 ID 之间只保留一个 / |
| display_name | string | 否 | 显示名称 |
| asset_folder | string | 否 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| use_filename | boolean | 否 | 用文件名生成 public_id |
| unique_filename | boolean | 否 | 自动附加唯一后缀 |
| use_filename_as_display_name | boolean | 否 | 用文件名作为显示名称 |
| filename_override | string | 否 | 覆盖原文件名称 |
| overwrite | boolean | 否 | 是否覆盖同名素材 |
| tags | string / string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | string / object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| auto_tagging | number | 否 | 理解后将达到阈值的标签合并；0–1 |
| resource_type | image / video / raw / auto | 否 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |

返回: `CloudinaryResource`.

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string | Generated asset identifier: 32 lowercase hexadecimal characters, preserved across overwrites. |
| public_id | string | Delivery identifier unique within this library, used in asset URLs. |
| display_name | string | Human-readable asset name, independent of its delivery identifier. |
| asset_folder | string | Organizational folder path; the empty string denotes the root folder. |
| resource_type | string | Stored media category: image for images, video for video or audio, and raw for other files. Upload also accepts auto for detection. |
| type | string | Public asset delivery mode; upload is the only supported value. |
| format | string | Detected file format used as the delivery URL extension. |
| version | number | Monotonically increasing asset version used in delivery URLs; based on upload time in Unix seconds and advanced on overwrite. |
| version_id | string | Identifier for this asset version, regenerated on overwrite. |
| bytes | number | Size of the original source content, in bytes. |
| etag | string | MD5 digest of the source bytes, as 32 lowercase hexadecimal characters. |
| width | number | Source image or video width in pixels, when known. |
| height | number | Source image or video height in pixels, when known. |
| duration | number | Source audio or video duration in seconds, when known. |
| pages | number |  |
| is_audio | boolean | True for audio-only media, which uses resource_type video. |
| original_filename | string | Original or overridden source filename with its final extension removed. |
| tags | array&lt;string&gt; | Labels attached to the asset. |
| context | object | Custom string metadata; omitted when empty or excluded by the search projection. |
| context.custom | object | Caller-supplied metadata entries with string values. |
| created_at | string | Time this asset identity was created, in UTC. |
| url | string | URL for retrieving this version of the asset’s original content. |
| secure_url | string | HTTPS delivery URL for this asset version; equal to url. |
| placeholder | boolean | False because this response represents stored source content. |
| existing | boolean | True when overwrite=false returns the asset already stored under the requested public_id. |
| processing | object | Processing progress, included when auto_tagging was requested. |
| processing.state | string |  |
| processing.kinds | object | Processing states by kind. tagging is present when auto_tagging was requested and follows visual understanding. |
| processing.updated_at | string | Time the processing state was last updated, in UTC. |
| done | boolean | False while more chunks are needed before the asset is complete. / True when the final chunk has completed the asset upload. |
| upload_id | string | Upload session identifier supplied in X-Unique-Upload-Id; reuse it for subsequent chunks. |

```bash
curl -X POST "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/assets" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"file":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==","public_id":"walk-lib-r1-MDP-1791733789929-tagged","tags":["docs"],"auto_tagging":0.6}'
```

HTTP 200

```json
{
  "asset_id": "9dfa312ef9bc4b00816339b598b1152c",
  "public_id": "walk-lib-r1-MDP-1791733789929-tagged",
  "display_name": "walk-lib-r1-MDP-1791733789929-tagged",
  "asset_folder": "",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791733815,
  "version_id": "26cb8171caa5431b8373ad417fd71e32",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "processing": {
    "state": "pending",
    "kinds": {
      "visual": "pending",
      "embedding": "pending",
      "tagging": "pending"
    },
    "updated_at": "2026-10-11T15:50:15.996Z"
  },
  "created_at": "2026-10-11T15:50:15.996Z",
  "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
  "placeholder": false
}
```

## 导入文件 [#导入文件]

`POST /media/v1/libraries/{library_id}/assets/import`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| file_id | string | 是 | 同账户文件 ID |
| public_id | string | 否 | 交付地址中的素材名称，可带路径 |
| public_id_prefix | string | 否 | public_id 的路径前缀；末尾的 / 可有可无，前缀与 ID 之间只保留一个 / |
| display_name | string | 否 | 显示名称 |
| asset_folder | string | 否 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| use_filename | boolean | 否 | 用文件名生成 public_id |
| unique_filename | boolean | 否 | 自动附加唯一后缀 |
| use_filename_as_display_name | boolean | 否 | 用文件名作为显示名称 |
| filename_override | string | 否 | 覆盖原文件名称 |
| overwrite | boolean | 否 | 是否覆盖同名素材 |
| tags | string / string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | string / object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| auto_tagging | number | 否 | 理解后将达到阈值的标签合并；0–1 |
| resource_type | image / video / raw / auto | 否 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |

返回: `Asset`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string | Generated asset identifier: 32 lowercase hexadecimal characters, preserved across overwrites. |
| public_id | string | Delivery identifier unique within this library, used in asset URLs. |
| display_name | string | Human-readable asset name, independent of its delivery identifier. |
| asset_folder | string | Organizational folder path; the empty string denotes the root folder. |
| resource_type | string | Stored media category: image for images, video for video or audio, and raw for other files. Upload also accepts auto for detection. |
| type | string | Public asset delivery mode; upload is the only supported value. |
| format | string | Detected file format used as the delivery URL extension. |
| version | number | Monotonically increasing asset version used in delivery URLs; based on upload time in Unix seconds and advanced on overwrite. |
| version_id | string | Identifier for this asset version, regenerated on overwrite. |
| bytes | number | Size of the original source content, in bytes. |
| etag | string | MD5 digest of the source bytes, as 32 lowercase hexadecimal characters. |
| width | number | Source image or video width in pixels, when known. |
| height | number | Source image or video height in pixels, when known. |
| duration | number | Source audio or video duration in seconds, when known. |
| pages | number |  |
| is_audio | boolean | True for audio-only media, which uses resource_type video. |
| original_filename | string | Original or overridden source filename with its final extension removed. |
| tags | array&lt;string&gt; | Labels attached to the asset. |
| context | object | Custom string metadata; omitted when empty or excluded by the search projection. |
| context.custom | object | Caller-supplied metadata entries with string values. |
| created_at | string | Time this asset identity was created, in UTC. |
| url | string | URL for retrieving this version of the asset’s original content. |
| secure_url | string | HTTPS delivery URL for this asset version; equal to url. |
| placeholder | boolean | False because this response represents stored source content. |
| existing | boolean |  |
| processing | object | Progress of understanding and embedding tasks for the asset. |
| processing.state | string |  |
| processing.kinds | object | Processing states by kind. tagging is present when auto_tagging was requested and follows visual understanding. |
| processing.updated_at | string | Time the processing state was last updated, in UTC. |
| library_id | string | Identifier of the library containing this asset. |
| sha256 | string | SHA-256 digest of the source bytes, as 64 lowercase hexadecimal characters. |
| status | string | Resource status; active identifies an asset that has not been deleted. |
| semantic | string | Search-vector status: pending awaits vector generation or reprocessing; ready has searchable vectors; unavailable indicates disabled, unsupported or failed embedding. Existing vectors may still serve searches while reprocessing is pending. |
| preview | object | Generated video previews, present once preview generation succeeds. |
| preview.poster_url | string | Delivery URL of the video’s first-frame poster. |
| preview.storyboard | object | Preview sprite sheet with tile dimensions and sample spacing. |

## 读取素材 [#读取素材]

`GET /media/v1/libraries/{library_id}/assets/{asset_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| asset_id | path | string | 素材 ID |

返回: `Asset`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string | Generated asset identifier: 32 lowercase hexadecimal characters, preserved across overwrites. |
| public_id | string | Delivery identifier unique within this library, used in asset URLs. |
| display_name | string | Human-readable asset name, independent of its delivery identifier. |
| asset_folder | string | Organizational folder path; the empty string denotes the root folder. |
| resource_type | string | Stored media category: image for images, video for video or audio, and raw for other files. Upload also accepts auto for detection. |
| type | string | Public asset delivery mode; upload is the only supported value. |
| format | string | Detected file format used as the delivery URL extension. |
| version | number | Monotonically increasing asset version used in delivery URLs; based on upload time in Unix seconds and advanced on overwrite. |
| version_id | string | Identifier for this asset version, regenerated on overwrite. |
| bytes | number | Size of the original source content, in bytes. |
| etag | string | MD5 digest of the source bytes, as 32 lowercase hexadecimal characters. |
| width | number | Source image or video width in pixels, when known. |
| height | number | Source image or video height in pixels, when known. |
| duration | number | Source audio or video duration in seconds, when known. |
| pages | number |  |
| is_audio | boolean | True for audio-only media, which uses resource_type video. |
| original_filename | string | Original or overridden source filename with its final extension removed. |
| tags | array&lt;string&gt; | Labels attached to the asset. |
| context | object | Custom string metadata; omitted when empty or excluded by the search projection. |
| context.custom | object | Caller-supplied metadata entries with string values. |
| created_at | string | Time this asset identity was created, in UTC. |
| url | string | URL for retrieving this version of the asset’s original content. |
| secure_url | string | HTTPS delivery URL for this asset version; equal to url. |
| placeholder | boolean | False because this response represents stored source content. |
| existing | boolean |  |
| processing | object | Progress of understanding and embedding tasks for the asset. |
| processing.state | string |  |
| processing.kinds | object | Processing states by kind. tagging is present when auto_tagging was requested and follows visual understanding. |
| processing.updated_at | string | Time the processing state was last updated, in UTC. |
| library_id | string | Identifier of the library containing this asset. |
| sha256 | string | SHA-256 digest of the source bytes, as 64 lowercase hexadecimal characters. |
| status | string | Resource status; active identifies an asset that has not been deleted. |
| semantic | string | Search-vector status: pending awaits vector generation or reprocessing; ready has searchable vectors; unavailable indicates disabled, unsupported or failed embedding. Existing vectors may still serve searches while reprocessing is pending. |
| preview | object | Generated video previews, present once preview generation succeeds. |
| preview.poster_url | string | Delivery URL of the video’s first-frame poster. |
| preview.storyboard | object | Preview sprite sheet with tile dimensions and sample spacing. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/assets/85b7ef616a8b4719a41777a036ebc1d2" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "asset_id": "85b7ef616a8b4719a41777a036ebc1d2",
  "public_id": "walk-lib-r1-MDP-1791733789929-plain",
  "display_name": "walk-lib-r1-MDP-1791733789929-plain",
  "asset_folder": "",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791733810,
  "version_id": "fdf3c8cd40c2424d86e8397425a69857",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "created_at": "2026-10-11T15:50:10.842Z",
  "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
  "placeholder": false,
  "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "sha256": "497790947d4666760ce38f3c00e852c71fdb66cae849bae8e9ede352719e1581",
  "status": "active",
  "processing": {
    "state": "processing",
    "kinds": {
      "embedding": "pending",
      "visual": "running"
    },
    "updated_at": "2026-10-11T15:50:17.571Z"
  },
  "semantic": "pending"
}
```

## 更新素材 [#更新素材]

`PATCH /media/v1/libraries/{library_id}/assets/{asset_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| asset_id | path | string | 素材 ID |

### 请求体 [#请求体-2]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| display_name | string | 否 | 显示名称 |
| asset_folder | string | 否 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| tags | string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |

返回: `Asset`.

### 响应 [#响应-4]

#### HTTP 200 [#http-200-4]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string | Generated asset identifier: 32 lowercase hexadecimal characters, preserved across overwrites. |
| public_id | string | Delivery identifier unique within this library, used in asset URLs. |
| display_name | string | Human-readable asset name, independent of its delivery identifier. |
| asset_folder | string | Organizational folder path; the empty string denotes the root folder. |
| resource_type | string | Stored media category: image for images, video for video or audio, and raw for other files. Upload also accepts auto for detection. |
| type | string | Public asset delivery mode; upload is the only supported value. |
| format | string | Detected file format used as the delivery URL extension. |
| version | number | Monotonically increasing asset version used in delivery URLs; based on upload time in Unix seconds and advanced on overwrite. |
| version_id | string | Identifier for this asset version, regenerated on overwrite. |
| bytes | number | Size of the original source content, in bytes. |
| etag | string | MD5 digest of the source bytes, as 32 lowercase hexadecimal characters. |
| width | number | Source image or video width in pixels, when known. |
| height | number | Source image or video height in pixels, when known. |
| duration | number | Source audio or video duration in seconds, when known. |
| pages | number |  |
| is_audio | boolean | True for audio-only media, which uses resource_type video. |
| original_filename | string | Original or overridden source filename with its final extension removed. |
| tags | array&lt;string&gt; | Labels attached to the asset. |
| context | object | Custom string metadata; omitted when empty or excluded by the search projection. |
| context.custom | object | Caller-supplied metadata entries with string values. |
| created_at | string | Time this asset identity was created, in UTC. |
| url | string | URL for retrieving this version of the asset’s original content. |
| secure_url | string | HTTPS delivery URL for this asset version; equal to url. |
| placeholder | boolean | False because this response represents stored source content. |
| existing | boolean |  |
| processing | object | Progress of understanding and embedding tasks for the asset. |
| processing.state | string |  |
| processing.kinds | object | Processing states by kind. tagging is present when auto_tagging was requested and follows visual understanding. |
| processing.updated_at | string | Time the processing state was last updated, in UTC. |
| library_id | string | Identifier of the library containing this asset. |
| sha256 | string | SHA-256 digest of the source bytes, as 64 lowercase hexadecimal characters. |
| status | string | Resource status; active identifies an asset that has not been deleted. |
| semantic | string | Search-vector status: pending awaits vector generation or reprocessing; ready has searchable vectors; unavailable indicates disabled, unsupported or failed embedding. Existing vectors may still serve searches while reprocessing is pending. |
| preview | object | Generated video previews, present once preview generation succeeds. |
| preview.poster_url | string | Delivery URL of the video’s first-frame poster. |
| preview.storyboard | object | Preview sprite sheet with tile dimensions and sample spacing. |

```bash
curl -X PATCH "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/assets/85b7ef616a8b4719a41777a036ebc1d2" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"display_name":"walk-lib-r1-MDP-1791733789929-plain"}'
```

HTTP 200

```json
{
  "asset_id": "85b7ef616a8b4719a41777a036ebc1d2",
  "public_id": "walk-lib-r1-MDP-1791733789929-plain",
  "display_name": "walk-lib-r1-MDP-1791733789929-plain",
  "asset_folder": "",
  "resource_type": "image",
  "type": "upload",
  "format": "png",
  "version": 1791733810,
  "version_id": "fdf3c8cd40c2424d86e8397425a69857",
  "bytes": 70,
  "etag": "b357a19c87624c7c4d131aeeb4ae677f",
  "width": 1,
  "height": 1,
  "original_filename": "file",
  "tags": [
    "docs"
  ],
  "created_at": "2026-10-11T15:50:10.842Z",
  "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
  "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
  "placeholder": false,
  "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "sha256": "497790947d4666760ce38f3c00e852c71fdb66cae849bae8e9ede352719e1581",
  "status": "active",
  "processing": {
    "state": "processing",
    "kinds": {
      "embedding": "pending",
      "visual": "running"
    },
    "updated_at": "2026-10-11T15:50:17.571Z"
  },
  "semantic": "pending"
}
```

## 删除素材 [#删除素材]

`DELETE /media/v1/libraries/{library_id}/assets/{asset_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| asset_id | path | string | 素材 ID |

返回: `Deleted`.

### 响应 [#响应-5]

#### HTTP 200 [#http-200-5]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| deleted | boolean | True once this asset has been removed from the library. |

```bash
curl -X DELETE "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/assets/e5f3de0d8609482d8b351894b133c8cb" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "deleted": true
}
```

## 重新处理素材 [#重新处理素材]

`POST /media/v1/libraries/{library_id}/assets/{asset_id}/reprocess`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| asset_id | path | string | 素材 ID |

### 请求体 [#请求体-3]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| kinds | ProcessingKind[] | 否 | 要强制重跑的处理种类；省略时只重试失败项 |

返回: `Asset`.

kinds 可选 visual、frames、transcript、embedding。不带 kinds 时，只重跑当前素材版本的失败任务。显式传 kinds 时，所选的 ready、failed、unsupported 任务会重置为 pending 并强制重跑；pending 或 running 任务原样跳过，重复请求不会重复入队。

kinds 必须适用于素材类型：图片为 visual、embedding；音频为 transcript、embedding；视频为 frames、visual、transcript、embedding；raw 没有可重跑的种类。全部不适用时返回 400 INVALID\_PARAMS，消息列出该素材可用的 kinds；部分适用时只处理适用的种类，其余忽略（返回的 Asset 没有字段说明被忽略的种类，请以 processing.kinds 为准）。

重跑 visual、frames 或 transcript 时，旧结果立即标记为 superseded，同时将 embedding 与素材的 semantic 置为 pending。旧向量继续服务语义检索，直到新的向量写入后才被替换，因此重新处理期间素材不会从检索结果中消失；期间命中片段可能显示素材名称而非旧描述。默认读取只返回当前结果；使用 include\_superseded=true 可查看历史。请求立即返回更新后的 Asset，处理异步完成。

```bash
curl -X POST "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/assets/${ASSET_ID}/reprocess" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{}'
```

### 响应 [#响应-6]

#### HTTP 200 [#http-200-6]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| asset_id | string | Generated asset identifier: 32 lowercase hexadecimal characters, preserved across overwrites. |
| public_id | string | Delivery identifier unique within this library, used in asset URLs. |
| display_name | string | Human-readable asset name, independent of its delivery identifier. |
| asset_folder | string | Organizational folder path; the empty string denotes the root folder. |
| resource_type | string | Stored media category: image for images, video for video or audio, and raw for other files. Upload also accepts auto for detection. |
| type | string | Public asset delivery mode; upload is the only supported value. |
| format | string | Detected file format used as the delivery URL extension. |
| version | number | Monotonically increasing asset version used in delivery URLs; based on upload time in Unix seconds and advanced on overwrite. |
| version_id | string | Identifier for this asset version, regenerated on overwrite. |
| bytes | number | Size of the original source content, in bytes. |
| etag | string | MD5 digest of the source bytes, as 32 lowercase hexadecimal characters. |
| width | number | Source image or video width in pixels, when known. |
| height | number | Source image or video height in pixels, when known. |
| duration | number | Source audio or video duration in seconds, when known. |
| pages | number |  |
| is_audio | boolean | True for audio-only media, which uses resource_type video. |
| original_filename | string | Original or overridden source filename with its final extension removed. |
| tags | array&lt;string&gt; | Labels attached to the asset. |
| context | object | Custom string metadata; omitted when empty or excluded by the search projection. |
| context.custom | object | Caller-supplied metadata entries with string values. |
| created_at | string | Time this asset identity was created, in UTC. |
| url | string | URL for retrieving this version of the asset’s original content. |
| secure_url | string | HTTPS delivery URL for this asset version; equal to url. |
| placeholder | boolean | False because this response represents stored source content. |
| existing | boolean |  |
| processing | object | Progress of understanding and embedding tasks for the asset. |
| processing.state | string |  |
| processing.kinds | object | Processing states by kind. tagging is present when auto_tagging was requested and follows visual understanding. |
| processing.updated_at | string | Time the processing state was last updated, in UTC. |
| library_id | string | Identifier of the library containing this asset. |
| sha256 | string | SHA-256 digest of the source bytes, as 64 lowercase hexadecimal characters. |
| status | string | Resource status; active identifies an asset that has not been deleted. |
| semantic | string | Search-vector status: pending awaits vector generation or reprocessing; ready has searchable vectors; unavailable indicates disabled, unsupported or failed embedding. Existing vectors may still serve searches while reprocessing is pending. |
| preview | object | Generated video previews, present once preview generation succeeds. |
| preview.poster_url | string | Delivery URL of the video’s first-frame poster. |
| preview.storyboard | object | Preview sprite sheet with tile dimensions and sample spacing. |

## AssetPage [#assetpage]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | Asset[] | 是 | 本页结果 |
| next_cursor | string / null | 是 | 下一页游标；没有时为 null 或省略 |

## CloudinaryResource [#cloudinaryresource]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_id | AssetId | 是 | 素材 ID |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |
| display_name | string | 是 | 显示名称 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| resource_type | ResourceType | 是 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| type | DeliveryType | 是 | 资源或事件类型 |
| format | string | 是 | 文件格式 |
| version | number | 是 | 交付版本号 |
| version_id | string | 是 | 版本标识 |
| bytes | number | 是 | 文件字节数 |
| etag | string | 是 | 文件校验标识 |
| width | number | 否 | 宽度像素 |
| height | number | 否 | 高度像素 |
| duration | number | 否 | 时长秒数 |
| pages | number | 否 | 文档页数 |
| is_audio | boolean | 否 | 是否为音频 |
| original_filename | string | 否 | 原文件名称 |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| created_at | IsoTimestamp | 是 | 创建时间 |
| url | string | 是 | 原文件地址 |
| secure_url | string | 是 | HTTPS 交付地址 |
| placeholder | false | 是 | 固定为 false |
| existing | boolean | 否 | 未覆盖时是否返回已有素材 |
| processing | Processing | 否 | 整体与各项理解状态 |

## Asset [#asset]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_id | AssetId | 是 | 素材 ID |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |
| display_name | string | 是 | 显示名称 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| resource_type | ResourceType | 是 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| type | DeliveryType | 是 | 资源或事件类型 |
| format | string | 是 | 文件格式 |
| version | number | 是 | 交付版本号 |
| version_id | string | 是 | 版本标识 |
| bytes | number | 是 | 文件字节数 |
| etag | string | 是 | 文件校验标识 |
| width | number | 否 | 宽度像素 |
| height | number | 否 | 高度像素 |
| duration | number | 否 | 时长秒数 |
| pages | number | 否 | 文档页数 |
| is_audio | boolean | 否 | 是否为音频 |
| original_filename | string | 否 | 原文件名称 |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| created_at | IsoTimestamp | 是 | 创建时间 |
| url | string | 是 | 原文件地址 |
| secure_url | string | 是 | HTTPS 交付地址 |
| placeholder | false | 是 | 固定为 false |
| existing | boolean | 否 | 未覆盖时是否返回已有素材 |
| processing | Processing | 是 | 整体与各项理解状态 |
| library_id | LibraryId | 是 | 库 ID |
| sha256 | string | 是 | 内容校验摘要 |
| status | "active" | 是 | 资源状态 |
| semantic | "pending" / "ready" / "unavailable" | 是 | ready 时可语义检索 |
| preview | object | 否 | 预览海报和故事板 |

## Deleted [#deleted]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| deleted | true | 是 | 删除结果 |

## Processing [#processing]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| state | ProcessingState | 是 | 整体处理状态 |
| kinds | object | 是 | 各项处理状态 |
| updated_at | IsoTimestamp | 是 | 更新时间 |

## Storyboard [#storyboard]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | string | 是 | 原文件地址 |
| tiles | number | 是 | 故事板画面数 |
| interval_ms | number | 是 | 画面间隔毫秒数 |
| tile_width | number | 是 | 单个画面宽度 |
| tile_height | number | 是 | 单个画面高度 |

# 理解结果

## 重新理解已有素材 [#重新理解已有素材]

kinds 可选 visual、frames、transcript、embedding。不带 kinds 时，只重跑当前素材版本的失败任务。显式传 kinds 时，所选的 ready、failed、unsupported 任务会重置为 pending 并强制重跑；pending 或 running 任务原样跳过，重复请求不会重复入队。

kinds 必须适用于素材类型：图片为 visual、embedding；音频为 transcript、embedding；视频为 frames、visual、transcript、embedding；raw 没有可重跑的种类。全部不适用时返回 400 INVALID\_PARAMS，消息列出该素材可用的 kinds；部分适用时只处理适用的种类，其余忽略（返回的 Asset 没有字段说明被忽略的种类，请以 processing.kinds 为准）。

重跑 visual、frames 或 transcript 时，旧结果立即标记为 superseded，同时将 embedding 与素材的 semantic 置为 pending。旧向量继续服务语义检索，直到新的向量写入后才被替换，因此重新处理期间素材不会从检索结果中消失；期间命中片段可能显示素材名称而非旧描述。默认读取只返回当前结果；使用 include\_superseded=true 可查看历史。请求立即返回更新后的 Asset，处理异步完成。

## 转写幻听过滤 [#转写幻听过滤]

转写片段先做全角转半角、转小写并去除首尾空白和标点。规范化后为空，或整段命中常见幻听短语表时，丢弃该片段。仅完整匹配，不做子串匹配，例如 “thank you for the report” 会保留。

短语表包括：thank you、thanks for watching、thank you for watching、please subscribe、subscribe、you、bye、字幕由amara.org社区提供、请不吝点赞 订阅 转发 打赏支持明镜与点点栏目、谢谢观看、优优独播剧场——yoyo television series exclusive。

被过滤的片段不进入转写文字、关键词索引或转写向量。全部被过滤时，transcript 理解仍为 ready，content 为空字符串，data 为 `{ "filtered_segments": n }`，n 是被过滤的片段数；该素材不会生成转写向量。

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/native/media)

## 读取理解 [#读取理解]

`GET /media/v1/libraries/{library_id}/assets/{asset_id}/understandings`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| asset_id | path | string | 素材 ID |
| include_superseded | query | boolean | 包含已被新版本替代的结果；只接受 true 或 false |
| kind | query | caption / tags / ocr / transcript / frame | 理解或处理种类；列出理解结果时按此筛选 |
| cursor | query | string | 上一页的 next_cursor |
| limit | query | integer | 每页 1–200 条，默认 200 |

返回: `UnderstandingPage`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Understanding results in this page, ordered by creation time ascending. |
| data[].id | string | Generated identifier of this understanding result. |
| data[].asset_id | string | Identifier of the asset from which this result was produced. |
| data[].asset_version | number | Asset version processed to produce this result; compare with the asset’s current version. |
| data[].kind | string | Result kind: caption is a visual description, tags are recognized labels, ocr is text recognized in the image, transcript is speech text, and frame is a description of a video segment. |
| data[].producer | string | Producer model identifier; a failure may use the configured model when no model response is available. |
| data[].producer_version | string |  |
| data[].segment | object &#124; null | Source-media time range for a frame or transcript segment; null for results without a segment. |
| data[].status | string | Result status: ready contains completed output; failed records an error. |
| data[].content | string &#124; null | Text output, such as a caption, recognized text or transcript; null for structured-only or failed results. |
| data[].data | any &#124; null | Structured producer output, such as recognized labels or frame details; null when absent. |
| data[].confidence | number &#124; null |  |
| data[].error | object &#124; null | Failure code and message, or null for a successful result. |
| data[].superseded | boolean | Whether a newer result or asset version has replaced this result. Excluded from listing unless include_superseded is true. |
| data[].created_at | string | Time this immutable result was recorded, in UTC. |
| next_cursor | string &#124; null | Opaque token to pass as cursor to listUnderstandings; null means no further page. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/assets/9339cdae93804c0c8c65d5189ef1f646/understandings" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "data": [],
  "next_cursor": null
}
```

## UnderstandingPage [#understandingpage]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | Understanding[] | 是 | 本页结果 |
| next_cursor | string / null | 是 | 下一页游标；没有时为 null 或省略 |

## Understanding [#understanding]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | UnderstandingId | 是 | 资源 ID |
| asset_id | AssetId | 是 | 素材 ID |
| asset_version | number | 是 | 理解对应的素材版本 |
| kind | UnderstandingKind | 是 | 理解或处理种类；列出理解结果时按此筛选 |
| producer | string | 是 | 理解生成者 |
| producer_version | string | 是 | 生成者版本 |
| segment | Segment / null | 是 | 起止毫秒；整份素材为 null |
| status | "ready" / "failed" | 是 | 资源状态 |
| content | string / null | 是 | 理解的文字内容 |
| data | JSON / null | 是 | 本页结果 |
| confidence | number / null | 是 | 置信度；可能为空 |
| error | object / null | 是 | 错误码与消息；成功时为空 |
| superseded | boolean | 是 | 是否被新版本替代 |
| created_at | IsoTimestamp | 是 | 创建时间 |

## Segment [#segment]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| start_ms | number | 是 | 片段开始毫秒 |
| end_ms | number | 是 | 片段结束毫秒 |

# 检索

expression 接受表达式；semantic 与 search 接受自然语言。语义检索只返回就绪素材。

[表达式语法](/docs/api/compatible/cloudinary/search)

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/native/media)

## 表达式检索 [#表达式检索]

`POST /media/v1/libraries/{library_id}/search/expression`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| expression | string | 否 | 结构化查询表达式；空表达式返回全部素材 |
| sort_by | object[] | 否 | 排序字段与方向 |
| max_results | integer | 否 | 最多 500；检索默认 100，Admin 默认 10 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |
| with_field | tags / context[] | 否 | 额外返回 tags 或 context |
| aggregate | AggregateField[] | 否 | 统计字段 |

返回: `ExpressionSearchResult`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| total_count | number | Number of matching assets across pages; a lower bound when total_count_exact is false. |
| time | number | Elapsed search time in whole milliseconds. |
| next_cursor | string | Continuation token for the next page; omitted when no further page is available. |
| resources | array&lt;object&gt; | Assets in this page, ordered by sort_by; tags and context follow with_field. |
| resources[].asset_id | string | Generated asset identifier: 32 lowercase hexadecimal characters, preserved across overwrites. |
| resources[].public_id | string | Delivery identifier unique within this library, used in asset URLs. |
| resources[].display_name | string | Human-readable asset name, independent of its delivery identifier. |
| resources[].asset_folder | string | Organizational folder path; the empty string denotes the root folder. |
| resources[].resource_type | string | Stored media category: image for images, video for video or audio, and raw for other files. Upload also accepts auto for detection. |
| resources[].type | string | Public asset delivery mode; upload is the only supported value. |
| resources[].format | string | Detected file format used as the delivery URL extension. |
| resources[].version | number | Monotonically increasing asset version used in delivery URLs; based on upload time in Unix seconds and advanced on overwrite. |
| resources[].version_id | string | Identifier for this asset version, regenerated on overwrite. |
| resources[].bytes | number | Size of the original source content, in bytes. |
| resources[].etag | string | MD5 digest of the source bytes, as 32 lowercase hexadecimal characters. |
| resources[].width | number | Source image or video width in pixels, when known. |
| resources[].height | number | Source image or video height in pixels, when known. |
| resources[].duration | number | Source audio or video duration in seconds, when known. |
| resources[].pages | number |  |
| resources[].is_audio | boolean | True for audio-only media, which uses resource_type video. |
| resources[].original_filename | string | Original or overridden source filename with its final extension removed. |
| resources[].tags | array&lt;string&gt; | Labels attached to the asset. |
| resources[].context | object | Custom string metadata; omitted when empty or excluded by the search projection. |
| resources[].created_at | string | Time this asset identity was created, in UTC. |
| resources[].url | string | URL for retrieving this version of the asset’s original content. |
| resources[].secure_url | string | HTTPS delivery URL for this asset version; equal to url. |
| resources[].placeholder | boolean | False because this response represents stored source content. |
| resources[].existing | boolean |  |
| resources[].processing | object | Progress of understanding and embedding tasks for the asset. |
| resources[].library_id | string | Identifier of the library containing this asset. |
| resources[].sha256 | string | SHA-256 digest of the source bytes, as 64 lowercase hexadecimal characters. |
| resources[].status | string | Resource status; active identifies an asset that has not been deleted. |
| resources[].semantic | string | Search-vector status: pending awaits vector generation or reprocessing; ready has searchable vectors; unavailable indicates disabled, unsupported or failed embedding. Existing vectors may still serve searches while reprocessing is pending. |
| resources[].preview | object | Generated video previews, present once preview generation succeeds. |
| aggregations | object | Requested facet counts, keyed by facet name and then by field value. |
| total_count_exact | boolean | Whether total_count covers all matches; false indicates a bounded partial count. |
| aggregations_exact | boolean | Whether the returned facet counts cover all matching assets. |

```bash
curl -X POST "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/search/expression" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"expression":"tags:docs"}'
```

HTTP 200

```json
{
  "total_count": 2,
  "total_count_exact": true,
  "time": 0,
  "resources": [
    {
      "asset_id": "9dfa312ef9bc4b00816339b598b1152c",
      "public_id": "walk-lib-r1-MDP-1791733789929-tagged",
      "display_name": "walk-lib-r1-MDP-1791733789929-tagged",
      "asset_folder": "",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791733815,
      "version_id": "26cb8171caa5431b8373ad417fd71e32",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "processing": {
        "state": "processing",
        "kinds": {
          "embedding": "pending",
          "visual": "running",
          "tagging": "running"
        },
        "updated_at": "2026-10-11T15:50:17.571Z"
      },
      "created_at": "2026-10-11T15:50:15.996Z",
      "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733815/walk-lib-r1-MDP-1791733789929-tagged.png",
      "placeholder": false,
      "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
      "sha256": "497790947d4666760ce38f3c00e852c71fdb66cae849bae8e9ede352719e1581",
      "status": "active",
      "semantic": "pending"
    },
    {
      "asset_id": "85b7ef616a8b4719a41777a036ebc1d2",
      "public_id": "walk-lib-r1-MDP-1791733789929-plain",
      "display_name": "walk-lib-r1-MDP-1791733789929-plain",
      "asset_folder": "",
      "resource_type": "image",
      "type": "upload",
      "format": "png",
      "version": 1791733810,
      "version_id": "fdf3c8cd40c2424d86e8397425a69857",
      "bytes": 70,
      "etag": "b357a19c87624c7c4d131aeeb4ae677f",
      "width": 1,
      "height": 1,
      "original_filename": "file",
      "created_at": "2026-10-11T15:50:10.842Z",
      "url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
      "secure_url": "https://media-develop.praxisusercontent.com/lib_d3881a2f54a34cd79121b9d659e8378c/image/upload/v1791733810/walk-lib-r1-MDP-1791733789929-plain.png",
      "placeholder": false,
      "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
      "sha256": "497790947d4666760ce38f3c00e852c71fdb66cae849bae8e9ede352719e1581",
      "status": "active",
      "processing": {
        "state": "processing",
        "kinds": {
          "embedding": "pending",
          "visual": "running"
        },
        "updated_at": "2026-10-11T15:50:17.571Z"
      },
      "semantic": "pending"
    }
  ]
}
```

## 以图搜图 [#以图搜图]

`POST /media/v1/libraries/{library_id}/search/visual`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_id | AssetId | 否 | 素材 ID |
| image | object | 否 | 查询图片对象，data 为 base64，mime 为图片类型 |
| top_k | integer | 否 | 命中数，1–50 |
| filter | string | 否 | 表达式筛选条件 |

返回: `SemanticSearchResult`.

库的 `search.image` 为 true 时可用；不支持的库返回 LIBRARY\_INVALID\_STATE。图片仅接受 JPEG、PNG、WebP、GIF，解码后最大 10 MiB。每个素材返回最高分命中，视频定位到最佳帧。qwen3-vl-embedding 的图片相似度门槛为 0.35。标定来自 2026-10-10 的测试：同图变体 0.82–0.96，同类场景 0.38–0.66，无关图片最高 0.34。

`asset_id` 与 `image: { data, mime }` 必须且只能给一个。asset\_id 复用已有图片理解并排除素材自身；视频使用第一帧，未完成理解返回 LIBRARY\_INVALID\_STATE。上传图片的 data 为 base64。top\_k 默认 20，范围 1–50；filter 使用与 semantic 相同的表达式。仅检索图片相似内容，返回与 semantic 相同的 hits、embedding\_producer、not\_ready\_excluded；matches.kind 为 image，snippet 为最新描述或素材名称。删除、旧版本及已替换的理解不会出现在结果中。

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| hits | array&lt;object&gt; | Ranked assets up to top_k; an empty array means no eligible matches were found. |
| hits[].asset | object | Asset matched by the query. |
| hits[].score | number | Ranking score: cosine similarity for semantic or visual search; normalized rank-fusion score for hybrid search. Higher values rank first. |
| hits[].semantic_score | number &#124; null | Cosine similarity for hybrid hits with a semantic match; null for keyword-only hybrid hits. Omitted outside hybrid mode. |
| hits[].matches | array&lt;object&gt; | Supporting content or metadata matches contributing to this asset’s hit. |
| embedding_producer | string | Embedding model identifier used for the query, or for the source asset embedding in an asset-based visual query. |
| not_ready_excluded | number | Number of distinct candidate asset identifiers, or unresolved vector identifiers, excluded because their vectors or assets were missing, deleted or stale; not a count of all pending assets in the library. |

## 语义检索 [#语义检索]

`POST /media/v1/libraries/{library_id}/search/semantic`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体-2]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| query | string | 是 | 用自然语言描述要找的内容 |
| filter | string | 否 | 表达式筛选条件 |
| top_k | integer | 否 | 命中数，1–50 |
| mode | hybrid / semantic | 否 | hybrid 结合关键词与语义；semantic 仅语义 |

返回: `SemanticSearchResult`.

使用 bge-m3 时，向量候选在与关键词结果融合前按余弦相似度 ≥ 0.55 筛选，新完成的内容也使用相同门槛。门槛依据 2026-10-09 的 7 个演示素材标定：相关结果最低约 0.58（0.581–0.729），不相关结果最高 0.523；完全无关的查询最高 0.478。qwen3-vl-embedding 的文字查询对文字内容（描述、转写）门槛为 0.40，对图片内容门槛为 0.25；其他模型尚未标定，暂不过滤。关键词命中不受此门槛影响。查询与库内容都不相关时返回空列表；mode=semantic 只返回达到向量门槛的结果。

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| hits | array&lt;object&gt; | Ranked assets up to top_k; an empty array means no eligible matches were found. |
| hits[].asset | object | Asset matched by the query. |
| hits[].score | number | Ranking score: cosine similarity for semantic or visual search; normalized rank-fusion score for hybrid search. Higher values rank first. |
| hits[].semantic_score | number &#124; null | Cosine similarity for hybrid hits with a semantic match; null for keyword-only hybrid hits. Omitted outside hybrid mode. |
| hits[].matches | array&lt;object&gt; | Supporting content or metadata matches contributing to this asset’s hit. |
| embedding_producer | string | Embedding model identifier used for the query, or for the source asset embedding in an asset-based visual query. |
| not_ready_excluded | number | Number of distinct candidate asset identifiers, or unresolved vector identifiers, excluded because their vectors or assets were missing, deleted or stale; not a count of all pending assets in the library. |

## 语义检索别名 [#语义检索别名]

`POST /media/v1/libraries/{library_id}/search`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体-3]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| query | string | 是 | 用自然语言描述要找的内容 |
| filter | string | 否 | 表达式筛选条件 |
| top_k | integer | 否 | 命中数，1–50 |
| mode | hybrid / semantic | 否 | hybrid 结合关键词与语义；semantic 仅语义 |

返回: `SemanticSearchResult`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| hits | array&lt;object&gt; | Ranked assets up to top_k; an empty array means no eligible matches were found. |
| hits[].asset | object | Asset matched by the query. |
| hits[].score | number | Ranking score: cosine similarity for semantic or visual search; normalized rank-fusion score for hybrid search. Higher values rank first. |
| hits[].semantic_score | number &#124; null | Cosine similarity for hybrid hits with a semantic match; null for keyword-only hybrid hits. Omitted outside hybrid mode. |
| hits[].matches | array&lt;object&gt; | Supporting content or metadata matches contributing to this asset’s hit. |
| embedding_producer | string | Embedding model identifier used for the query, or for the source asset embedding in an asset-based visual query. |
| not_ready_excluded | number | Number of distinct candidate asset identifiers, or unresolved vector identifiers, excluded because their vectors or assets were missing, deleted or stale; not a count of all pending assets in the library. |

## ExpressionSearchResult [#expressionsearchresult]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| total_count | number | 是 | 匹配总数 |
| time | number | 是 | 检索耗时，整数毫秒，由服务端测得 |
| next_cursor | string | 否 | 下一页游标；没有时为 null 或省略 |
| resources | SearchAsset[] | 是 | 本页素材 |
| aggregations | object | 否 | 按请求字段统计 |
| total_count_exact | boolean | 否 | 计数是否精确 |
| aggregations_exact | boolean | 否 | 统计是否精确 |

## SemanticSearchResult [#semanticsearchresult]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| hits | SemanticHit[] | 是 | 检索命中 |
| embedding_producer | string | 是 | 语义理解生成者 |
| not_ready_excluded | number | 是 | 因未就绪而排除的素材数 |

## SearchAsset [#searchasset]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset_id | AssetId | 是 | 素材 ID |
| public_id | string | 是 | 交付地址中的素材名称，可带路径 |
| display_name | string | 是 | 显示名称 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |
| resource_type | ResourceType | 是 | image、video（含音频）或 raw；auto 只用于上传，列表传 auto 或其他值返回 400 |
| type | DeliveryType | 是 | 资源或事件类型 |
| format | string | 是 | 文件格式 |
| version | number | 是 | 交付版本号 |
| version_id | string | 是 | 版本标识 |
| bytes | number | 是 | 文件字节数 |
| etag | string | 是 | 文件校验标识 |
| width | number | 否 | 宽度像素 |
| height | number | 否 | 高度像素 |
| duration | number | 否 | 时长秒数 |
| pages | number | 否 | 文档页数 |
| is_audio | boolean | 否 | 是否为音频 |
| original_filename | string | 否 | 原文件名称 |
| tags | string[] | 否 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |
| context | object | 否 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |
| created_at | IsoTimestamp | 是 | 创建时间 |
| url | string | 是 | 原文件地址 |
| secure_url | string | 是 | HTTPS 交付地址 |
| placeholder | false | 是 | 固定为 false |
| existing | boolean | 否 | 未覆盖时是否返回已有素材 |
| processing | Processing | 是 | 整体与各项理解状态 |
| library_id | LibraryId | 是 | 库 ID |
| sha256 | string | 是 | 内容校验摘要 |
| status | "active" | 是 | 资源状态 |
| semantic | "pending" / "ready" / "unavailable" | 是 | ready 时可语义检索 |
| preview | object | 否 | 预览海报和故事板 |

## SemanticHit [#semantichit]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| asset | Asset | 是 | 命中的素材 |
| score | number | 是 | 相关度分数 |
| semantic_score | number / null | 否 | — |
| matches | SemanticMatch[] | 是 | 匹配内容与片段时间 |

## SemanticMatch [#semanticmatch]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| kind | UnderstandingKind / "metadata" / "image" | 是 | 理解或处理种类；列出理解结果时按此筛选 |
| understanding_id | UnderstandingId / null | 是 | 对应的理解记录；元数据命中为空 |
| segment | Segment / null | 是 | 起止毫秒；整份素材为 null |
| snippet | string | 是 | 命中文字片段 |

# 文件夹

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/native/media)

## 列出文件夹 [#列出文件夹]

`GET /media/v1/libraries/{library_id}/folders`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| parent | query | string | 父文件夹路径；省略或空字符串为根。一次返回这一层的全部子文件夹，不分页；传 limit 或 cursor 返回 400 |

返回: `Folders`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| folders | array&lt;object&gt; | All immediate child folders of parent, sorted by path. |
| folders[].name | string | Final path segment naming the child folder. |
| folders[].path | string | Full folder path relative to the library root. |
| folders[].asset_count | number | Number of assets in this folder and all descendant folders. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/folders" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "folders": [
    {
      "name": "examples",
      "path": "examples",
      "asset_count": 1
    }
  ]
}
```

## Folders [#folders]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| folders | object[] | 是 | 文件夹列表 |

# 批量操作

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/native/media)

## 批量操作 [#批量操作]

`POST /media/v1/libraries/{library_id}/batches`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "tag" / "untag" | 是 | 批量操作 |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "set_context" | 是 | 批量操作 |
| context | object | 是 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "move" | 是 | 批量操作 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "delete" | 是 | 批量操作 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| selector | BatchSelector | 是 | 按 ID 或表达式选择 |

返回: `Job`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Generated batch identifier: job_ followed by 32 lowercase hexadecimal characters. |
| library_id | string | Identifier of the library in which the batch operates. |
| action | string | Batch operation: tag adds labels, untag removes labels, set_context replaces custom metadata, move changes asset_folder, and delete removes selected assets. |
| status | string | Job status: queued awaits execution; running is processing items; completed means all items succeeded; completed_with_errors means some succeeded and some failed; failed means all selected items failed. An empty job completes successfully. |
| total | number | Number of distinct assets selected when the job was created. |
| done | number | Number of items successfully processed; failed items are counted separately. |
| failed | number | Number of items that could not be processed successfully. |
| failures | array&lt;object&gt; | Always present, including an empty array before any item failure or when all items succeed. At most 20 item failures are returned. |
| failures[].asset_id | string | Identifier supplied for the failed item; it may identify a missing asset. |
| failures[].code | string | Domain error code explaining the individual item failure. |
| created_at | string | Time the batch job was created, in UTC. |
| finished_at | string &#124; null | Time the job reached a terminal status, or null while queued or running. |

```bash
curl -X POST "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/batches" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"action":"tag","tags":["sample"],"selector":{"ids":["85b7ef616a8b4719a41777a036ebc1d2","00000000000000000000000000000000"]}}'
```

HTTP 200

```json
{
  "id": "job_b562f087623c4756b43813e3dce670ba",
  "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "action": "tag",
  "status": "queued",
  "total": 2,
  "done": 0,
  "failed": 0,
  "created_at": "2026-10-11T15:50:24.942Z",
  "failures": [],
  "finished_at": null
}
```

## 读取任务 [#读取任务]

`GET /media/v1/libraries/{library_id}/batches/{job_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| job_id | path | string | 任务 ID |

返回: `Job`.

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Generated batch identifier: job_ followed by 32 lowercase hexadecimal characters. |
| library_id | string | Identifier of the library in which the batch operates. |
| action | string | Batch operation: tag adds labels, untag removes labels, set_context replaces custom metadata, move changes asset_folder, and delete removes selected assets. |
| status | string | Job status: queued awaits execution; running is processing items; completed means all items succeeded; completed_with_errors means some succeeded and some failed; failed means all selected items failed. An empty job completes successfully. |
| total | number | Number of distinct assets selected when the job was created. |
| done | number | Number of items successfully processed; failed items are counted separately. |
| failed | number | Number of items that could not be processed successfully. |
| failures | array&lt;object&gt; | Always present, including an empty array before any item failure or when all items succeed. At most 20 item failures are returned. |
| failures[].asset_id | string | Identifier supplied for the failed item; it may identify a missing asset. |
| failures[].code | string | Domain error code explaining the individual item failure. |
| created_at | string | Time the batch job was created, in UTC. |
| finished_at | string &#124; null | Time the job reached a terminal status, or null while queued or running. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/batches/job_b562f087623c4756b43813e3dce670ba" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "id": "job_b562f087623c4756b43813e3dce670ba",
  "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "action": "tag",
  "status": "completed_with_errors",
  "total": 2,
  "done": 1,
  "failed": 1,
  "created_at": "2026-10-11T15:50:24.942Z",
  "failures": [
    {
      "asset_id": "00000000000000000000000000000000",
      "code": "ASSET_NOT_FOUND"
    }
  ],
  "finished_at": "2026-10-11T15:50:27.555Z"
}
```

## 批量操作别名 [#批量操作别名]

`POST /media/v1/libraries/{library_id}/assets:batch`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "tag" / "untag" | 是 | 批量操作 |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "set_context" | 是 | 批量操作 |
| context | object | 是 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "move" | 是 | 批量操作 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "delete" | 是 | 批量操作 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| selector | BatchSelector | 是 | 按 ID 或表达式选择 |

返回: `Job`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Generated batch identifier: job_ followed by 32 lowercase hexadecimal characters. |
| library_id | string | Identifier of the library in which the batch operates. |
| action | string | Batch operation: tag adds labels, untag removes labels, set_context replaces custom metadata, move changes asset_folder, and delete removes selected assets. |
| status | string | Job status: queued awaits execution; running is processing items; completed means all items succeeded; completed_with_errors means some succeeded and some failed; failed means all selected items failed. An empty job completes successfully. |
| total | number | Number of distinct assets selected when the job was created. |
| done | number | Number of items successfully processed; failed items are counted separately. |
| failed | number | Number of items that could not be processed successfully. |
| failures | array&lt;object&gt; | Always present, including an empty array before any item failure or when all items succeed. At most 20 item failures are returned. |
| failures[].asset_id | string | Identifier supplied for the failed item; it may identify a missing asset. |
| failures[].code | string | Domain error code explaining the individual item failure. |
| created_at | string | Time the batch job was created, in UTC. |
| finished_at | string &#124; null | Time the job reached a terminal status, or null while queued or running. |

```bash
curl -X POST "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/assets:batch" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"action":"tag","tags":["sample"],"selector":{"ids":["85b7ef616a8b4719a41777a036ebc1d2"]}}'
```

HTTP 200

```json
{
  "id": "job_3c2fe728de054c7396058c7438b289d2",
  "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "action": "tag",
  "status": "queued",
  "total": 1,
  "done": 0,
  "failed": 0,
  "created_at": "2026-10-11T15:50:29.266Z",
  "failures": [],
  "finished_at": null
}
```

## 读取任务别名 [#读取任务别名]

`GET /media/v1/libraries/{library_id}/jobs/{job_id}`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| job_id | path | string | 任务 ID |

返回: `Job`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Generated batch identifier: job_ followed by 32 lowercase hexadecimal characters. |
| library_id | string | Identifier of the library in which the batch operates. |
| action | string | Batch operation: tag adds labels, untag removes labels, set_context replaces custom metadata, move changes asset_folder, and delete removes selected assets. |
| status | string | Job status: queued awaits execution; running is processing items; completed means all items succeeded; completed_with_errors means some succeeded and some failed; failed means all selected items failed. An empty job completes successfully. |
| total | number | Number of distinct assets selected when the job was created. |
| done | number | Number of items successfully processed; failed items are counted separately. |
| failed | number | Number of items that could not be processed successfully. |
| failures | array&lt;object&gt; | Always present, including an empty array before any item failure or when all items succeed. At most 20 item failures are returned. |
| failures[].asset_id | string | Identifier supplied for the failed item; it may identify a missing asset. |
| failures[].code | string | Domain error code explaining the individual item failure. |
| created_at | string | Time the batch job was created, in UTC. |
| finished_at | string &#124; null | Time the job reached a terminal status, or null while queued or running. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/jobs/job_3c2fe728de054c7396058c7438b289d2" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "id": "job_3c2fe728de054c7396058c7438b289d2",
  "library_id": "lib_d3881a2f54a34cd79121b9d659e8378c",
  "action": "tag",
  "status": "completed",
  "total": 1,
  "done": 1,
  "failed": 0,
  "created_at": "2026-10-11T15:50:29.266Z",
  "failures": [],
  "finished_at": "2026-10-11T15:50:29.494Z"
}
```

## Job [#job]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | JobId | 是 | 资源 ID |
| library_id | LibraryId | 是 | 库 ID |
| action | tag / untag / set_context / move / delete | 是 | 批量操作 |
| status | "queued" / "running" / "completed" / "completed_with_errors" / "failed" | 是 | 资源状态 |
| total | number | 是 | 任务素材总数 |
| done | number | 是 | 已完成数量；分片响应中表示是否完成 |
| failed | number | 是 | 失败数量 |
| failures | object[] | 是 | — |
| created_at | IsoTimestamp | 是 | 创建时间 |
| finished_at | IsoTimestamp / null | 是 | 结束时间；未结束为空 |

## BatchSelector [#batchselector]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| ids | AssetId[] | 是 | 素材 ID 列表 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| expression | string | 是 | 结构化查询表达式；空表达式返回全部素材 |
| exclusions | AssetId[] | 否 | 从选择中排除的素材 ID |

## BatchAction [#batchaction]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "tag" / "untag" | 是 | 批量操作 |
| tags | string[] | 是 | 素材标签。上传可传逗号分隔字符串（每项去首尾空白、丢弃空项）、数组或重复的 tags 字段；PATCH 只接受数组并整体替换 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "set_context" | 是 | 批量操作 |
| context | object | 是 | 自定义文字键值；PATCH 整体替换，传 &#123;&#125; 清空 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "move" | 是 | 批量操作 |
| asset_folder | string | 是 | 组织文件夹；不改变 public_id。按它列出时只匹配这一层、不含子文件夹；空字符串表示根 |

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| action | "delete" | 是 | 批量操作 |

# 事件

按 seq 翻页：asc 配 after\_seq，desc 配 before\_seq；两个游标不可同用。

[指南 →](/docs/cloud/services/media/quickstart)

[基础地址与鉴权](/docs/api/native/media)

## 读取事件 [#读取事件]

`GET /media/v1/libraries/{library_id}/events`

| 参数 | 位置 | 类型 | 说明 |
| --- | --- | --- | --- |
| library_id | path | string | 库 ID |
| after_seq | query | integer | 升序游标；不可与 before_seq 同用 |
| before_seq | query | integer | 降序游标；不可与 after_seq 同用 |
| order | query | asc / desc | asc 默认升序或 desc 降序 |
| limit | query | integer | 每页 1–200 条，默认 50 |

返回: `MediaEventPage`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Successful response.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Events in this page, ordered by sequence in the requested direction. |
| data[].seq | number | Increasing sequence number within this library; use it with after_seq or before_seq to page through events. |
| data[].id | string | Unique identifier of this recorded event. |
| data[].type | string | Type of lifecycle, asset, processing, search or batch change recorded. |
| data[].processed_at | string | Time this event was recorded, in UTC. |
| data[].library_id | string | Identifier of the library whose event was recorded. |
| data[].asset_id | string | Related asset identifier, when the event concerns an asset. |
| data[].job_id | string | Related batch job identifier, when present. |
| data[].kind | string | Related processing task: visual, frames, transcript or embedding. |
| data[].detail | object | Event-specific details, such as changed values, reprocessing kinds or failed-item counts. |
| next_cursor | string &#124; null | Last returned sequence as a string when more events exist; convert to a number and pass as after_seq for asc or before_seq for desc. Null means no further page. |

```bash
curl -X GET "https://api.deepraxis.ai/media/v1/libraries/${LIBRARY_ID}/events?limit=1" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

HTTP 200

```json
{
  "data": [
    {
      "seq": 1,
      "id": "2cd2cd71-1fc5-41fc-aeb0-29583af9b900",
      "type": "library.status_provisioning",
      "processed_at": "2026-10-09T09:34:09.858Z",
      "library_id": "lib_fff73e25733449b1bf6f880d91f5c045"
    }
  ],
  "next_cursor": "1"
}
```

## MediaEventPage [#mediaeventpage]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | MediaEvent[] | 是 | 本页结果 |
| next_cursor | string / null | 是 | 下一页游标；没有时为 null 或省略 |

## MediaEvent [#mediaevent]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| seq | number | 是 | 库内递增的事件序号 |
| id | string | 是 | 资源 ID |
| type | MediaEventType | 是 | 资源或事件类型 |
| processed_at | IsoTimestamp | 是 | 事件时间 |
| library_id | LibraryId | 是 | 库 ID |
| asset_id | AssetId | 否 | 素材 ID |
| job_id | JobId | 否 | 任务 ID |
| kind | ProcessingKind | 否 | 理解或处理种类；列出理解结果时按此筛选 |
| detail | object | 否 | 事件详情 |

# 错误码

[指南 →](/docs/cloud/services/media/quickstart)

自有 API 返回 error.code、error.message、error.details。兼容接口返回 error.message，并通过 X-Cld-Error 响应头重复消息；非 ASCII 消息在响应头中使用百分号编码。

| 领域码 | 自有 HTTP | 兼容 HTTP | 可重试 |
| --- | --- | --- | --- |
| LIBRARY_NOT_FOUND | 404 | 404 | 否 |
| ASSET_NOT_FOUND | 404 | 404 | 否 |
| JOB_NOT_FOUND | 404 | 404 | 否 |
| UNDERSTANDING_NOT_FOUND | 404 | 404 | 否 |
| LIBRARY_INVALID_STATE | 409 | 400 | 否 |
| INVALID_PARAMS | 400 | 400 | 否 |
| INVALID_EXPRESSION | 400 | 400 | 否 |
| UNSUPPORTED | 400 | 400 | 否 |
| NOT_IMPLEMENTED | 501 | 400 | 否 |
| FILE_TOO_LARGE | 413 | 400 | 否 |
| FILE_EMPTY | 400 | 400 | 否 |
| UNSUPPORTED_MEDIA | 415 | 400 | 否 |
| FETCH_FAILED | 400 | 400 | 否 |
| LIMIT_EXCEEDED | 400 | 400 | 否 |
| CHUNK_INVALID | 400 | 400 | 否 |
| RATE_LIMITED | 429 | 420 | 是 |
| CAPACITY | 503 | 500 | 是 |
| UPSTREAM_FAILED | 502 | 500 | 是 |

可重试错误采用退避重试；其它错误先修正请求或资源状态。

## 模型配置错误 [#模型配置错误]

* 400 `INVALID_PARAMS`：模型调用 ID 不存在（`Model <id> is not available`）、vision 模型不支持图片输入，或 models 含未知角色、空白 ID 或不合法的值。
* 409 `LIBRARY_INVALID_STATE`：库中已有素材时更换 embedding，包括恢复默认值导致模型改变。消息为「库中已有素材时不能更换嵌入模型」。
* 502 `UPSTREAM_FAILED`：写入模型配置时无法查询模型目录；可退避重试。

# 知识库 API

（待译）

Knowledge turns uploaded files into searchable knowledge bases with asynchronous ingestion and inspectable text segments. Concepts and behavior follow OpenAI vector stores (stores, file attachments, batches and search), so OpenAI vector stores experience applies. Differences: search has no next page (native results count chunks, while the compatible URL groups files); auto ranking does not rerank, so request default-2024-11-15 for reranking; chunk sizes use estimated tokens rather than a model tokenizer; ingestion accepts at most 100000000 bytes per file and also supports images and XLSX; native deletion retains a readable, restorable store for seven days. Start with `praxis.knowledge.vectorStores.create`, passing file\_ids from File uploads to begin ingestion.

把文件加入知识库，按语义和关键词搜索相关分段。使用 API Key 作为 Bearer 凭据，建议从服务端调用。

`https://api.deepraxis.ai/knowledge/v1`

[快速开始：官方 Python SDK](/docs/cloud/services/knowledge/quickstart)

| 资源                                        | 用途               |
| ----------------------------------------- | ---------------- |
| [知识库](/docs/api/native/knowledge/stores)  | 创建、读取、更新、删除与恢复   |
| [文件](/docs/api/native/knowledge/files)    | 添加、读取、更新属性、移除与重试 |
| [批量](/docs/api/native/knowledge/batches)  | 成批添加文件、读取状态与取消   |
| [搜索](/docs/api/native/knowledge/search)   | 检索相关文本分段         |
| [分段](/docs/api/native/knowledge/segments) | 读取分段、位置与关键词      |
| [事件](/docs/api/native/knowledge/events)   | 读取知识库与文件处理事件     |

[错误码](/docs/api/native/knowledge/errors) · [上限与格式支持](/docs/cloud/services/knowledge/limits-and-errors) · [OpenAI vector stores](/docs/api/compatible/openai/vector-stores)

# 知识库

[快速开始：官方 Python SDK](/docs/cloud/services/knowledge/quickstart)

[基础地址与鉴权](/docs/api/native/knowledge)

路径中的 ID 使用已有资源的 ID。示例中的环境变量由调用者设置。

## 创建知识库 [#创建知识库]

`POST /knowledge/v1/vector_stores`

创建知识库。可用 file\_ids 添加已有 File 并异步入库；后续调用使用返回的 id。最小请求体：\{"name":"Refund policies"}。

### 请求体 [#请求体]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | string | 可选; 省略时为空字符串；不接受 null。; 最长字符数: 256; 默认: "" |
| metadata | object / null | 可选; 知识库自定义字符串元数据；省略或 null 得到空对象。; 默认: &#123;&#125; |
| expires_after | object / null | 可选; 从最近活动计算的过期策略；省略或 null 表示不自动过期。; 默认: null |
| expires_after (1).anchor | "last_active_at" | 必填; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必填; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| file_ids | string[] | 可选; 要加入的已有文件 ID；每库最多 10,000 个文件。 |
| chunking_strategy | object / object | 可选; auto 等同于每段 800 token、重叠 400 token。; 默认: &#123;"type":"auto"&#125; |
| chunking_strategy (1).type | "auto" | 必填; auto 使用默认静态分段：800 个估算 token，重叠 400 个。 |
| chunking_strategy (2).type | "static" | 必填; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (2).static | object | 必填; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (2).static.max_chunk_size_tokens | integer | 必填; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (2).static.chunk_overlap_tokens | integer | 必填; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| description | string | 可选; 不生效: 接受后丢弃，不保存也不返回；当前不校验类型。 |
| models | object / null | 可选; 要设置的模型角色。模型必须在模型目录中且支持该角色（embedding → openai.embeddings，rerank → cohere.rerank，query_rewrite → openai.chat.completions）。嵌入模型必须输出 1024 维向量。省略的角色不变；null 恢复全部默认。未知角色或空 ID 返回 400 INVALID_PARAMS。OpenAI 兼容接口传入此字段返回 400。; Praxis 扩展 |
| models (1).embedding | string / null | 可选; 给文件分段和查询生成向量。库中已有文件后不能更换。null 恢复默认（bge-m3）。 |
| models (1).rerank | string / null | 可选; ranking_options.ranker 为 default-2024-11-15 时用于重排结果。null 恢复默认（bge-reranker-base）。 |
| models (1).query_rewrite | string / null | 可选; 搜索设置 rewrite_query 时用于改写查询。null 恢复默认（qwen3.8-flash）。 |

### 请求示例 [#请求示例]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"name\":\"Refund policies\"}"
```

### 响应 [#响应]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| status | "in_progress" / "completed" / "expired" / "deleting" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。deleting 表示已软删除、等待永久清除。 |
| usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |
| purge_at | string / null | 可选; ISO 8601 格式的恢复截止时间；未软删除时为 null。 |
| models | object | 可选; 各角色生效的模型（Router 模型 ID）；未设置的角色使用默认模型。; Praxis 扩展 |
| models.embedding | string | 必有; 给文件分段和查询生成向量。库中已有文件后不能更换。默认 bge-m3。; 最短字符数: 1 |
| models.rerank | string | 必有; ranking_options.ranker 为 default-2024-11-15 时用于重排结果。默认 bge-reranker-base。; 最短字符数: 1 |
| models.query_rewrite | string | 必有; 搜索设置 rewrite_query 时用于改写查询。默认 qwen3.8-flash。; 最短字符数: 1 |
| praxis | object | 可选; 此知识库的原生生命周期与恢复信息。 |
| praxis.lifecycle | "provisioning" / "active" / "expired" / "deleted" / "failed" | 必有; provisioning 表示正在初始化；active 允许文件操作与搜索；expired 表示已过期；deleted 表示已软删除；failed 表示初始化失败。 |
| praxis.deleted_at | integer / null | 必有; 软删除的 Unix 秒时间戳；未软删除时为 null。 |
| praxis.purge_at | integer / null | 必有; 恢复截止的 Unix 秒时间戳；未软删除时为 null。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 列出知识库 [#列出知识库]

`GET /knowledge/v1/vector_stores`

列出调用方可见的知识库，默认最新在前。将 last\_id 作为 after 读取下一页，例如 ?limit=20。

### 参数 [#参数]

| 名称     | 位置与类型                        | 说明                                          |
| ------ | ---------------------------- | ------------------------------------------- |
| status | query: "active" / "deleting" | active 筛选活跃库；deleting 筛选软删除待清除的库。省略时排除软删除库。 |
| after  | query: string                | 上一页的 ID 游标。 最短字符数: 1                        |
| before | query: string                | 返回此 ID 之前的条目。 最短字符数: 1                      |
| limit  | query: integer               | 每页条数。 最小: 1; 最大: 100; 默认: 20                |
| order  | query: "asc" / "desc"        | 知识库和文件默认按创建时间降序；分段默认按序号升序。 默认: "desc"       |

### 请求示例 [#请求示例-1]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-1]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| data[].id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| data[].name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| data[].status | "in_progress" / "completed" / "expired" / "deleting" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。deleting 表示已软删除、等待永久清除。 |
| data[].usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| data[].file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| data[].file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| data[].file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| data[].file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| data[].file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| data[].file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| data[].created_at | integer | 必有; Unix 时间戳，单位秒。 |
| data[].last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| data[].expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| data[].expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| data[].expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| data[].expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| data[].metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |
| data[].purge_at | string / null | 可选; ISO 8601 格式的恢复截止时间；未软删除时为 null。 |
| data[].models | object | 可选; 各角色生效的模型（Router 模型 ID）；未设置的角色使用默认模型。; Praxis 扩展 |
| data[].models.embedding | string | 必有; 给文件分段和查询生成向量。库中已有文件后不能更换。默认 bge-m3。; 最短字符数: 1 |
| data[].models.rerank | string | 必有; ranking_options.ranker 为 default-2024-11-15 时用于重排结果。默认 bge-reranker-base。; 最短字符数: 1 |
| data[].models.query_rewrite | string | 必有; 搜索设置 rewrite_query 时用于改写查询。默认 qwen3.8-flash。; 最短字符数: 1 |
| data[].praxis | object | 可选; 此知识库的原生生命周期与恢复信息。 |
| data[].praxis.lifecycle | "provisioning" / "active" / "expired" / "deleted" / "failed" | 必有; provisioning 表示正在初始化；active 允许文件操作与搜索；expired 表示已过期；deleted 表示已软删除；failed 表示初始化失败。 |
| data[].praxis.deleted_at | integer / null | 必有; 软删除的 Unix 秒时间戳；未软删除时为 null。 |
| data[].praxis.purge_at | integer / null | 必有; 恢复截止的 Unix 秒时间戳；未软删除时为 null。 |
| first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取知识库 [#读取知识库]

`GET /knowledge/v1/vector_stores/{vector_store_id}`

使用创建或列表返回的 id 读取知识库。添加 ?expand=files 可同时返回附件首页。软删除的库在永久清除前仍可读取，status 为 deleting。

### 参数 [#参数-1]

| 名称                | 位置与类型             | 说明                                     |
| ----------------- | ----------------- | -------------------------------------- |
| vector\_store\_id | path: string      | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1   |
| expand            | query: "files"\[] | 两个地址均支持的 Praxis 扩展：files 附带文件首页；未知值忽略。 |
| expand\[]         | query: "files"\[] | 两个地址均支持的 Praxis 扩展：files 附带文件首页；未知值忽略。 |

### 请求示例 [#请求示例-2]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-2]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| (1).id | string | 必有; 资源 ID。; 最短字符数: 1 |
| (1).object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| (1).name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| (1).status | "in_progress" / "completed" / "expired" / "deleting" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。deleting 表示已软删除、等待永久清除。 |
| (1).usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| (1).file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| (1).file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| (1).file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| (1).file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| (1).file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| (1).file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| (1).created_at | integer | 必有; Unix 时间戳，单位秒。 |
| (1).last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| (1).expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| (1).expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| (1).expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| (1).expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| (1).metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |
| (1).purge_at | string / null | 可选; ISO 8601 格式的恢复截止时间；未软删除时为 null。 |
| (1).models | object | 可选; 各角色生效的模型（Router 模型 ID）；未设置的角色使用默认模型。; Praxis 扩展 |
| (1).models.embedding | string | 必有; 给文件分段和查询生成向量。库中已有文件后不能更换。默认 bge-m3。; 最短字符数: 1 |
| (1).models.rerank | string | 必有; ranking_options.ranker 为 default-2024-11-15 时用于重排结果。默认 bge-reranker-base。; 最短字符数: 1 |
| (1).models.query_rewrite | string | 必有; 搜索设置 rewrite_query 时用于改写查询。默认 qwen3.8-flash。; 最短字符数: 1 |
| (1).praxis | object | 可选; 此知识库的原生生命周期与恢复信息。 |
| (1).praxis.lifecycle | "provisioning" / "active" / "expired" / "deleted" / "failed" | 必有; provisioning 表示正在初始化；active 允许文件操作与搜索；expired 表示已过期；deleted 表示已软删除；failed 表示初始化失败。 |
| (1).praxis.deleted_at | integer / null | 必有; 软删除的 Unix 秒时间戳；未软删除时为 null。 |
| (1).praxis.purge_at | integer / null | 必有; 恢复截止的 Unix 秒时间戳；未软删除时为 null。 |
| (2).files | object | 可选; 仅在 expand=files 时返回文件首页。 |
| (2).files.object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| (2).files.data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| (2).files.data[].id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| (2).files.data[].object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| (2).files.data[].vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| (2).files.data[].status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| (2).files.data[].last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| (2).files.data[].last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| (2).files.data[].last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| (2).files.data[].usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| (2).files.data[].created_at | integer | 必有; Unix 时间戳，单位秒。 |
| (2).files.data[].chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| (2).files.data[].chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| (2).files.data[].chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| (2).files.data[].chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| (2).files.data[].chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| (2).files.data[].chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| (2).files.data[].attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| (2).files.data[].praxis | object | 可选; 原生入库进度与源文件统计。 |
| (2).files.data[].praxis.stage | "queued" / "parse" / "chunk" / "embed" / "index" / null | 必有; queued 表示等待；parse 提取文本；chunk 划分分段；embed 生成向量；index 建立检索索引。null 表示入库已不在进行中。 |
| (2).files.data[].praxis.deadline_at | integer / null | 必有; 入库截止的 Unix 秒时间戳；到点仍未完成的入库转为失败。 |
| (2).files.data[].praxis.filename | string | 必有; File 服务返回的源文件名。 |
| (2).files.data[].praxis.bytes | integer | 必有; 源文件字节数。; 最小: 0 |
| (2).files.data[].praxis.pages | integer / null | 必有; 成功入库后的解析页数；成功结果保存前为 null。 |
| (2).files.data[].praxis.chunk_count | integer | 必有; 已完成入库的分段数；完成前、失败或取消后为零。; 最小: 0 |
| (2).files.first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| (2).files.last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| (2).files.has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 更新知识库 [#更新知识库]

`POST /knowledge/v1/vector_stores/{vector_store_id}`

使用返回的 id 修改活跃知识库。省略的字段不变；metadata 替换整个对象。请求体示例：\{"name":"Refund policies"}。

### 参数 [#参数-2]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求体 [#请求体-1]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| name | string / null | 可选; null 将名称清空为空字符串；省略的字段不变。 |
| metadata | object / null | 可选; 替换全部元数据；null 清空为一个空对象。 |
| expires_after | object / null | 可选; null 取消自动过期。 |
| expires_after (1).anchor | "last_active_at" | 必填; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必填; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| models | object / null | 可选; 要设置的模型角色。模型必须在模型目录中且支持该角色（embedding → openai.embeddings，rerank → cohere.rerank，query_rewrite → openai.chat.completions）。嵌入模型必须输出 1024 维向量。省略的角色不变；null 恢复全部默认。未知角色或空 ID 返回 400 INVALID_PARAMS。OpenAI 兼容接口传入此字段返回 400。; Praxis 扩展 |
| models (1).embedding | string / null | 可选; 给文件分段和查询生成向量。库中已有文件后不能更换。null 恢复默认（bge-m3）。 |
| models (1).rerank | string / null | 可选; ranking_options.ranker 为 default-2024-11-15 时用于重排结果。null 恢复默认（bge-reranker-base）。 |
| models (1).query_rewrite | string / null | 可选; 搜索设置 rewrite_query 时用于改写查询。null 恢复默认（qwen3.8-flash）。 |

### 请求示例 [#请求示例-3]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"models\":{\"query_rewrite\":\"qwen3.8-flash\"}}"
```

### 响应 [#响应-3]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| status | "in_progress" / "completed" / "expired" / "deleting" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。deleting 表示已软删除、等待永久清除。 |
| usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |
| purge_at | string / null | 可选; ISO 8601 格式的恢复截止时间；未软删除时为 null。 |
| models | object | 可选; 各角色生效的模型（Router 模型 ID）；未设置的角色使用默认模型。; Praxis 扩展 |
| models.embedding | string | 必有; 给文件分段和查询生成向量。库中已有文件后不能更换。默认 bge-m3。; 最短字符数: 1 |
| models.rerank | string | 必有; ranking_options.ranker 为 default-2024-11-15 时用于重排结果。默认 bge-reranker-base。; 最短字符数: 1 |
| models.query_rewrite | string | 必有; 搜索设置 rewrite_query 时用于改写查询。默认 qwen3.8-flash。; 最短字符数: 1 |
| praxis | object | 可选; 此知识库的原生生命周期与恢复信息。 |
| praxis.lifecycle | "provisioning" / "active" / "expired" / "deleted" / "failed" | 必有; provisioning 表示正在初始化；active 允许文件操作与搜索；expired 表示已过期；deleted 表示已软删除；failed 表示初始化失败。 |
| praxis.deleted_at | integer / null | 必有; 软删除的 Unix 秒时间戳；未软删除时为 null。 |
| praxis.purge_at | integer / null | 必有; 恢复截止的 Unix 秒时间戳；未软删除时为 null。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 删除知识库 [#删除知识库]

`DELETE /knowledge/v1/vector_stores/{vector_store_id}`

软删除后保留 7 天；返回 status=deleting 和 ISO purge\_at，重复删除幂等。读取仍为 200，对象操作返回 409。

### 参数 [#参数-3]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求示例 [#请求示例-4]

```bash
curl -X DELETE "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-4]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| status | "in_progress" / "completed" / "expired" / "deleting" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。deleting 表示已软删除、等待永久清除。 |
| usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |
| purge_at | string / null | 可选; ISO 8601 格式的恢复截止时间；未软删除时为 null。 |
| models | object | 可选; 各角色生效的模型（Router 模型 ID）；未设置的角色使用默认模型。; Praxis 扩展 |
| models.embedding | string | 必有; 给文件分段和查询生成向量。库中已有文件后不能更换。默认 bge-m3。; 最短字符数: 1 |
| models.rerank | string | 必有; ranking_options.ranker 为 default-2024-11-15 时用于重排结果。默认 bge-reranker-base。; 最短字符数: 1 |
| models.query_rewrite | string | 必有; 搜索设置 rewrite_query 时用于改写查询。默认 qwen3.8-flash。; 最短字符数: 1 |
| praxis | object | 可选; 此知识库的原生生命周期与恢复信息。 |
| praxis.lifecycle | "provisioning" / "active" / "expired" / "deleted" / "failed" | 必有; provisioning 表示正在初始化；active 允许文件操作与搜索；expired 表示已过期；deleted 表示已软删除；failed 表示初始化失败。 |
| praxis.deleted_at | integer / null | 必有; 软删除的 Unix 秒时间戳；未软删除时为 null。 |
| praxis.purge_at | integer / null | 必有; 恢复截止的 Unix 秒时间戳；未软删除时为 null。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 恢复知识库 [#恢复知识库]

`POST /knowledge/v1/vector_stores/{vector_store_id}/restore`

恢复删除未满 7 天的知识库；可用库返回 409 VECTOR\_STORE\_INVALID\_STATE，不存在返回 404；请求体可为空。

### 参数 [#参数-4]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求示例 [#请求示例-5]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/restore" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-5]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store" | 必有; 对象标记；vector_store 表示知识库。 |
| name | string | 必有; 知识库显示名称；空字符串表示未设置名称。; 最长字符数: 256 |
| status | "in_progress" / "completed" / "expired" / "deleting" | 必有; in_progress 表示仍有文件入库中；completed 表示没有入库中的文件，不保证全部成功；expired 表示过期策略已生效。deleting 表示已软删除、等待永久清除。 |
| usage_bytes | integer | 必有; 已完成源文件的字节数之和。; 最小: 0 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| last_active_at | integer / null | 必有; 最近创建、添加文件或搜索的 Unix 秒时间戳；不可用时为 null。 |
| expires_after | object / null | 必有; 从最近活动开始计算的过期策略；null 表示不自动过期。 |
| expires_after (1).anchor | "last_active_at" | 必有; last_active_at 表示从最近活动时间开始计算过期。 |
| expires_after (1).days | integer | 必有; 自最近活动起的天数；添加文件和搜索会刷新活动时间。; 最小: 1; 最大: 365 |
| expires_at | integer / null | 必有; 预计过期的 Unix 秒时间戳；未设置过期策略时为 null。 |
| metadata | object | 必有; 最多 16 个键；键最多 64 字符；字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string |
| purge_at | string / null | 可选; ISO 8601 格式的恢复截止时间；未软删除时为 null。 |
| models | object | 可选; 各角色生效的模型（Router 模型 ID）；未设置的角色使用默认模型。; Praxis 扩展 |
| models.embedding | string | 必有; 给文件分段和查询生成向量。库中已有文件后不能更换。默认 bge-m3。; 最短字符数: 1 |
| models.rerank | string | 必有; ranking_options.ranker 为 default-2024-11-15 时用于重排结果。默认 bge-reranker-base。; 最短字符数: 1 |
| models.query_rewrite | string | 必有; 搜索设置 rewrite_query 时用于改写查询。默认 qwen3.8-flash。; 最短字符数: 1 |
| praxis | object | 可选; 此知识库的原生生命周期与恢复信息。 |
| praxis.lifecycle | "provisioning" / "active" / "expired" / "deleted" / "failed" | 必有; provisioning 表示正在初始化；active 允许文件操作与搜索；expired 表示已过期；deleted 表示已软删除；failed 表示初始化失败。 |
| praxis.deleted_at | integer / null | 必有; 软删除的 Unix 秒时间戳；未软删除时为 null。 |
| praxis.purge_at | integer / null | 必有; 恢复截止的 Unix 秒时间戳；未软删除时为 null。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 永久清除知识库 [#永久清除知识库]

`POST /knowledge/v1/vector_stores/{vector_store_id}/purge`

立即永久清除删除中的知识库，不可撤销；复用到期清理路径。可用库返回 409，不存在返回 404；请求体可为空。

### 参数 [#参数-5]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求示例 [#请求示例-6]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/purge" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-6]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 已永久清除的知识库 ID。 |
| object | "vector_store" | 必有; 对象标记；vector_store 表示此操作回执。 |
| purged | true | 必有; 确认已永久清除知识库及其索引内容。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

# 文件

[快速开始：官方 Python SDK](/docs/cloud/services/knowledge/quickstart)

[基础地址与鉴权](/docs/api/native/knowledge)

路径中的 ID 使用已有资源的 ID。示例中的环境变量由调用者设置。

## 添加文件 [#添加文件]

`POST /knowledge/v1/vector_stores/{vector_store_id}/files`

异步处理。重复加入同一文件返回已有记录，不应用新的属性或分段策略。

### 参数 [#参数]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求体 [#请求体]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| file_id | string | 必填; 上传文件返回的已有源 File ID；文件必须对调用方可见。; 最短字符数: 1 |
| attributes | object / null | 可选; 新附件的搜索筛选属性；省略或 null 表示不设置。重复加入已有文件不改变属性。 |
| chunking_strategy | object / object | 可选; auto 等同于每段 800 token、重叠 400 token。; 默认: &#123;"type":"auto"&#125; |
| chunking_strategy (1).type | "auto" | 必填; auto 使用默认静态分段：800 个估算 token，重叠 400 个。 |
| chunking_strategy (2).type | "static" | 必填; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (2).static | object | 必填; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (2).static.max_chunk_size_tokens | integer | 必填; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (2).static.chunk_overlap_tokens | integer | 必填; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |

### 请求示例 [#请求示例]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/files" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"file_id\":\"${FILE_ID}\"}"
```

### 响应 [#响应]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| praxis | object | 可选; 原生入库进度与源文件统计。 |
| praxis.stage | "queued" / "parse" / "chunk" / "embed" / "index" / null | 必有; queued 表示等待；parse 提取文本；chunk 划分分段；embed 生成向量；index 建立检索索引。null 表示入库已不在进行中。 |
| praxis.deadline_at | integer / null | 必有; 入库截止的 Unix 秒时间戳；到点仍未完成的入库转为失败。 |
| praxis.filename | string | 必有; File 服务返回的源文件名。 |
| praxis.bytes | integer | 必有; 源文件字节数。; 最小: 0 |
| praxis.pages | integer / null | 必有; 成功入库后的解析页数；成功结果保存前为 null。 |
| praxis.chunk_count | integer | 必有; 已完成入库的分段数；完成前、失败或取消后为零。; 最小: 0 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 列出文件 [#列出文件]

`GET /knowledge/v1/vector_stores/{vector_store_id}/files`

列出附件及入库状态，默认最新附件在前。使用 last\_id 作为 after 继续查询；?filter=failed 筛选可重新入库的失败文件。

### 参数 [#参数-1]

| 名称                | 位置与类型                                                        | 说明                                                                                    |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| vector\_store\_id | path: string                                                 | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1                                                  |
| after             | query: string                                                | 上一页的 ID 游标。 最短字符数: 1                                                                  |
| before            | query: string                                                | 返回此 ID 之前的条目。 最短字符数: 1                                                                |
| limit             | query: integer                                               | 每页条数。 最小: 1; 最大: 100; 默认: 20                                                          |
| order             | query: "asc" / "desc"                                        | 知识库和文件默认按创建时间降序；分段默认按序号升序。 默认: "desc"                                                 |
| filter            | query: "in\_progress" / "completed" / "failed" / "cancelled" | in\_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。省略时包含全部状态。 |

### 请求示例 [#请求示例-1]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/files" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-1]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| data[].id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| data[].object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| data[].vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| data[].last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| data[].last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| data[].last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| data[].usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| data[].created_at | integer | 必有; Unix 时间戳，单位秒。 |
| data[].chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| data[].chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| data[].chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| data[].chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| data[].chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| data[].chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| data[].attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| data[].praxis | object | 可选; 原生入库进度与源文件统计。 |
| data[].praxis.stage | "queued" / "parse" / "chunk" / "embed" / "index" / null | 必有; queued 表示等待；parse 提取文本；chunk 划分分段；embed 生成向量；index 建立检索索引。null 表示入库已不在进行中。 |
| data[].praxis.deadline_at | integer / null | 必有; 入库截止的 Unix 秒时间戳；到点仍未完成的入库转为失败。 |
| data[].praxis.filename | string | 必有; File 服务返回的源文件名。 |
| data[].praxis.bytes | integer | 必有; 源文件字节数。; 最小: 0 |
| data[].praxis.pages | integer / null | 必有; 成功入库后的解析页数；成功结果保存前为 null。 |
| data[].praxis.chunk_count | integer | 必有; 已完成入库的分段数；完成前、失败或取消后为零。; 最小: 0 |
| first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取文件 [#读取文件]

`GET /knowledge/v1/vector_stores/{vector_store_id}/files/{file_id}`

使用添加附件或附件列表返回的 id 读取文件。可轮询此操作，直到 status 离开 in\_progress 后确认入库结果。

### 参数 [#参数-2]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求示例 [#请求示例-2]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-2]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| praxis | object | 可选; 原生入库进度与源文件统计。 |
| praxis.stage | "queued" / "parse" / "chunk" / "embed" / "index" / null | 必有; queued 表示等待；parse 提取文本；chunk 划分分段；embed 生成向量；index 建立检索索引。null 表示入库已不在进行中。 |
| praxis.deadline_at | integer / null | 必有; 入库截止的 Unix 秒时间戳；到点仍未完成的入库转为失败。 |
| praxis.filename | string | 必有; File 服务返回的源文件名。 |
| praxis.bytes | integer | 必有; 源文件字节数。; 最小: 0 |
| praxis.pages | integer / null | 必有; 成功入库后的解析页数；成功结果保存前为 null。 |
| praxis.chunk_count | integer | 必有; 已完成入库的分段数；完成前、失败或取消后为零。; 最小: 0 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 更新文件属性 [#更新文件属性]

`POST /knowledge/v1/vector_stores/{vector_store_id}/files/{file_id}`

替换已有附件的搜索筛选属性，不重新入库。使用附件 id。请求体示例：\{"attributes":\{"category":"refund"}}；null 清空属性。

### 参数 [#参数-3]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求体 [#请求体-1]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| attributes | object / null | 可选; 替换全部搜索筛选属性；null 清空属性。 |

### 请求示例 [#请求示例-3]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"attributes\":{\"category\":\"refund\"}}"
```

### 响应 [#响应-3]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| praxis | object | 可选; 原生入库进度与源文件统计。 |
| praxis.stage | "queued" / "parse" / "chunk" / "embed" / "index" / null | 必有; queued 表示等待；parse 提取文本；chunk 划分分段；embed 生成向量；index 建立检索索引。null 表示入库已不在进行中。 |
| praxis.deadline_at | integer / null | 必有; 入库截止的 Unix 秒时间戳；到点仍未完成的入库转为失败。 |
| praxis.filename | string | 必有; File 服务返回的源文件名。 |
| praxis.bytes | integer | 必有; 源文件字节数。; 最小: 0 |
| praxis.pages | integer / null | 必有; 成功入库后的解析页数；成功结果保存前为 null。 |
| praxis.chunk_count | integer | 必有; 已完成入库的分段数；完成前、失败或取消后为零。; 最小: 0 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 移除文件 [#移除文件]

`DELETE /knowledge/v1/vector_stores/{vector_store_id}/files/{file_id}`

返回后立即不再搜索到该文件；不会删除源文件。

### 参数 [#参数-4]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求示例 [#请求示例-4]

```bash
curl -X DELETE "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-4]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.file.deleted" | 必有; 对象标记；vector_store.file.deleted 表示此操作回执。 |
| deleted | true | 必有; 确认已从此知识库移出；源 File 未删除。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取抽取内容 [#读取抽取内容]

`GET /knowledge/v1/vector_stores/{vector_store_id}/files/{file_id}/content`

抽取文本按分段返回，可能重叠。图片内容可能是生成的描述，并非逐字 OCR。

### 参数 [#参数-5]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求示例 [#请求示例-5]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}/content" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-5]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "vector_store.file_content.page" | 必有; 对象标记；vector_store.file_content.page 表示提取的文件内容。 |
| data | object[] | 必有; 按分段序号排列的全部现存文本分段；相邻分段可能重叠。 |
| data[].type | "text" | 必有; text 表示提取出的文本分段。 |
| data[].text | string | 必有; 此分段的提取文本；可能与相邻分段重叠。 |
| has_more | false | 必有; 恒为 false；此响应返回全部现存分段。 |
| next_page | null | 必有; 恒为 null；提取内容不分页。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 重试失败文件 [#重试失败文件]

`POST /knowledge/v1/vector_stores/{vector_store_id}/files/{file_id}/retry`

仅重试 failed 文件；其他状态返回 409 FILE\_INVALID\_STATE。本次实测尚未覆盖失败后的重试。

### 参数 [#参数-6]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |

### 请求示例 [#请求示例-6]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}/retry" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-6]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |
| chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| praxis | object | 可选; 原生入库进度与源文件统计。 |
| praxis.stage | "queued" / "parse" / "chunk" / "embed" / "index" / null | 必有; queued 表示等待；parse 提取文本；chunk 划分分段；embed 生成向量；index 建立检索索引。null 表示入库已不在进行中。 |
| praxis.deadline_at | integer / null | 必有; 入库截止的 Unix 秒时间戳；到点仍未完成的入库转为失败。 |
| praxis.filename | string | 必有; File 服务返回的源文件名。 |
| praxis.bytes | integer | 必有; 源文件字节数。; 最小: 0 |
| praxis.pages | integer / null | 必有; 成功入库后的解析页数；成功结果保存前为 null。 |
| praxis.chunk_count | integer | 必有; 已完成入库的分段数；完成前、失败或取消后为零。; 最小: 0 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

# 批量

[快速开始：官方 Python SDK](/docs/cloud/services/knowledge/quickstart)

[基础地址与鉴权](/docs/api/native/knowledge)

路径中的 ID 使用已有资源的 ID。示例中的环境变量由调用者设置。

## 创建文件批次 [#创建文件批次]

`POST /knowledge/v1/vector_stores/{vector_store_id}/file_batches`

批量添加已有 File 并异步入库。file\_ids 与 files 必须且只能提供一个；files 支持逐文件设置。已有附件直接复用。使用返回的批次 id 查询进度。

### 参数 [#参数]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求体 [#请求体]

file\_ids 与 files 必须且只能提供一个。已有文件直接复用，不修改属性或分段策略。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| (1).file_ids | string[] | 必填; 使用共同属性和分段设置的已有 File ID 列表。file_ids 与 files 二选一。; 最少条数: 1; 最多条数: 500 |
| (1).attributes | object / null | 可选; 用于每个新附件的搜索筛选属性；省略或 null 表示不设置。 |
| (1).chunking_strategy | object / object | 可选; auto 等同于每段 800 token、重叠 400 token。; 默认: &#123;"type":"auto"&#125; |
| (1).chunking_strategy (1).type | "auto" | 必填; auto 使用默认静态分段：800 个估算 token，重叠 400 个。 |
| (1).chunking_strategy (2).type | "static" | 必填; static 表示使用显式分段大小与重叠设置。 |
| (1).chunking_strategy (2).static | object | 必填; 以估算 token 数表示的分段大小与重叠限制。 |
| (1).chunking_strategy (2).static.max_chunk_size_tokens | integer | 必填; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| (1).chunking_strategy (2).static.chunk_overlap_tokens | integer | 必填; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| (2).files | object[] | 必填; 分别指定属性和分段设置的附件列表；忽略顶层 attributes 与 chunking_strategy。; 最少条数: 1; 最多条数: 500 |
| (2).files[].file_id | string | 必填; 上传文件返回的已有源 File ID；文件必须对调用方可见。; 最短字符数: 1 |
| (2).files[].attributes | object | 可选; 用于搜索筛选的文件属性。最多 16 个键，键最多 64 字符，字符串值最多 512 字符。; 最多键数: 16; 键最多 64 字符; 值: string / number / boolean |
| (2).files[].chunking_strategy | object / object | 可选; auto 等同于每段 800 token、重叠 400 token。; 默认: &#123;"type":"auto"&#125; |
| (2).files[].chunking_strategy (1).type | "auto" | 必填; auto 使用默认静态分段：800 个估算 token，重叠 400 个。 |
| (2).files[].chunking_strategy (2).type | "static" | 必填; static 表示使用显式分段大小与重叠设置。 |
| (2).files[].chunking_strategy (2).static | object | 必填; 以估算 token 数表示的分段大小与重叠限制。 |
| (2).files[].chunking_strategy (2).static.max_chunk_size_tokens | integer | 必填; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| (2).files[].chunking_strategy (2).static.chunk_overlap_tokens | integer | 必填; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| (2).attributes | JSON | 可选; 不生效: 使用 files 时不生效。 |
| (2).chunking_strategy | JSON | 可选; 不生效: 使用 files 时不生效。 |

### 请求示例 [#请求示例]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/file_batches" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"file_ids\":[\"${FILE_ID}\"]}"
```

### 响应 [#响应]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.files_batch" | 必有; 对象标记；vector_store.files_batch 表示批量附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; cancelled 表示批次已取消；否则 in_progress 表示仍有成员入库中，failed 表示入库结束且有失败成员，completed 表示无入库中或失败成员。取消终态批次不会改变它。 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取文件批次 [#读取文件批次]

`GET /knowledge/v1/vector_stores/{vector_store_id}/file_batches/{batch_id}`

读取此知识库中创建的批次，包括当前状态和文件计数。使用创建批次返回的 id 监测入库结果。

### 参数 [#参数-1]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| batch\_id         | path: string | 必填；此知识库创建批次时返回的文件批次 ID。 最短字符数: 1     |

### 请求示例 [#请求示例-1]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/file_batches/${BATCH_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-1]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.files_batch" | 必有; 对象标记；vector_store.files_batch 表示批量附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; cancelled 表示批次已取消；否则 in_progress 表示仍有成员入库中，failed 表示入库结束且有失败成员，completed 表示无入库中或失败成员。取消终态批次不会改变它。 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 取消文件批次 [#取消文件批次]

`POST /knowledge/v1/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel`

只取消处理中的批次和文件。已完成、失败或已取消的批次原样返回（200，幂等），计数不变。

### 参数 [#参数-2]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| batch\_id         | path: string | 必填；此知识库创建批次时返回的文件批次 ID。 最短字符数: 1     |

### 请求示例 [#请求示例-2]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/file_batches/${BATCH_ID}/cancel" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-2]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| object | "vector_store.files_batch" | 必有; 对象标记；vector_store.files_batch 表示批量附件。 |
| vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; cancelled 表示批次已取消；否则 in_progress 表示仍有成员入库中，failed 表示入库结束且有失败成员，completed 表示无入库中或失败成员。取消终态批次不会改变它。 |
| file_counts | object | 必有; 仍属于该库或批次的附件数量，按入库状态分组。 |
| file_counts.in_progress | integer | 必有; 等待或正在入库的文件数。; 最小: 0 |
| file_counts.completed | integer | 必有; 已完成入库的文件数。; 最小: 0 |
| file_counts.failed | integer | 必有; 入库失败的文件数。; 最小: 0 |
| file_counts.cancelled | integer | 必有; 因批次取消而停止入库的文件数。; 最小: 0 |
| file_counts.total | integer | 必有; 全部入库状态的附件总数。; 最小: 0 |
| created_at | integer | 必有; Unix 时间戳，单位秒。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 列出批次文件 [#列出批次文件]

`GET /knowledge/v1/vector_stores/{vector_store_id}/file_batches/{batch_id}/files`

列出指定批次仍在库中的附件，默认最新附件在前。使用批次创建返回的 id；?filter=failed 查看失败文件，last\_id 可作为下一页 after。

### 参数 [#参数-3]

| 名称                | 位置与类型                                                        | 说明                                                                                    |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| vector\_store\_id | path: string                                                 | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1                                                  |
| batch\_id         | path: string                                                 | 必填；此知识库创建批次时返回的文件批次 ID。 最短字符数: 1                                                      |
| after             | query: string                                                | 上一页的 ID 游标。 最短字符数: 1                                                                  |
| before            | query: string                                                | 返回此 ID 之前的条目。 最短字符数: 1                                                                |
| limit             | query: integer                                               | 每页条数。 最小: 1; 最大: 100; 默认: 20                                                          |
| order             | query: "asc" / "desc"                                        | 知识库和文件默认按创建时间降序；分段默认按序号升序。 默认: "desc"                                                 |
| filter            | query: "in\_progress" / "completed" / "failed" / "cancelled" | in\_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。省略时包含全部状态。 |

### 请求示例 [#请求示例-3]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/file_batches/${BATCH_ID}/files" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-3]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| data[].id | string | 必有; 与源文件相同的 ID。; 最短字符数: 1 |
| data[].object | "vector_store.file" | 必有; 对象标记；vector_store.file 表示知识库中的附件。 |
| data[].vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].status | "in_progress" / "completed" / "cancelled" / "failed" | 必有; in_progress 表示等待或正在入库；completed 表示可检索；failed 表示入库失败；cancelled 表示批次取消已停止入库。 |
| data[].last_error | object / null | 必有; 入库失败详情；未失败、成功完成或重新入库时为 null。 |
| data[].last_error (1).code | "server_error" / "unsupported_file" / "invalid_file" | 必有; unsupported_file 表示不支持的文件类型；invalid_file 表示加密、空文件或超过解析 token 上限；server_error 表示其它入库失败或超过截止时间。 |
| data[].last_error (1).message | string | 必有; 与 code 对应的入库失败说明。 |
| data[].usage_bytes | integer | 必有; 完成后计入源文件字节数；处理中、失败或已取消时为零。; 最小: 0 |
| data[].created_at | integer | 必有; Unix 时间戳，单位秒。 |
| data[].chunking_strategy | object / object | 必有; 此附件已保存的分段策略；auto 输入返回为具体 static 设置。 |
| data[].chunking_strategy (1).type | "static" | 必有; static 表示使用显式分段大小与重叠设置。 |
| data[].chunking_strategy (1).static | object | 必有; 以估算 token 数表示的分段大小与重叠限制。 |
| data[].chunking_strategy (1).static.max_chunk_size_tokens | integer | 必有; 每段的估算 token 数。; 最小: 100; 最大: 4096 |
| data[].chunking_strategy (1).static.chunk_overlap_tokens | integer | 必有; 不得超过 max_chunk_size_tokens 的一半。; 最小: 0; 最大: 2048 |
| data[].chunking_strategy (2).type | "other" | 必有; other identifies a stored strategy whose chunk-size settings are unavailable. |
| data[].attributes | object / null | 必有; 用于搜索筛选的文件属性；null 表示未设置。 |
| data[].praxis | object | 可选; 原生入库进度与源文件统计。 |
| data[].praxis.stage | "queued" / "parse" / "chunk" / "embed" / "index" / null | 必有; queued 表示等待；parse 提取文本；chunk 划分分段；embed 生成向量；index 建立检索索引。null 表示入库已不在进行中。 |
| data[].praxis.deadline_at | integer / null | 必有; 入库截止的 Unix 秒时间戳；到点仍未完成的入库转为失败。 |
| data[].praxis.filename | string | 必有; File 服务返回的源文件名。 |
| data[].praxis.bytes | integer | 必有; 源文件字节数。; 最小: 0 |
| data[].praxis.pages | integer / null | 必有; 成功入库后的解析页数；成功结果保存前为 null。 |
| data[].praxis.chunk_count | integer | 必有; 已完成入库的分段数；完成前、失败或取消后为零。; 最小: 0 |
| first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

# 搜索

[快速开始：官方 Python SDK](/docs/cloud/services/knowledge/quickstart)

[基础地址与鉴权](/docs/api/native/knowledge)

路径中的 ID 使用已有资源的 ID。示例中的环境变量由调用者设置。

## 搜索知识库 [#搜索知识库]

`POST /knowledge/v1/vector_stores/{vector_store_id}/search`

按分段返回，同一文件可出现多次。最多 50 条，没有下一页。

### 参数 [#参数]

| 名称                | 位置与类型        | 说明                                   |
| ----------------- | ------------ | ------------------------------------ |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |

### 请求体 [#请求体]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| query | string / string[] | 必填; 非空白文本；多个查询以换行连接后共同搜索。 |
| filters | object / object / object | 可选; 按类型严格匹配文件属性；根条件以下最多嵌套 20 层。 |
| filters (1).type | "eq" / "ne" / "gt" / "gte" / "lt" / "lte" | 必填; eq 等于，ne 不等于，gt 大于，gte 大于等于，lt 小于，lte 小于等于；属性必须存在且值类型一致。 |
| filters (1).key | string | 必填; 要比较的文件属性原始键名，标点也是键名的一部分。; 最短字符数: 1 |
| filters (1).value | string / number / boolean | 必填; 不进行类型转换的比较值。 |
| filters (2).type | "in" / "nin" | 必填; in 匹配数组中的值；nin 匹配不在数组中的值。属性不存在时均不匹配。 |
| filters (2).key | string | 必填; 要比较的文件属性原始键名，标点也是键名的一部分。; 最短字符数: 1 |
| filters (2).value | string / number[] | 必填; 不进行类型转换的字符串或数值成员列表。 |
| filters (3).type | "and" / "or" | 必填; and 要求所有子条件匹配；or 要求至少一个子条件匹配。 |
| filters (3).filters | object / object / object[] | 必填; 按选定 and/or 运算符组合的非空子条件列表。; 最少条数: 1 |
| filters (3).filters[] | object / object / object | 递归使用同一筛选结构，嵌套上限 20 层。 |
| max_num_results | integer | 可选; 最多返回的分段数，不是不同文件数。; 最小: 1; 最大: 50; 默认: 10 |
| rewrite_query | boolean | 可选; 支持: 为 true 时，先用该库 query_rewrite 角色的模型把每条查询改写为简洁的检索查询；检索使用改写结果，search_query 返回改写后的查询。每次改写是一次小模型调用，按模型用量计费。改写失败、超时（5 秒）或为空时，该条查询回退为原文，搜索照常完成。省略或为 false 时不调用模型。 |
| next_page | string | 可选; 不生效: 搜索不支持翻页；提供游标不生效。 |
| ranking_options | object | 可选; 控制结果排序与纳入结果的最低分数。 |
| ranking_options.ranker | "none" / "auto" / "default-2024-11-15" | 可选; 只有 default-2024-11-15 请求重排；none、auto 和省略时使用初始排序。尚未单独实测重排效果。 |
| ranking_options.score_threshold | number | 可选; 最低分数；分数不是相关性概率。尚未单独实测阈值效果。; 最小: 0; 最大: 1; 默认: 0 |
| ranking_options.hybrid_search | object | 可选; Praxis 扩展。两个权重均须提供，必须非负且总和大于 0；省略时使用 0.7 / 0.3。; Praxis 扩展 |
| ranking_options.hybrid_search.embedding_weight | number | 必填; 语义检索相对权重；零表示禁用语义检索。; 最小: 0; 默认: 0.7 |
| ranking_options.hybrid_search.text_weight | number | 必填; 关键词检索相对权重；零表示禁用关键词检索。; 最小: 0; 默认: 0.3 |
| praxis | object | 可选; 设置 explain=true 返回分数和关键词解释。; Praxis 扩展 |
| praxis.explain | boolean | 可选; true 请求每条结果的分数、排名与关键词解释。; 默认: false |

### 请求示例 [#请求示例]

```bash
curl -X POST "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/search" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"query\":\"When will I receive my refund?\",\"max_num_results\":5,\"praxis\":{\"explain\":true}}"
```

### 响应 [#响应]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "vector_store.search_results.page" | 必有; 对象标记；vector_store.search_results.page 表示搜索结果页。 |
| search_query | string[] | 必有; 实际用于检索的查询，与输入一一对应；rewrite_query 为 true 时为改写后的查询，否则原样返回。 |
| data | object[] | 必有; 每个命中分段返回一条；同一 file_id 可重复出现。 |
| data[].file_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].filename | string | 必有; 命中文件的源文件名。 |
| data[].score | number | 必有; 此分段的相关排序分数，限制在 0 到 1；不是概率。; 最小: 0; 最大: 1 |
| data[].attributes | object / null | 必有; 用于筛选的当前文件属性；未设置时为 null。 |
| data[].content | object[] | 必有; 命中分段文本与源文坐标；原生结果每条包含一个分段。 |
| data[].content[].type | "text" | 必有; text 表示提取出的文本分段。 |
| data[].content[].text | string | 必有; 命中分段的提取文本，可能与相邻分段重叠。 |
| data[].content[].chunk_id | string | 可选; 资源 ID。; 最短字符数: 1 |
| data[].content[].page | integer / null | 可选; 此段起点所在的源文页码，从一开始；无页码映射时为 null。 |
| data[].content[].span | integer[] | 可选; 以 UTF-16 代码单元表示的起止位置。; 最少条数: 2; 最多条数: 2 |
| data[].praxis | object | 可选; 原生搜索解释；仅请求 praxis.explain 时返回。 |
| data[].praxis.explain | object | 必有; 每个命中分段的检索分数、排名与匹配词。 |
| data[].praxis.explain.semantic_score | number / null | 必有; 此段语义检索分数；不在语义候选中时为 null。 |
| data[].praxis.explain.keyword_score | number / null | 必有; 此段关键词检索分数；不在关键词候选中时为 null。 |
| data[].praxis.explain.rerank_score | number / null | 必有; 重排模型分数；未重排时为 null。 |
| data[].praxis.explain.semantic_rank | integer / null | 必有; 语义候选中的排名，从一开始；该路未召回时为 null。 |
| data[].praxis.explain.keyword_rank | integer / null | 必有; 关键词候选中的排名，从一开始；该路未召回时为 null。 |
| data[].praxis.explain.rank_before_rerank | integer | 必有; One-based fused rank before reranking; without reranking, the position among returned filtered results.; 最小: 1 |
| data[].praxis.explain.query_terms | string[] | 必有; 解释使用的归一化查询词，包括相邻汉字组成的双字词。 |
| data[].praxis.explain.matched_terms | string[] | 必有; 归一化分段文本中出现的查询词。 |
| has_more | boolean | 必有; 过滤后的分段数超过 max_num_results 时为 true；next_page 仍为 null。; 支持:  |
| next_page | null | 必有; 不生效: 恒为 null，没有下一页搜索结果。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

# 分段

[快速开始：官方 Python SDK](/docs/cloud/services/knowledge/quickstart)

[基础地址与鉴权](/docs/api/native/knowledge)

路径中的 ID 使用已有资源的 ID。示例中的环境变量由调用者设置。

## 列出文件分段 [#列出文件分段]

`GET /knowledge/v1/vector_stores/{vector_store_id}/files/{file_id}/segments`

列出附件已有分段，默认按分段序号升序。使用附件 id，并将 last\_id 作为 after 继续查询；返回的分段 id 可单独读取。

### 参数 [#参数]

| 名称                | 位置与类型                 | 说明                                   |
| ----------------- | --------------------- | ------------------------------------ |
| vector\_store\_id | path: string          | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1 |
| file\_id          | path: string          | 必填；添加附件或附件列表返回的源 File ID。 最短字符数: 1   |
| after             | query: string         | 上一页的 ID 游标。 最短字符数: 1                 |
| before            | query: string         | 返回此 ID 之前的条目。 最短字符数: 1               |
| limit             | query: integer        | 每页条数。 最小: 1; 最大: 100; 默认: 20         |
| order             | query: "asc" / "desc" | 知识库和文件默认按创建时间降序；分段默认按序号升序。 默认: "asc" |

### 请求示例 [#请求示例]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/files/${FILE_ID}/segments" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| object | "list" | 必有; 对象标记；list 表示游标分页集合。 |
| data | object[] | 必有; 按请求顺序返回的当前页条目。 |
| data[].id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].file_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].index | integer | 必有; 此段在源文中的序号，从零开始。; 最小: 0 |
| data[].text | string | 必有; 此分段覆盖的提取文本；相邻分段可能重叠。 |
| data[].tokens | integer | 必有; 此段的估算 token 数，不是模型分词器计数。; 最小: 0 |
| data[].page | integer / null | 必有; 分段起点所在源文页码，从一开始；无页码映射时为 null。 |
| data[].span | integer[] | 必有; 以 UTF-16 代码单元表示的起止位置。; 最少条数: 2; 最多条数: 2 |
| data[].overlap_prev_tokens | integer | 必有; 与前段重叠的估算 token 数；首段为零。; 最小: 0 |
| data[].overlap_next_tokens | integer | 必有; 与后段重叠的估算 token 数；末段为零。; 最小: 0 |
| first_id | string / null | 必有; 本页首项的 ID；空页为 null。 |
| last_id | string / null | 必有; 本页末项的 ID，可作为 after 继续查询；空页为 null。 |
| has_more | boolean | 必有; 当前游标范围内，本页之后是否还有条目。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

## 读取分段 [#读取分段]

`GET /knowledge/v1/vector_stores/{vector_store_id}/segments/{chunk_id}`

读取一个分段及其词频统计。chunk\_id 来自分段列表或原生搜索 content；分段必须属于此知识库。

### 参数 [#参数-1]

| 名称                | 位置与类型        | 说明                                      |
| ----------------- | ------------ | --------------------------------------- |
| vector\_store\_id | path: string | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1    |
| chunk\_id         | path: string | 必填；分段列表或原生搜索 content 返回的分段 ID。 最短字符数: 1 |

### 请求示例 [#请求示例-1]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/segments/${CHUNK_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应-1]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 必有; 资源 ID。; 最短字符数: 1 |
| file_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| index | integer | 必有; 此段在源文中的序号，从零开始。; 最小: 0 |
| text | string | 必有; 此分段覆盖的提取文本；相邻分段可能重叠。 |
| tokens | integer | 必有; 此段的估算 token 数，不是模型分词器计数。; 最小: 0 |
| page | integer / null | 必有; 分段起点所在源文页码，从一开始；无页码映射时为 null。 |
| span | integer[] | 必有; 以 UTF-16 代码单元表示的起止位置。; 最少条数: 2; 最多条数: 2 |
| overlap_prev_tokens | integer | 必有; 与前段重叠的估算 token 数；首段为零。; 最小: 0 |
| overlap_next_tokens | integer | 必有; 与后段重叠的估算 token 数；末段为零。; 最小: 0 |
| terms | object[] | 必有; 此段出现的关键词及其段内频次、全库包含段数。 |
| terms[].term | string | 必有; 小写文本词；连续汉字还生成相邻双字词。 |
| terms[].count | integer | 必有; 该词在此段中的出现次数。; 最小: 0 |
| terms[].chunks_in_store | integer | 必有; 此库索引中包含该词的分段数。; 最小: 0 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

# 事件

[快速开始：官方 Python SDK](/docs/cloud/services/knowledge/quickstart)

[基础地址与鉴权](/docs/api/native/knowledge)

路径中的 ID 使用已有资源的 ID。示例中的环境变量由调用者设置。

## 列出事件 [#列出事件]

`GET /knowledge/v1/vector_stores/{vector_store_id}/events`

按序号升序读取此知识库事件，软删除期间仍可读取。将 next\_seq 作为 after\_seq 继续查询；next\_seq 为 null 表示当前已到末尾。例如 ?after\_seq=0\&limit=20。

### 参数 [#参数]

| 名称                | 位置与类型          | 说明                                            |
| ----------------- | -------------- | --------------------------------------------- |
| vector\_store\_id | path: string   | 必填；创建或列表返回的知识库 ID；不要使用显示名称。 最短字符数: 1          |
| after\_seq        | query: integer | 返回 seq 更大的事件；使用 next\_seq 继续。当前忽略非数字文本。 默认: 0 |
| limit             | query: integer | 每页条数。 最小: 1; 最大: 100; 默认: 20                  |

### 请求示例 [#请求示例]

```bash
curl -X GET "https://api.deepraxis.ai/knowledge/v1/vector_stores/${VECTOR_STORE_ID}/events" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应]

HTTP 200

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| data | object[] | 必有; seq 大于 after_seq 的事件，按 seq 升序返回。 |
| data[].seq | integer | 必有; 库内递增事件序号；将返回的 next_seq 作为 after_seq 继续查询。; 最小: 1 |
| data[].id | string | 必有; 服务端生成的事件 UUID。 |
| data[].type | "vector_store.created" / "vector_store.updated" / "vector_store.expired" / "vector_store.deleted" / "vector_store.restored" / "file.attached" / "file.stage_changed" / "file.completed" / "file.failed" / "file.cancelled" / "file.removed" / "batch.created" / "batch.completed" / "batch.cancelled" | 必有; 此知识库记录的库、文件入库或批次事件类别。 |
| data[].processed_at | integer | 必有; Unix 时间戳，单位秒。 |
| data[].vector_store_id | string | 必有; 资源 ID。; 最短字符数: 1 |
| data[].file_id | string / null | 必有; 关联的源 File ID；无关联文件时为 null。 |
| data[].batch_id | string / null | 必有; 关联的文件批次 ID；无关联批次时为 null。 |
| data[].data | object | 必有; 事件详情；阶段变化含 stage，入库失败含 code，其它事件可为空对象。 |
| next_seq | integer / null | 必有; 作为下一页的 after_seq；null 表示没有后续。 |

[错误码与错误对象](/docs/api/native/knowledge/errors)

# 错误

| HTTP | code                          | 处理建议                                        |
| ---- | ----------------------------- | ------------------------------------------- |
| 400  | INVALID\_PARAMS               | 字段、筛选条件或分页参数无效。                             |
| 400  | LIMIT\_EXCEEDED               | 超过容量或批次上限。                                  |
| 401  | UNAUTHENTICATED               | 检查 API Key；兼容响应 code 为 null。                |
| 404  | VECTOR\_STORE\_NOT\_FOUND     | 知识库不存在或不可访问。                                |
| 404  | FILE\_NOT\_FOUND              | 源文件不存在。                                     |
| 404  | FILE\_NOT\_IN\_STORE          | 文件未加入此知识库。                                  |
| 404  | BATCH\_NOT\_FOUND             | 批次不存在。                                      |
| 404  | CHUNK\_NOT\_FOUND             | 分段不存在。                                      |
| 409  | VECTOR\_STORE\_INVALID\_STATE | 知识库当前状态不允许该操作。                              |
| 409  | FILE\_INVALID\_STATE          | 仅 failed 文件可以重试。                            |
| 413  | PAYLOAD\_TOO\_LARGE           | JSON 请求超过 1,000,000 字节；兼容响应的 code 可能为 null。 |
| 429  | RATE\_LIMITED                 | 稍后重试。                                       |
| 500  | — / null                      | 服务内部错误；保留请求 ID 并稍后重试。                       |
| 501  | NOT\_IMPLEMENTED              | 操作尚未实现。                                     |
| 503  | PROVIDER\_UNAVAILABLE         | 处理服务暂不可用，可稍后重试。                             |

## 原生 API 错误对象 [#原生-api-错误对象]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| error | object | 必有 |
| error.code | "INVALID_PARAMS" / "LIMIT_EXCEEDED" / "UNAUTHENTICATED" / "VECTOR_STORE_NOT_FOUND" / "FILE_NOT_FOUND" / "FILE_NOT_IN_STORE" / "BATCH_NOT_FOUND" / "CHUNK_NOT_FOUND" / "VECTOR_STORE_INVALID_STATE" / "FILE_INVALID_STATE" / "PAYLOAD_TOO_LARGE" / "RATE_LIMITED" / "NOT_IMPLEMENTED" / "PROVIDER_UNAVAILABLE" | 可选 |
| error.message | string | 必有 |
| error.details | string / null | 可选 |

## OpenAI 兼容错误对象 [#openai-兼容错误对象]

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| error | object | 必有 |
| error.message | string | 必有 |
| error.type | "invalid_request_error" / "not_found_error" / "rate_limit_error" / "server_error" | 必有 |
| error.param | string / null | 必有 |
| error.code | "INVALID_PARAMS" / "LIMIT_EXCEEDED" / "UNAUTHENTICATED" / "VECTOR_STORE_NOT_FOUND" / "FILE_NOT_FOUND" / "FILE_NOT_IN_STORE" / "BATCH_NOT_FOUND" / "CHUNK_NOT_FOUND" / "VECTOR_STORE_INVALID_STATE" / "FILE_INVALID_STATE" / "PAYLOAD_TOO_LARGE" / "RATE_LIMITED" / "NOT_IMPLEMENTED" / "PROVIDER_UNAVAILABLE" / null | 必有 |

未知路径的 404 可能只有 error.message；401 可能没有 details，兼容接口的 413 可能返回 code: null。路径编码错误也可能返回 HTML。不要假定每个失败都有业务错误码。

## 异步文件错误 [#异步文件错误]

添加文件成功并不表示内容已可搜索。检查文件 status；failed 时读取 last\_error。

| last\_error.code  | 含义                       | 建议                       |
| ----------------- | ------------------------ | ------------------------ |
| unsupported\_file | 解析器不支持该文件                | 转换为 TXT、Markdown 或已验证的格式 |
| invalid\_file     | 内容无效、为空、加密或超过估算 token 上限 | 检查内容、解密或拆分文件             |
| server\_error     | 处理失败或超过 30 分钟截止时间        | 稍后用 retry 重试失败文件         |

# Database API

（待译）

Database is a headless content store: structured tables and rows that people, agents and scripts read and write directly through the API, the way a headless CMS works. Concepts and behavior follow Supabase (PostgREST filters, projections, ordering and row writes via supabase-js), so Supabase experience applies. Differences: storage uses SQLite, not PostgreSQL, and schema changes use table/field APIs rather than SQL migrations or raw SQL; access uses a Praxis credential scoped to its tenant, with no Supabase Auth or row-level security policies; realtime row subscriptions are unavailable; casts, aggregates, spread and join modifiers are unsupported, and filtered planned/estimated counts may be unknown; upsert targets id or one unique field rather than composite keys. For an application's own runtime data, use the application's own d1, kv or r2 components instead. Start with `praxis.database.databases.create` to create a database, then use its returned id for tables and rows.

用 API Key 作为 Bearer 凭据，通过以下地址管理库与表结构。

`https://api.deepraxis.ai/database/v1`

[指南 →](/docs/cloud/services/database/quickstart)

| 资源 | 路径 |
| --- | --- |
| [Databases](/docs/api/native/database/databases) | /database/v1/databases |
| [Tables](/docs/api/native/database/tables) | /database/v1/databases/&#123;database_id&#125;/tables |
| [Fields](/docs/api/native/database/fields) | /database/v1/databases/&#123;database_id&#125;/tables/&#123;table&#125;/fields |
| [Events](/docs/api/native/database/events) | /database/v1/databases/&#123;database_id&#125;/events |
| [REST](/docs/api/native/database/rest) | /database/v1/databases/&#123;database_id&#125;/rest/&#123;table&#125; |

[错误码](/docs/api/native/database/errors)

# 数据库

[指南 →](/docs/cloud/services/database/quickstart)

[基础地址与鉴权](/docs/api/native/database)

## 创建库 [#创建库]

`POST /database/v1/databases`

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 名称 |
| labels | object | 否 | 标签 |

返回: `Database`.

### 响应 [#响应]

#### HTTP 201 [#http-201]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Database identifier, prefixed db_. Pass it as database_id in every database, table, field, rows and events path. |
| name | string | Display name given at creation or by the last update; it is not an identifier. |
| labels | object | String tags attached to the database, as key and value pairs; empty object when none. |
| status | string | Lifecycle state of the database. Table, field and row calls work only while it is active. |
| table_count | integer | Number of tables currently in the database, at most 50; refreshed when the schema changes. |
| size_bytes | integer | Storage size; row writes and GET refresh usage at most once per five seconds, schema changes refresh immediately. |
| created_at | string | Time the database was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last change to the name, labels, status or usage snapshot, as an RFC 3339 UTC timestamp. |
| deleted_at | string &#124; null | Time the database entered the deleting state, as an RFC 3339 UTC timestamp; null while it is active and again after a restore. |
| purge_at | string &#124; null | Permanent deletion deadline for deleting databases; null otherwise. |

```bash
curl -X POST "https://api.deepraxis.ai/database/v1/databases" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"walk-lib-r1-DOC-5320-tasks","labels":{"purpose":"docs","sample":"walk-lib-r1-doc-5320-"}}'
```

响应示例 — HTTP 201

```json
{
  "id": "db_d6f0d743d5a645e8",
  "name": "walk-lib-r1-DOC-5320-tasks",
  "labels": {
    "purpose": "docs",
    "sample": "walk-lib-r1-doc-5320-"
  },
  "status": "active",
  "table_count": 0,
  "size_bytes": 53248,
  "created_at": "2026-10-11T17:41:40.620Z",
  "updated_at": "2026-10-11T17:41:41.488Z",
  "deleted_at": null,
  "purge_at": null
}
```

## 列出库 [#列出库]

`GET /database/v1/databases`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| cursor | query | 上一页返回的 next_cursor。 |
| limit | query | 最多返回的条数。 (default: 20) (1–100) |
| labels | query | 精确匹配标签，例如 labels[purpose]=docs。 |
| status | query | 库状态：active 或 deleting；省略时只列出 active。 |

返回: `Page + object`.

### 响应 [#响应-1]

#### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Databases on this page, newest first (created_at descending, ties by id). Deleting databases are excluded unless status=deleting. |
| data[].id | string | Database identifier, prefixed db_. Pass it as database_id in every database, table, field, rows and events path. |
| data[].name | string | Display name given at creation or by the last update; it is not an identifier. |
| data[].labels | object | String tags attached to the database, as key and value pairs; empty object when none. |
| data[].status | string | Lifecycle state of the database. Table, field and row calls work only while it is active. |
| data[].table_count | integer | Number of tables currently in the database, at most 50; refreshed when the schema changes. |
| data[].size_bytes | integer | Storage size; row writes and GET refresh usage at most once per five seconds, schema changes refresh immediately. |
| data[].created_at | string | Time the database was created, as an RFC 3339 UTC timestamp. |
| data[].updated_at | string | Time of the last change to the name, labels, status or usage snapshot, as an RFC 3339 UTC timestamp. |
| data[].deleted_at | string &#124; null | Time the database entered the deleting state, as an RFC 3339 UTC timestamp; null while it is active and again after a restore. |
| data[].purge_at | string &#124; null | Permanent deletion deadline for deleting databases; null otherwise. |
| next_cursor | string &#124; null | Opaque cursor for the next page, or null when there are no more items. Databases list: pass it as cursor. Events list: pass it as after_seq (order asc) or before_seq (order desc). |

```bash
curl -g -X GET "https://api.deepraxis.ai/database/v1/databases?limit=10&labels[purpose]=docs&labels[sample]=walk-lib-r1-doc-5320-" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "data": [
    {
      "id": "db_d6f0d743d5a645e8",
      "name": "walk-lib-r1-DOC-5320-tasks",
      "labels": {
        "purpose": "docs",
        "sample": "walk-lib-r1-doc-5320-"
      },
      "status": "active",
      "table_count": 0,
      "size_bytes": 53248,
      "created_at": "2026-10-11T17:41:40.620Z",
      "updated_at": "2026-10-11T17:41:41.488Z",
      "deleted_at": null,
      "purge_at": null
    }
  ],
  "next_cursor": null
}
```

## 读取库 [#读取库]

`GET /database/v1/databases/{database_id}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |

返回: `Database`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-1]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Database identifier, prefixed db_. Pass it as database_id in every database, table, field, rows and events path. |
| name | string | Display name given at creation or by the last update; it is not an identifier. |
| labels | object | String tags attached to the database, as key and value pairs; empty object when none. |
| status | string | Lifecycle state of the database. Table, field and row calls work only while it is active. |
| table_count | integer | Number of tables currently in the database, at most 50; refreshed when the schema changes. |
| size_bytes | integer | Storage size; row writes and GET refresh usage at most once per five seconds, schema changes refresh immediately. |
| created_at | string | Time the database was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last change to the name, labels, status or usage snapshot, as an RFC 3339 UTC timestamp. |
| deleted_at | string &#124; null | Time the database entered the deleting state, as an RFC 3339 UTC timestamp; null while it is active and again after a restore. |
| purge_at | string &#124; null | Permanent deletion deadline for deleting databases; null otherwise. |

```bash
curl -X GET "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "id": "db_d6f0d743d5a645e8",
  "name": "walk-lib-r1-DOC-5320-tasks",
  "labels": {
    "purpose": "docs",
    "sample": "walk-lib-r1-doc-5320-"
  },
  "status": "active",
  "table_count": 0,
  "size_bytes": 53248,
  "created_at": "2026-10-11T17:41:40.620Z",
  "updated_at": "2026-10-11T17:41:41.488Z",
  "deleted_at": null,
  "purge_at": null
}
```

## 更新库 [#更新库]

`PATCH /database/v1/databases/{database_id}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 否 | 名称 |
| labels | object | 否 | 标签 |

返回: `Database`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-2]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Database identifier, prefixed db_. Pass it as database_id in every database, table, field, rows and events path. |
| name | string | Display name given at creation or by the last update; it is not an identifier. |
| labels | object | String tags attached to the database, as key and value pairs; empty object when none. |
| status | string | Lifecycle state of the database. Table, field and row calls work only while it is active. |
| table_count | integer | Number of tables currently in the database, at most 50; refreshed when the schema changes. |
| size_bytes | integer | Storage size; row writes and GET refresh usage at most once per five seconds, schema changes refresh immediately. |
| created_at | string | Time the database was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last change to the name, labels, status or usage snapshot, as an RFC 3339 UTC timestamp. |
| deleted_at | string &#124; null | Time the database entered the deleting state, as an RFC 3339 UTC timestamp; null while it is active and again after a restore. |
| purge_at | string &#124; null | Permanent deletion deadline for deleting databases; null otherwise. |

```bash
curl -X PATCH "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"walk-lib-r1-DOC-5320-notes"}'
```

响应示例 — HTTP 200

```json
{
  "id": "db_d6f0d743d5a645e8",
  "name": "walk-lib-r1-DOC-5320-notes",
  "labels": {
    "purpose": "docs",
    "sample": "walk-lib-r1-doc-5320-"
  },
  "status": "active",
  "table_count": 0,
  "size_bytes": 53248,
  "created_at": "2026-10-11T17:41:40.620Z",
  "updated_at": "2026-10-11T17:41:43.514Z",
  "deleted_at": null,
  "purge_at": null
}
```

## 删除库 [#删除库]

`DELETE /database/v1/databases/{database_id}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |

返回: `Database`.

### 响应 [#响应-4]

#### HTTP 200 [#http-200-3]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Database identifier, prefixed db_. Pass it as database_id in every database, table, field, rows and events path. |
| name | string | Display name given at creation or by the last update; it is not an identifier. |
| labels | object | String tags attached to the database, as key and value pairs; empty object when none. |
| status | string | Lifecycle state of the database. Table, field and row calls work only while it is active. |
| table_count | integer | Number of tables currently in the database, at most 50; refreshed when the schema changes. |
| size_bytes | integer | Storage size; row writes and GET refresh usage at most once per five seconds, schema changes refresh immediately. |
| created_at | string | Time the database was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last change to the name, labels, status or usage snapshot, as an RFC 3339 UTC timestamp. |
| deleted_at | string &#124; null | Time the database entered the deleting state, as an RFC 3339 UTC timestamp; null while it is active and again after a restore. |
| purge_at | string &#124; null | Permanent deletion deadline for deleting databases; null otherwise. |

```bash
curl -X DELETE "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "id": "db_d6f0d743d5a645e8",
  "name": "walk-lib-r1-DOC-5320-notes",
  "labels": {
    "purpose": "docs",
    "sample": "walk-lib-r1-doc-5320-"
  },
  "status": "deleting",
  "table_count": 0,
  "size_bytes": 53248,
  "created_at": "2026-10-11T17:41:40.620Z",
  "updated_at": "2026-10-11T17:41:51.868Z",
  "deleted_at": "2026-10-11T17:41:51.868Z",
  "purge_at": "2026-10-18T17:41:51.868Z"
}
```

## 恢复库 [#恢复库]

`POST /database/v1/databases/{database_id}/restore`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |

返回: `Database`.

### 响应 [#响应-5]

#### HTTP 200 [#http-200-4]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Database identifier, prefixed db_. Pass it as database_id in every database, table, field, rows and events path. |
| name | string | Display name given at creation or by the last update; it is not an identifier. |
| labels | object | String tags attached to the database, as key and value pairs; empty object when none. |
| status | string | Lifecycle state of the database. Table, field and row calls work only while it is active. |
| table_count | integer | Number of tables currently in the database, at most 50; refreshed when the schema changes. |
| size_bytes | integer | Storage size; row writes and GET refresh usage at most once per five seconds, schema changes refresh immediately. |
| created_at | string | Time the database was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last change to the name, labels, status or usage snapshot, as an RFC 3339 UTC timestamp. |
| deleted_at | string &#124; null | Time the database entered the deleting state, as an RFC 3339 UTC timestamp; null while it is active and again after a restore. |
| purge_at | string &#124; null | Permanent deletion deadline for deleting databases; null otherwise. |

```bash
curl -X POST "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/restore" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "id": "db_d6f0d743d5a645e8",
  "name": "walk-lib-r1-DOC-5320-notes",
  "labels": {
    "purpose": "docs",
    "sample": "walk-lib-r1-doc-5320-"
  },
  "status": "active",
  "table_count": 0,
  "size_bytes": 53248,
  "created_at": "2026-10-11T17:41:40.620Z",
  "updated_at": "2026-10-11T17:41:51.528Z",
  "deleted_at": null,
  "purge_at": null
}
```

## 清除库 [#清除库]

`POST /database/v1/databases/{database_id}/purge`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |

返回: `object`.

### 响应 [#响应-6]

#### HTTP 200 [#http-200-5]

Permanently purged

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Id (db_…) of the database that was permanently purged; it no longer resolves. |
| object | string | Resource type of the purged object; always database. |
| purged | boolean | Always true: the database and all of its data were permanently removed and cannot be recovered. |

```bash
curl -X POST "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/purge" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "id": "db_d6f0d743d5a645e8",
  "object": "database",
  "purged": true
}
```

## Database [#database]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 资源 ID; ^db_ |
| name | string | 是 | 名称 |
| labels | object | 是 | 标签 |
| status | "provisioning" / "active" / "deleting" / "deleted" / "failed" | 是 | 库状态 |
| table_count | integer | 是 | 表数量 |
| size_bytes | integer | 是 | 占用字节数 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| deleted_at | date-time / null | 是 | 删除时间；未删除时为 null |
| purge_at | date-time / null | 是 | — |

## Page [#page]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | JSON[] | 是 | 资源数组 |
| next_cursor | string / null | 是 | 下一页游标；没有后续时为 null |

# 数据表

[指南 →](/docs/cloud/services/database/quickstart)

[基础地址与鉴权](/docs/api/native/database)

## 创建表 [#创建表]

`POST /database/v1/databases/{database_id}/tables`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |

### 请求体 [#请求体]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 名称; ^[a-z_][a-z0-9_]&#123;0,62&#125;$ |
| description | string | 否 | 描述 |
| fields | NewField[] | 是 | 字段列表 |

返回: `Table`.

### 响应 [#响应]

#### HTTP 201 [#http-201]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Table identifier, prefixed tbl_. Stable across renames and accepted wherever a table path parameter takes an id or name. |
| name | string | Current table name, usable in the rows path; may change when the table is renamed. |
| description | string &#124; null | Free-text note about the table, or null when none was set. |
| fields | array&lt;object&gt; | Field definitions of the table, in display order. Row values are keyed by each field's name. |
| fields[].id | string | Field identifier, prefixed fld_. Stable across renames; accepted wherever a field path parameter takes an id or name. |
| fields[].name | string | Current field name; rows are keyed by it in requests and responses. May change when the field is renamed. |
| fields[].description | string &#124; null | Free-text note about the field, or null when none was set. |
| fields[].required | boolean | Whether every row must hold a non-null value for this field. |
| fields[].unique | boolean | Whether values must be distinct across rows; fixed at creation. A unique field is indexed, and a violation returns 409 UNIQUE_VIOLATION. |
| fields[].indexed | boolean | Whether an index is maintained for faster filters and ordering. Always false for json and link fields. |
| fields[].type | string | Scalar data type of the field; it cannot be changed after the field is created. / Type json: the value is any JSON document validated against options.schema. It cannot be changed after the field is created. / Type link: the value is the id of a row in another table (an array of ids when options.multiple is true). It cannot be changed after the field is created. |
| fields[].options | object | Scalar fields take no options; always an empty object. / Settings of a json field. schema is required. / Settings of a link field. Both linked_table_id and multiple are required. |
| fields[].default | any | Default JSON value for omitted insert fields; must match the field type and JSON schema. A datetime default of "now()" evaluates to server time on insertion and reads back as "now()" in the field definition. For string and json fields it is a literal string. Explicit null remains null. Link fields do not support defaults. |
| schema_revision | integer | Counter that starts at 1 and increases by one each time the table's name, description or fields change; use it to detect schema changes. |
| created_at | string | Time the table was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last schema change to the table, as an RFC 3339 UTC timestamp. |
| row_count | integer | Number of rows currently stored. Returned only by databaseGetTable; absent from list, create and field responses. |

```bash
curl -X POST "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/tables" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"tasks","fields":[{"name":"title","type":"string","required":true,"unique":true},{"name":"done","type":"boolean"}]}'
```

响应示例 — HTTP 201

```json
{
  "id": "tbl_2b3431c772754599",
  "name": "tasks",
  "description": null,
  "schema_revision": 1,
  "created_at": "2026-10-11T17:41:44.246Z",
  "updated_at": "2026-10-11T17:41:44.246Z",
  "fields": [
    {
      "id": "fld_bc71f7c6a1a848d2",
      "name": "title",
      "type": "string",
      "description": null,
      "required": true,
      "unique": true,
      "indexed": true
    },
    {
      "id": "fld_c7879883dfe04ca0",
      "name": "done",
      "type": "boolean",
      "description": null,
      "required": false,
      "unique": false,
      "indexed": true
    }
  ]
}
```

## 列出表 [#列出表]

`GET /database/v1/databases/{database_id}/tables`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |

返回: `Page + object`.

### 响应 [#响应-1]

#### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Every table of the database with its fields, in creation order; at most 50 items. |
| data[].id | string | Table identifier, prefixed tbl_. Stable across renames and accepted wherever a table path parameter takes an id or name. |
| data[].name | string | Current table name, usable in the rows path; may change when the table is renamed. |
| data[].description | string &#124; null | Free-text note about the table, or null when none was set. |
| data[].fields | array&lt;object&gt; | Field definitions of the table, in display order. Row values are keyed by each field's name. |
| data[].schema_revision | integer | Counter that starts at 1 and increases by one each time the table's name, description or fields change; use it to detect schema changes. |
| data[].created_at | string | Time the table was created, as an RFC 3339 UTC timestamp. |
| data[].updated_at | string | Time of the last schema change to the table, as an RFC 3339 UTC timestamp. |
| data[].row_count | integer | Number of rows currently stored. Returned only by databaseGetTable; absent from list, create and field responses. |
| next_cursor | string &#124; null | Opaque cursor for the next page, or null when there are no more items. Databases list: pass it as cursor. Events list: pass it as after_seq (order asc) or before_seq (order desc). |

```bash
curl -X GET "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/tables" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "data": [
    {
      "id": "tbl_2b3431c772754599",
      "name": "tasks",
      "description": null,
      "schema_revision": 1,
      "created_at": "2026-10-11T17:41:44.246Z",
      "updated_at": "2026-10-11T17:41:44.246Z",
      "fields": [
        {
          "id": "fld_bc71f7c6a1a848d2",
          "name": "title",
          "type": "string",
          "description": null,
          "required": true,
          "unique": true,
          "indexed": true
        },
        {
          "id": "fld_c7879883dfe04ca0",
          "name": "done",
          "type": "boolean",
          "description": null,
          "required": false,
          "unique": false,
          "indexed": true
        }
      ]
    }
  ],
  "next_cursor": null
}
```

## 读取表 [#读取表]

`GET /database/v1/databases/{database_id}/tables/{table}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |
| table | path | 表 ID 或名称。 |

返回: `Table`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-1]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Table identifier, prefixed tbl_. Stable across renames and accepted wherever a table path parameter takes an id or name. |
| name | string | Current table name, usable in the rows path; may change when the table is renamed. |
| description | string &#124; null | Free-text note about the table, or null when none was set. |
| fields | array&lt;object&gt; | Field definitions of the table, in display order. Row values are keyed by each field's name. |
| fields[].id | string | Field identifier, prefixed fld_. Stable across renames; accepted wherever a field path parameter takes an id or name. |
| fields[].name | string | Current field name; rows are keyed by it in requests and responses. May change when the field is renamed. |
| fields[].description | string &#124; null | Free-text note about the field, or null when none was set. |
| fields[].required | boolean | Whether every row must hold a non-null value for this field. |
| fields[].unique | boolean | Whether values must be distinct across rows; fixed at creation. A unique field is indexed, and a violation returns 409 UNIQUE_VIOLATION. |
| fields[].indexed | boolean | Whether an index is maintained for faster filters and ordering. Always false for json and link fields. |
| fields[].type | string | Scalar data type of the field; it cannot be changed after the field is created. / Type json: the value is any JSON document validated against options.schema. It cannot be changed after the field is created. / Type link: the value is the id of a row in another table (an array of ids when options.multiple is true). It cannot be changed after the field is created. |
| fields[].options | object | Scalar fields take no options; always an empty object. / Settings of a json field. schema is required. / Settings of a link field. Both linked_table_id and multiple are required. |
| fields[].default | any | Default JSON value for omitted insert fields; must match the field type and JSON schema. A datetime default of "now()" evaluates to server time on insertion and reads back as "now()" in the field definition. For string and json fields it is a literal string. Explicit null remains null. Link fields do not support defaults. |
| schema_revision | integer | Counter that starts at 1 and increases by one each time the table's name, description or fields change; use it to detect schema changes. |
| created_at | string | Time the table was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last schema change to the table, as an RFC 3339 UTC timestamp. |
| row_count | integer | Number of rows currently stored. Returned only by databaseGetTable; absent from list, create and field responses. |

```bash
curl -X GET "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/tables/tasks" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "id": "tbl_2b3431c772754599",
  "name": "tasks",
  "description": null,
  "schema_revision": 1,
  "created_at": "2026-10-11T17:41:44.246Z",
  "updated_at": "2026-10-11T17:41:44.246Z",
  "fields": [
    {
      "id": "fld_bc71f7c6a1a848d2",
      "name": "title",
      "type": "string",
      "description": null,
      "required": true,
      "unique": true,
      "indexed": true
    },
    {
      "id": "fld_c7879883dfe04ca0",
      "name": "done",
      "type": "boolean",
      "description": null,
      "required": false,
      "unique": false,
      "indexed": true
    }
  ],
  "row_count": 0
}
```

## 更新表 [#更新表]

`PATCH /database/v1/databases/{database_id}/tables/{table}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |
| table | path | 表 ID 或名称。 |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 否 | 名称 |
| description | string / null | 否 | 描述 |

返回: `Table`.

### 响应 [#响应-3]

#### HTTP 200 [#http-200-2]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Table identifier, prefixed tbl_. Stable across renames and accepted wherever a table path parameter takes an id or name. |
| name | string | Current table name, usable in the rows path; may change when the table is renamed. |
| description | string &#124; null | Free-text note about the table, or null when none was set. |
| fields | array&lt;object&gt; | Field definitions of the table, in display order. Row values are keyed by each field's name. |
| fields[].id | string | Field identifier, prefixed fld_. Stable across renames; accepted wherever a field path parameter takes an id or name. |
| fields[].name | string | Current field name; rows are keyed by it in requests and responses. May change when the field is renamed. |
| fields[].description | string &#124; null | Free-text note about the field, or null when none was set. |
| fields[].required | boolean | Whether every row must hold a non-null value for this field. |
| fields[].unique | boolean | Whether values must be distinct across rows; fixed at creation. A unique field is indexed, and a violation returns 409 UNIQUE_VIOLATION. |
| fields[].indexed | boolean | Whether an index is maintained for faster filters and ordering. Always false for json and link fields. |
| fields[].type | string | Scalar data type of the field; it cannot be changed after the field is created. / Type json: the value is any JSON document validated against options.schema. It cannot be changed after the field is created. / Type link: the value is the id of a row in another table (an array of ids when options.multiple is true). It cannot be changed after the field is created. |
| fields[].options | object | Scalar fields take no options; always an empty object. / Settings of a json field. schema is required. / Settings of a link field. Both linked_table_id and multiple are required. |
| fields[].default | any | Default JSON value for omitted insert fields; must match the field type and JSON schema. A datetime default of "now()" evaluates to server time on insertion and reads back as "now()" in the field definition. For string and json fields it is a literal string. Explicit null remains null. Link fields do not support defaults. |
| schema_revision | integer | Counter that starts at 1 and increases by one each time the table's name, description or fields change; use it to detect schema changes. |
| created_at | string | Time the table was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last schema change to the table, as an RFC 3339 UTC timestamp. |
| row_count | integer | Number of rows currently stored. Returned only by databaseGetTable; absent from list, create and field responses. |

```bash
curl -X PATCH "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/tables/tasks" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"description":"Tasks for an agent"}'
```

响应示例 — HTTP 200

```json
{
  "id": "tbl_2b3431c772754599",
  "name": "tasks",
  "description": "Tasks for an agent",
  "schema_revision": 2,
  "created_at": "2026-10-11T17:41:44.246Z",
  "updated_at": "2026-10-11T17:41:45.127Z",
  "fields": [
    {
      "id": "fld_bc71f7c6a1a848d2",
      "name": "title",
      "type": "string",
      "description": null,
      "required": true,
      "unique": true,
      "indexed": true
    },
    {
      "id": "fld_c7879883dfe04ca0",
      "name": "done",
      "type": "boolean",
      "description": null,
      "required": false,
      "unique": false,
      "indexed": true
    }
  ]
}
```

## 删除表 [#删除表]

`DELETE /database/v1/databases/{database_id}/tables/{table}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |
| table | path | 表 ID 或名称。 |

返回: `object`.

### 响应 [#响应-4]

#### HTTP 200 [#http-200-3]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| deleted | boolean | Always true: the table and all of its rows were dropped immediately and cannot be recovered. |

```bash
curl -X DELETE "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/tables/tasks" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "deleted": true
}
```

## Table [#table]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 资源 ID; ^tbl_ |
| name | string | 是 | 名称 |
| description | string / null | 是 | 描述 |
| fields | Field[] | 是 | 字段列表 |
| schema_revision | integer | 是 | 表结构版本 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| row_count | integer | 否 | 行数；仅单表查询返回 |

[Field](/docs/api/native/database/fields#field) · [Page](/docs/api/native/database/databases#page)

# 字段

[指南 →](/docs/cloud/services/database/quickstart)

[基础地址与鉴权](/docs/api/native/database)

添加、更新和删除字段均返回完整 Table。字段 type 不可修改；link 的关联目标不可修改。json 的 schema 更新仅约束之后的写入。

新增带 default 的字段时，已有行一律用 default 回填（无论是否 required），行的 \_version 不变；不带 default 的新字段在已有行上为 null。在已有行的表上新增 required 字段时必须提供 default，没有 default 时返回 400 VALIDATION\_FAILED。把字段改为 required 时，若仍有行在该字段为空，返回 400 VALIDATION\_FAILED 并在 message 中给出空行数。空请求体、只含被忽略键或所有值都与当前相同的 PATCH 不修改 updated\_at 与 schema\_revision、不产生事件，直接返回当前对象。

datetime 的 default 可以是字符串 "now()"，插入时生成服务器当前 UTC 时间；读回字段定义仍是 "now()"。例如 `{"name":"created_at","type":"datetime","default":"now()"}`。string/json 的 "now()" 保持字面量；其他类型仍按原校验规则处理。新增字段回填已有行时也会求值。

## 添加字段 [#添加字段]

`POST /database/v1/databases/{database_id}/tables/{table}/fields`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |
| table | path | 表 ID 或名称。 |

### 请求体 [#请求体]

"string" / "integer" / "number" / "boolean" / "datetime"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 字段名；只保留 id；新字段不能以下划线开头。created_at、updated_at、version 可作为用户字段名；已有下划线字段照常使用，且优先于同名元数据。; ^(?!id$)[a-z][a-z0-9_]&#123;0,62&#125;$ |
| description | string | 否 | 描述 |
| required | boolean | 否 | 是否必填 |
| unique | boolean | 否 | 是否唯一 |
| indexed | boolean | 否 | 是否索引 |
| type | "string" / "integer" / "number" / "boolean" / "datetime" | 是 | 类型 |
| options | object | 否 | json：schema；link：linked_table_id 与 multiple |
| default | JSON | 否 | 省略插入值时的默认值；datetime 的 now() 在写入时取服务器时间，字段定义仍读回 now()。string/json 中为字面量。显式 null 不使用默认值。 |

"json"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 字段名；只保留 id；新字段不能以下划线开头。created_at、updated_at、version 可作为用户字段名；已有下划线字段照常使用，且优先于同名元数据。; ^(?!id$)[a-z][a-z0-9_]&#123;0,62&#125;$ |
| description | string | 否 | 描述 |
| required | boolean | 否 | 是否必填 |
| unique | boolean | 否 | 是否唯一 |
| indexed | boolean | 否 | 是否索引 |
| type | "json" | 是 | 类型 |
| options | object | 是 | json：schema；link：linked_table_id 与 multiple |
| default | JSON | 否 | 省略插入值时的默认值；datetime 的 now() 在写入时取服务器时间，字段定义仍读回 now()。string/json 中为字面量。显式 null 不使用默认值。 |

"link"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 字段名；只保留 id；新字段不能以下划线开头。created_at、updated_at、version 可作为用户字段名；已有下划线字段照常使用，且优先于同名元数据。; ^(?!id$)[a-z][a-z0-9_]&#123;0,62&#125;$ |
| description | string | 否 | 描述 |
| required | boolean | 否 | 是否必填 |
| unique | boolean | 否 | 是否唯一 |
| indexed | boolean | 否 | 是否索引 |
| type | "link" | 是 | 类型 |
| options | object | 是 | json：schema；link：linked_table_id 与 multiple |

返回: `Table`.

### 响应 [#响应]

#### HTTP 201 [#http-201]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Table identifier, prefixed tbl_. Stable across renames and accepted wherever a table path parameter takes an id or name. |
| name | string | Current table name, usable in the rows path; may change when the table is renamed. |
| description | string &#124; null | Free-text note about the table, or null when none was set. |
| fields | array&lt;object&gt; | Field definitions of the table, in display order. Row values are keyed by each field's name. |
| fields[].id | string | Field identifier, prefixed fld_. Stable across renames; accepted wherever a field path parameter takes an id or name. |
| fields[].name | string | Current field name; rows are keyed by it in requests and responses. May change when the field is renamed. |
| fields[].description | string &#124; null | Free-text note about the field, or null when none was set. |
| fields[].required | boolean | Whether every row must hold a non-null value for this field. |
| fields[].unique | boolean | Whether values must be distinct across rows; fixed at creation. A unique field is indexed, and a violation returns 409 UNIQUE_VIOLATION. |
| fields[].indexed | boolean | Whether an index is maintained for faster filters and ordering. Always false for json and link fields. |
| fields[].type | string | Scalar data type of the field; it cannot be changed after the field is created. / Type json: the value is any JSON document validated against options.schema. It cannot be changed after the field is created. / Type link: the value is the id of a row in another table (an array of ids when options.multiple is true). It cannot be changed after the field is created. |
| fields[].options | object | Scalar fields take no options; always an empty object. / Settings of a json field. schema is required. / Settings of a link field. Both linked_table_id and multiple are required. |
| fields[].default | any | Default JSON value for omitted insert fields; must match the field type and JSON schema. A datetime default of "now()" evaluates to server time on insertion and reads back as "now()" in the field definition. For string and json fields it is a literal string. Explicit null remains null. Link fields do not support defaults. |
| schema_revision | integer | Counter that starts at 1 and increases by one each time the table's name, description or fields change; use it to detect schema changes. |
| created_at | string | Time the table was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last schema change to the table, as an RFC 3339 UTC timestamp. |
| row_count | integer | Number of rows currently stored. Returned only by databaseGetTable; absent from list, create and field responses. |

```bash
curl -X POST "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/tables/tasks/fields" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"priority","type":"integer"}'
```

响应示例 — HTTP 201

```json
{
  "id": "tbl_2b3431c772754599",
  "name": "tasks",
  "description": "Tasks for an agent",
  "schema_revision": 3,
  "created_at": "2026-10-11T17:41:44.246Z",
  "updated_at": "2026-10-11T17:41:45.420Z",
  "fields": [
    {
      "id": "fld_bc71f7c6a1a848d2",
      "name": "title",
      "type": "string",
      "description": null,
      "required": true,
      "unique": true,
      "indexed": true
    },
    {
      "id": "fld_c7879883dfe04ca0",
      "name": "done",
      "type": "boolean",
      "description": null,
      "required": false,
      "unique": false,
      "indexed": true
    },
    {
      "id": "fld_4c3e63869e35458c",
      "name": "priority",
      "type": "integer",
      "description": null,
      "required": false,
      "unique": false,
      "indexed": true
    }
  ]
}
```

## 更新字段 [#更新字段]

`PATCH /database/v1/databases/{database_id}/tables/{table}/fields/{field}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |
| table | path | 表 ID 或名称。 |
| field | path | 字段 ID 或名称。 |

### 请求体 [#请求体-1]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 否 | 名称 |
| description | string / null | 否 | 描述 |
| required | boolean | 否 | 是否必填 |
| indexed | boolean | 否 | 是否索引 |
| options | object | 否 | json：schema；link：linked_table_id 与 multiple |
| default | JSON | 否 | 省略插入值时的默认值；datetime 的 now() 在写入时取服务器时间，字段定义仍读回 now()。string/json 中为字面量。显式 null 不使用默认值。 |

返回: `Table`.

### 响应 [#响应-1]

#### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Table identifier, prefixed tbl_. Stable across renames and accepted wherever a table path parameter takes an id or name. |
| name | string | Current table name, usable in the rows path; may change when the table is renamed. |
| description | string &#124; null | Free-text note about the table, or null when none was set. |
| fields | array&lt;object&gt; | Field definitions of the table, in display order. Row values are keyed by each field's name. |
| fields[].id | string | Field identifier, prefixed fld_. Stable across renames; accepted wherever a field path parameter takes an id or name. |
| fields[].name | string | Current field name; rows are keyed by it in requests and responses. May change when the field is renamed. |
| fields[].description | string &#124; null | Free-text note about the field, or null when none was set. |
| fields[].required | boolean | Whether every row must hold a non-null value for this field. |
| fields[].unique | boolean | Whether values must be distinct across rows; fixed at creation. A unique field is indexed, and a violation returns 409 UNIQUE_VIOLATION. |
| fields[].indexed | boolean | Whether an index is maintained for faster filters and ordering. Always false for json and link fields. |
| fields[].type | string | Scalar data type of the field; it cannot be changed after the field is created. / Type json: the value is any JSON document validated against options.schema. It cannot be changed after the field is created. / Type link: the value is the id of a row in another table (an array of ids when options.multiple is true). It cannot be changed after the field is created. |
| fields[].options | object | Scalar fields take no options; always an empty object. / Settings of a json field. schema is required. / Settings of a link field. Both linked_table_id and multiple are required. |
| fields[].default | any | Default JSON value for omitted insert fields; must match the field type and JSON schema. A datetime default of "now()" evaluates to server time on insertion and reads back as "now()" in the field definition. For string and json fields it is a literal string. Explicit null remains null. Link fields do not support defaults. |
| schema_revision | integer | Counter that starts at 1 and increases by one each time the table's name, description or fields change; use it to detect schema changes. |
| created_at | string | Time the table was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last schema change to the table, as an RFC 3339 UTC timestamp. |
| row_count | integer | Number of rows currently stored. Returned only by databaseGetTable; absent from list, create and field responses. |

```bash
curl -X PATCH "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/tables/tasks/fields/priority" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"description":"Task priority"}'
```

响应示例 — HTTP 200

```json
{
  "id": "tbl_2b3431c772754599",
  "name": "tasks",
  "description": "Tasks for an agent",
  "schema_revision": 4,
  "created_at": "2026-10-11T17:41:44.246Z",
  "updated_at": "2026-10-11T17:41:46.276Z",
  "fields": [
    {
      "id": "fld_bc71f7c6a1a848d2",
      "name": "title",
      "type": "string",
      "description": null,
      "required": true,
      "unique": true,
      "indexed": true
    },
    {
      "id": "fld_c7879883dfe04ca0",
      "name": "done",
      "type": "boolean",
      "description": null,
      "required": false,
      "unique": false,
      "indexed": true
    },
    {
      "id": "fld_4c3e63869e35458c",
      "name": "priority",
      "type": "integer",
      "description": "Task priority",
      "required": false,
      "unique": false,
      "indexed": true
    }
  ]
}
```

## 删除字段 [#删除字段]

`DELETE /database/v1/databases/{database_id}/tables/{table}/fields/{field}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |
| table | path | 表 ID 或名称。 |
| field | path | 字段 ID 或名称。 |

返回: `Table`.

### 响应 [#响应-2]

#### HTTP 200 [#http-200-1]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Table identifier, prefixed tbl_. Stable across renames and accepted wherever a table path parameter takes an id or name. |
| name | string | Current table name, usable in the rows path; may change when the table is renamed. |
| description | string &#124; null | Free-text note about the table, or null when none was set. |
| fields | array&lt;object&gt; | Field definitions of the table, in display order. Row values are keyed by each field's name. |
| fields[].id | string | Field identifier, prefixed fld_. Stable across renames; accepted wherever a field path parameter takes an id or name. |
| fields[].name | string | Current field name; rows are keyed by it in requests and responses. May change when the field is renamed. |
| fields[].description | string &#124; null | Free-text note about the field, or null when none was set. |
| fields[].required | boolean | Whether every row must hold a non-null value for this field. |
| fields[].unique | boolean | Whether values must be distinct across rows; fixed at creation. A unique field is indexed, and a violation returns 409 UNIQUE_VIOLATION. |
| fields[].indexed | boolean | Whether an index is maintained for faster filters and ordering. Always false for json and link fields. |
| fields[].type | string | Scalar data type of the field; it cannot be changed after the field is created. / Type json: the value is any JSON document validated against options.schema. It cannot be changed after the field is created. / Type link: the value is the id of a row in another table (an array of ids when options.multiple is true). It cannot be changed after the field is created. |
| fields[].options | object | Scalar fields take no options; always an empty object. / Settings of a json field. schema is required. / Settings of a link field. Both linked_table_id and multiple are required. |
| fields[].default | any | Default JSON value for omitted insert fields; must match the field type and JSON schema. A datetime default of "now()" evaluates to server time on insertion and reads back as "now()" in the field definition. For string and json fields it is a literal string. Explicit null remains null. Link fields do not support defaults. |
| schema_revision | integer | Counter that starts at 1 and increases by one each time the table's name, description or fields change; use it to detect schema changes. |
| created_at | string | Time the table was created, as an RFC 3339 UTC timestamp. |
| updated_at | string | Time of the last schema change to the table, as an RFC 3339 UTC timestamp. |
| row_count | integer | Number of rows currently stored. Returned only by databaseGetTable; absent from list, create and field responses. |

```bash
curl -X DELETE "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/tables/tasks/fields/priority" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "id": "tbl_2b3431c772754599",
  "name": "tasks",
  "description": "Tasks for an agent",
  "schema_revision": 5,
  "created_at": "2026-10-11T17:41:44.246Z",
  "updated_at": "2026-10-11T17:41:47.136Z",
  "fields": [
    {
      "id": "fld_bc71f7c6a1a848d2",
      "name": "title",
      "type": "string",
      "description": null,
      "required": true,
      "unique": true,
      "indexed": true
    },
    {
      "id": "fld_c7879883dfe04ca0",
      "name": "done",
      "type": "boolean",
      "description": null,
      "required": false,
      "unique": false,
      "indexed": true
    }
  ]
}
```

## Field [#field]

"string" / "integer" / "number" / "boolean" / "datetime"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 资源 ID |
| name | string | 是 | 名称 |
| description | string / null | 是 | 描述 |
| required | boolean | 是 | 是否必填 |
| unique | boolean | 是 | 是否唯一 |
| indexed | boolean | 是 | 是否索引 |
| type | "string" / "integer" / "number" / "boolean" / "datetime" | 是 | 类型 |
| options | object | 否 | json：schema；link：linked_table_id 与 multiple |
| default | JSON | 否 | 省略插入值时的默认值；datetime 的 now() 在写入时取服务器时间，字段定义仍读回 now()。string/json 中为字面量。显式 null 不使用默认值。 |

"json"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 资源 ID |
| name | string | 是 | 名称 |
| description | string / null | 是 | 描述 |
| required | boolean | 是 | 是否必填 |
| unique | boolean | 是 | 是否唯一 |
| indexed | boolean | 是 | 是否索引 |
| type | "json" | 是 | 类型 |
| options | object | 是 | json：schema；link：linked_table_id 与 multiple |
| default | JSON | 否 | 省略插入值时的默认值；datetime 的 now() 在写入时取服务器时间，字段定义仍读回 now()。string/json 中为字面量。显式 null 不使用默认值。 |

"link"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 资源 ID |
| name | string | 是 | 名称 |
| description | string / null | 是 | 描述 |
| required | boolean | 是 | 是否必填 |
| unique | boolean | 是 | 是否唯一 |
| indexed | boolean | 是 | 是否索引 |
| type | "link" | 是 | 类型 |
| options | object | 是 | json：schema；link：linked_table_id 与 multiple |

## NewField [#newfield]

"string" / "integer" / "number" / "boolean" / "datetime"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 字段名；只保留 id；新字段不能以下划线开头。created_at、updated_at、version 可作为用户字段名；已有下划线字段照常使用，且优先于同名元数据。; ^(?!id$)[a-z][a-z0-9_]&#123;0,62&#125;$ |
| description | string | 否 | 描述 |
| required | boolean | 否 | 是否必填 |
| unique | boolean | 否 | 是否唯一 |
| indexed | boolean | 否 | 是否索引 |
| type | "string" / "integer" / "number" / "boolean" / "datetime" | 是 | 类型 |
| options | object | 否 | json：schema；link：linked_table_id 与 multiple |
| default | JSON | 否 | 省略插入值时的默认值；datetime 的 now() 在写入时取服务器时间，字段定义仍读回 now()。string/json 中为字面量。显式 null 不使用默认值。 |

"json"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 字段名；只保留 id；新字段不能以下划线开头。created_at、updated_at、version 可作为用户字段名；已有下划线字段照常使用，且优先于同名元数据。; ^(?!id$)[a-z][a-z0-9_]&#123;0,62&#125;$ |
| description | string | 否 | 描述 |
| required | boolean | 否 | 是否必填 |
| unique | boolean | 否 | 是否唯一 |
| indexed | boolean | 否 | 是否索引 |
| type | "json" | 是 | 类型 |
| options | object | 是 | json：schema；link：linked_table_id 与 multiple |
| default | JSON | 否 | 省略插入值时的默认值；datetime 的 now() 在写入时取服务器时间，字段定义仍读回 now()。string/json 中为字面量。显式 null 不使用默认值。 |

"link"

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 字段名；只保留 id；新字段不能以下划线开头。created_at、updated_at、version 可作为用户字段名；已有下划线字段照常使用，且优先于同名元数据。; ^(?!id$)[a-z][a-z0-9_]&#123;0,62&#125;$ |
| description | string | 否 | 描述 |
| required | boolean | 否 | 是否必填 |
| unique | boolean | 否 | 是否唯一 |
| indexed | boolean | 否 | 是否索引 |
| type | "link" | 是 | 类型 |
| options | object | 是 | json：schema；link：linked_table_id 与 multiple |

# 事件

[指南 →](/docs/cloud/services/database/quickstart)

[基础地址与鉴权](/docs/api/native/database)

事件记录库生命周期与表、字段结构变化，不记录行读写。

默认按 seq 升序；只给 before\_seq 时默认按 desc（最新在前）。next\_cursor 是不透明的字符串游标，原样传回：asc 时传给 after\_seq，desc 时传给 before\_seq。两个游标同时提供，或 before\_seq 与 order=asc 同时提供，返回 400 INVALID\_PARAMS。删除中的库仍可读取事件。

next\_cursor 是不透明的字符串游标，原样传回，不要对它做运算；为 null 表示没有后续页。下方响应为省略 order 的升序实测结果。倒序翻页按以下请求使用；该扩展的线上响应将在服务更新后补充。

```bash
# 最新一页
curl "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/events?order=desc&limit=10" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"

# 把 NEXT_CURSOR 设为上一页返回的 next_cursor
curl "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/events?order=desc&before_seq=${NEXT_CURSOR}&limit=10" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 读取事件 [#读取事件]

`GET /database/v1/databases/{database_id}/events`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| database_id | path | 库 ID。 |
| after_seq | query | order=asc 时，只取 seq 大于该值的事件；不可同时提供 before_seq。 |
| limit | query | 最多返回的条数。 (default: 50) (1–200) |
| order | query | asc 按 seq 升序，desc 为最新在前。默认 asc；只给 before_seq 时默认 desc。 |
| before_seq | query | 只取 seq 小于该值的事件，最新在前；省略 order 时按 desc。不可同时提供 after_seq 或 order=asc。 |

返回: `Page + object`.

### 响应 [#响应]

#### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Events on this page in the requested order (ascending seq by default, newest first with before_seq or order=desc). |
| data[].seq | integer | Position of the event in the database's event log; starts at 1 and strictly increases. Use it as after_seq or before_seq to page. |
| data[].id | string | Unique identifier of this event record. |
| data[].type | string | What happened: a lifecycle transition of the database, or a schema change to a table or field. |
| data[].processed_at | string | Time the event was recorded, as an RFC 3339 UTC timestamp. |
| data[].database_id | string | Id (db_…) of the database the event belongs to. |
| data[].table_id | string | Id (tbl_…) of the affected table; present only for table and field events. |
| data[].field_id | string | Id (fld_…) of the affected field; present only for field events. |
| next_cursor | string &#124; null | Opaque cursor for the next page, or null when there are no more items. Databases list: pass it as cursor. Events list: pass it as after_seq (order asc) or before_seq (order desc). |

```bash
curl -X GET "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/events?after_seq=0&limit=10" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

响应示例 — HTTP 200

```json
{
  "data": [
    {
      "seq": 1,
      "id": "7390d75e-216c-4799-891e-c043bac8bce5",
      "type": "database.status_provisioning",
      "processed_at": "2026-10-11T17:41:41.339Z",
      "database_id": "db_d6f0d743d5a645e8"
    },
    {
      "seq": 2,
      "id": "39db0ef4-99b4-4846-9d50-9998e25cf48f",
      "type": "database.status_active",
      "processed_at": "2026-10-11T17:41:41.339Z",
      "database_id": "db_d6f0d743d5a645e8"
    },
    {
      "seq": 3,
      "id": "d295651d-5e83-4b42-bcd3-c979fb71f375",
      "type": "table.created",
      "processed_at": "2026-10-11T17:41:44.246Z",
      "database_id": "db_d6f0d743d5a645e8",
      "table_id": "tbl_2b3431c772754599"
    },
    {
      "seq": 4,
      "id": "eb255753-3dd7-4eae-8861-d53408bfcaf4",
      "type": "table.updated",
      "processed_at": "2026-10-11T17:41:45.127Z",
      "database_id": "db_d6f0d743d5a645e8",
      "table_id": "tbl_2b3431c772754599"
    },
    {
      "seq": 5,
      "id": "99c86e22-0629-4391-85e5-d7b8b31de833",
      "type": "field.added",
      "processed_at": "2026-10-11T17:41:45.420Z",
      "database_id": "db_d6f0d743d5a645e8",
      "table_id": "tbl_2b3431c772754599",
      "field_id": "fld_4c3e63869e35458c"
    },
    {
      "seq": 6,
      "id": "a9b85950-363d-4ab3-8c85-6228eec3d099",
      "type": "field.updated",
      "processed_at": "2026-10-11T17:41:46.276Z",
      "database_id": "db_d6f0d743d5a645e8",
      "table_id": "tbl_2b3431c772754599",
      "field_id": "fld_4c3e63869e35458c"
    },
    {
      "seq": 7,
      "id": "73ca124f-6cbb-4a43-8a37-4ff50a211dd5",
      "type": "field.deleted",
      "processed_at": "2026-10-11T17:41:47.136Z",
      "database_id": "db_d6f0d743d5a645e8",
      "table_id": "tbl_2b3431c772754599",
      "field_id": "fld_4c3e63869e35458c"
    }
  ],
  "next_cursor": null
}
```

## DatabaseEvent [#databaseevent]

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| seq | integer | 是 | 库内递增序号 |
| id | string | 是 | 资源 ID |
| type | "database.status_provisioning" / "database.status_active" / "database.status_deleting" / "database.status_deleted" / "database.status_failed" / "database.restored" / "table.created" / "table.updated" / "table.deleted" / "field.added" / "field.updated" / "field.deleted" | 是 | 类型 |
| processed_at | date-time | 是 | 事件时间 |
| database_id | string | 是 | 库 ID |
| table_id | string | 否 | 相关表 ID（可选） |
| field_id | string | 否 | 相关字段 ID（可选） |

# 读写行

[指南 →](/docs/cloud/services/database/quickstart)

`/database/v1/databases/{database_id}/rest/{table}`

与同一库的其它入口读写相同的行；错误使用 PostgREST code。

[支持矩阵与初始化](/docs/api/compatible/supabase)

[完整参数、响应头与返回状态](/docs/api/compatible/supabase/tables)

一次批量 POST 最多插入 **500 行**，单次请求是原子的：任何一行失败，整批回滚。跨请求没有事务；需要一起成功的行应放在一次批量 POST 中。有关联依赖时先查后插，并处理并发变化导致的关联错误。

同一批次按所有行的键的并集补齐缺失值为 `null`（PostgREST 行为）。发送 `Prefer: missing=default` 可改用字段默认值；显式 `null` 仍为 null，没有默认值的必填字段仍必须提供。默认 `return=minimal` 返回 201、body 为空；发送 `Prefer: return=representation` 才返回行。

## 查询行 [#查询行]

`GET /database/v1/databases/{database_id}/rest/{table}`

```bash
curl -X GET "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/rest/tasks?select=*&order=title.asc&limit=10" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

### 响应 [#响应]

#### HTTP 200 [#http-200]

Success; write bodies require Prefer: return=representation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

#### HTTP 206 [#http-206]

Partial range with requested count

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

响应示例 — HTTP 200

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| etag | W/"5.1" |
| range-unit | items |

```json
[
  {
    "id": "rec_3e85a292099340e3",
    "version": 1,
    "created_at": "2026-10-11T17:41:47.896Z",
    "updated_at": "2026-10-11T17:41:47.896Z",
    "title": "Write a summary",
    "done": false
  }
]
```

## 统计行 [#统计行]

`HEAD /database/v1/databases/{database_id}/rest/{table}`

```bash
curl --head "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/rest/tasks?select=*" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'prefer: count=exact'
```

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

Success; write bodies require Prefer: return=representation

未声明响应体。

#### HTTP 206 [#http-206-1]

Partial range with requested count

未声明响应体。

响应示例 — HTTP 200

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/1 |
| preference-applied | count=exact |
| etag | W/"5.1" |
| range-unit | items |

无响应正文。

## 插入行 [#插入行]

`POST /database/v1/databases/{database_id}/rest/{table}`

```bash
curl -X POST "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/rest/tasks" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'prefer: return=representation' \
  -H "Content-Type: application/json" \
  -d '{"title":"Write a summary","done":false}'
```

### 响应 [#响应-2]

#### HTTP 201 [#http-201]

Success (201). With the default return=minimal the body is empty; Prefer: return=representation returns rows.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

响应示例 — HTTP 201

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| preference-applied | return=representation |
| range-unit | items |

```json
[
  {
    "id": "rec_3e85a292099340e3",
    "version": 1,
    "created_at": "2026-10-11T17:41:47.896Z",
    "updated_at": "2026-10-11T17:41:47.896Z",
    "title": "Write a summary",
    "done": false
  }
]
```

## 更新行 [#更新行]

`PATCH /database/v1/databases/{database_id}/rest/{table}`

```bash
curl -X PATCH "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/rest/tasks?title=eq.Write%20a%20summary" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'prefer: return=representation' \
  -H "Content-Type: application/json" \
  -d '{"done":true}'
```

### 响应 [#响应-3]

#### HTTP 200 [#http-200-2]

Success; write bodies require Prefer: return=representation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

#### HTTP 204 [#http-204]

Success without a body

未声明响应体。

响应示例 — HTTP 200

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| preference-applied | return=representation |
| range-unit | items |

```json
[
  {
    "id": "rec_3e85a292099340e3",
    "version": 2,
    "created_at": "2026-10-11T17:41:47.896Z",
    "updated_at": "2026-10-11T17:41:48.802Z",
    "title": "Write a summary",
    "done": true
  }
]
```

## 合并行 [#合并行]

`POST /database/v1/databases/{database_id}/rest/{table}`

```bash
curl -X POST "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/rest/tasks?on_conflict=title" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'prefer: resolution=merge-duplicates,return=representation' \
  -H "Content-Type: application/json" \
  -d '{"title":"Write a summary","done":true}'
```

### 响应 [#响应-4]

#### HTTP 201 [#http-201-1]

Success (201). With the default return=minimal the body is empty; Prefer: return=representation returns rows.

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

响应示例 — HTTP 201

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| preference-applied | resolution=merge-duplicates, return=representation |
| range-unit | items |

```json
[
  {
    "id": "rec_3e85a292099340e3",
    "version": 3,
    "created_at": "2026-10-11T17:41:47.896Z",
    "updated_at": "2026-10-11T17:41:49.076Z",
    "title": "Write a summary",
    "done": true
  }
]
```

## 删除行 [#删除行]

`DELETE /database/v1/databases/{database_id}/rest/{table}`

```bash
curl -X DELETE "https://api.deepraxis.ai/database/v1/databases/${DATABASE_ID}/rest/tasks?title=eq.Write%20a%20summary" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H 'prefer: return=representation'
```

### 响应 [#响应-5]

#### HTTP 200 [#http-200-3]

Success; write bodies require Prefer: return=representation

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

**application/vnd.pgrst.object+json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Row identifier of 1–64 characters from A-Z a-z 0-9 _ -. Generated by the service unless the insert supplied one; it cannot be changed by updates. |

#### HTTP 204 [#http-204-1]

Success without a body

未声明响应体。

响应示例 — HTTP 200

| 响应头 | 值 |
| --- | --- |
| content-range | 0-0/* |
| preference-applied | return=representation |
| range-unit | items |

```json
[
  {
    "id": "rec_3e85a292099340e3",
    "version": 3,
    "created_at": "2026-10-11T17:41:47.896Z",
    "updated_at": "2026-10-11T17:41:49.076Z",
    "title": "Write a summary",
    "done": true
  }
]
```

## Row [#row]

默认投影、select=&#x2A;、return=representation 与 RPC 行对象只返回 id 和用户字段。系统元数据须显式点名，例如 select=*,\_version,\_created\_at,\_updated\_at；\* 不展开它们。可用 \_version=eq.3 过滤、order=\_created\_at.desc 排序，但不可写。未指定 order 时仍按内部创建时间、id 排序。没有同名用户字段时，旧名 created\_at/updated\_at/version 用于过滤或排序返回 400，details 为 use \_created\_at（或对应名字），hint 为 system metadata moved to underscore columns。已有下划线用户字段优先，同名系统元数据在该表上不可访问。上方历史响应样例采集于此规则调整前，仍可能包含旧元数据列；当前行形状以本节为准。

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 资源 ID; ^[A-Za-z0-9_-]&#123;1,64&#125;$ |

# 错误码

管理端点返回领域码；两个表端点返回 PostgREST code。HTTP 状态与重试属性如下。

| 领域码 | HTTP | PostgREST code | 可重试 |
| --- | --- | --- | --- |
| SINGULAR_MISMATCH | 406 | PGRST116 | 否 |
| AMBIGUOUS_EMBED | 300 | PGRST201 | 否 |
| EMBED_NOT_FOUND | 400 | PGRST200 | 否 |
| INVALID_PREFERENCE | 400 | PGRST122 | 否 |
| QUERY_CANCELED | 500 | 57014 | 否 |
| RANGE_NOT_SATISFIABLE | 416 | PGRST103 | 否 |
| NOT_ACCEPTABLE | 406 | PGRST107 | 否 |
| OPERATOR_TYPE_MISMATCH | 400 | 42883 | 否 |
| DATABASE_NOT_FOUND | 404 | PGRST125 | 否 |
| TABLE_NOT_FOUND | 404 | PGRST205 | 否 |
| FIELD_NOT_FOUND | 400 | 42703 | 否 |
| VALIDATION_FAILED | 400 | 23514 | 否 |
| UNIQUE_VIOLATION | 409 | 23505 | 否 |
| REFERENCE_RESTRICT | 409 | 23503 | 否 |
| FIELD_TYPE_IMMUTABLE | 400 | — | 否 |
| LIMIT_EXCEEDED | 400 | 54000 | 否 |
| UNSUPPORTED | 400 | PGRST127 | 否 |
| INVALID_PARAMS | 400 | PGRST100 | 否 |
| DATABASE_INVALID_STATE | 409 | — | 否 |
| CAPACITY | 503 | — | 是 |
| NOT_IMPLEMENTED | 501 | PGRST127 | 否 |

可重试不表示重复原请求一定成功。例如 57014 应先缩小查询范围或调整过滤条件，再重试。

## 管理端点错误体 [#管理端点错误体]

响应示例 — HTTP 400

```json
{
  "code": "FIELD_TYPE_IMMUTABLE",
  "message": "field type is immutable",
  "details": null,
  "hint": null
}
```

## 表端点错误体 [#表端点错误体]

响应示例 — HTTP 400

```json
{
  "code": "PGRST127",
  "message": "operator fts is not supported",
  "details": null,
  "hint": null
}
```

code、message、details、hint 四个字段始终存在；details 与 hint 可以为 null。

## 未开放服务错误体 [#未开放服务错误体]

响应示例 — HTTP 501

| 响应头 | 值 |
| --- | --- |
| x-should-retry | false |

```json
{
  "code": "not_implemented",
  "message": "auth is not provided by praxis-database"
}
```

这五个服务直接返回 not\_implemented；它与错误表中的领域码 NOT\_IMPLEMENTED 不同。

## 按错误细节修正请求 [#按错误细节修正请求]

保留字段名只有 `id`；新字段名不能以 `_` 开头，这个前缀留给系统元数据。`created_at`、`updated_at`、`version` 可用作普通字段名。datetime 字段可用 `"now()"` 作为默认值。

`details` 指出字段或 JSON 路径及实际收到的值，批量校验还包含从 0 开始的行号。值最多显示 80 个字符，不回显整行。`hint` 给出修正方式，没有建议时为 null。下面是省略第 2 行必填 title 的错误示例：

```json
{
  "code": "23514",
  "message": "row validation failed",
  "details": "row 1: title: required value (got null)",
  "hint": "Rows in one insert are filled to the union of their keys with null (PostgREST behavior). Send every key in every row, or send Prefer: missing=default to use field defaults."
}
```

唯一冲突返回 409，例如：

```json
{
  "code": "23505",
  "message": "unique constraint violated",
  "details": "Key (email)=(a@b.c) already exists.",
  "hint": null
}
```

# Vault API

（待译）

Vault stores write-only credentials through `/vault/v1`, with a compatibility face at `/anthropic/v1/vaults`. Concepts and behavior follow Anthropic vaults (credential collections, write-only values, rotation and archival), so Anthropic experience applies. Differences: native secrets use names and static/oauth kinds; native OAuth uses authorizations, while compatible mcp\_oauth creation and updates return 501; explicit allowed\_hosts are required, with no unrestricted mode; Agent sessions reject nonempty vault\_ids, so vault-backed MCP authentication is unavailable; application vault references return 501, including praxis\_vault\_ref bindings and secret writes with a vault source. Metadata labels do not attach credentials to either resource. Start with `praxis.vault.vaults.create` to create the containing vault.

用 API Key 作为 Bearer 凭据，通过以下地址管理库与 Secret。Secret 的值只写，任何接口都不会返回。

`https://api.deepraxis.ai/vault/v1`

[指南 →](/docs/cloud/services/vault/quickstart)

| 资源 | 路径 |
| --- | --- |
| [库](/docs/api/native/vault/vaults) | /vault/v1/vaults |
| [Secret](/docs/api/native/vault/secrets) | /vault/v1/vaults/&#123;vault_id&#125;/secrets |
| [模板](/docs/api/native/vault/templates) | /vault/v1/templates |
| [一键授权](/docs/api/native/vault/authorizations) | /vault/v1/authorizations |

Secret 可以用名字或 vsec\_ 开头的 ID 寻址。列表用 cursor 与 limit 翻页（limit 默认 50，最大 200），返回的 next\_cursor 为 null 表示没有后续页。

同一批库也可以通过 Claude 托管智能体的凭据库接口访问：[Claude 托管智能体](/docs/api/compatible/anthropic/managed-agents)

[错误码](/docs/api/native/vault/errors)

# 库

创建和管理库，检查可用状态，并查询不含 Secret 值的审计事件。

[指南 →](/docs/cloud/services/vault/quickstart)

[基础地址与鉴权](/docs/api/native/vault)

审计事件按时间倒序列出，可用 secret 按名称或 ID 过滤；未知 Secret 返回空列表。limit 默认 50、最大 200；超限或无效 cursor 返回 400 INVALID\_PARAMS。事件没有按天自动过期的保留期；归档保留事件，删除库或 Secret 会清除其历史事件，仅保留删除记录。

## 列出库 [#列出库]

`GET /vault/v1/vaults`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| cursor | query | 上一页返回的 next_cursor。 |
| limit | query | 每页条数。 (默认: 50) (1–200) |
| include_archived | query | 是否包含已归档的条目。 (默认: false) |

### 响应 [#响应]

#### HTTP 200 [#http-200]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | Vault[] | 是 | 条目数组 |
| data[].id | string | 是 | 对象标识符 |
| data[].type | "vault" | 是 | 对象类型 |
| data[].display_name | string | 是 | 显示名称，1–255 个字符 |
| data[].metadata | object | 是 | 自定义标签最多 16 对，键最长 64 字符，值最长 512 字符 |
| data[].status | "active" / "archived" | 是 | 状态 |
| data[].secret_count | integer | 是 | 有效 Secret 数 |
| data[].needs_reauthorization_count | integer | 是 | 续期失败、需要重新授权的 OAuth Secret 数 |
| data[].created_at | date-time | 是 | 创建时间 |
| data[].updated_at | date-time | 是 | 更新时间 |
| data[].archived_at | date-time / null | 是 | 归档时间；未归档时为 null |
| next_cursor | string / null | 是 | 下一页游标；没有后续时为 null |

### 错误响应 [#错误响应]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

```bash
curl "https://api.deepraxis.ai/vault/v1/vaults" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 创建库 [#创建库]

`POST /vault/v1/vaults`

### 请求体 [#请求体]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| display_name | string | 是 | 显示名称，1–255 个字符 |
| metadata | object | 否 | 自定义标签最多 16 对，键最长 64 字符，值最长 512 字符 |

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault" | 是 | 对象类型 |
| display_name | string | 是 | 显示名称，1–255 个字符 |
| metadata | object | 是 | 自定义标签最多 16 对，键最长 64 字符，值最长 512 字符 |
| status | "active" / "archived" | 是 | 状态 |
| secret_count | integer | 是 | 有效 Secret 数 |
| needs_reauthorization_count | integer | 是 | 续期失败、需要重新授权的 OAuth Secret 数 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-1]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"display_name":"Agent credentials"}'
```

## 检查库 [#检查库]

`POST /vault/v1/vaults:check`

### 请求体 [#请求体-1]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| vault_ids | string[] | 是 | 要检查的库 ID |

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | object[] | 是 | 条目数组 |
| data[].vault_id | string | 是 | 库 ID |
| data[].status | "ok" / "not_found" / "archived" | 是 | 状态 |

### 错误响应 [#错误响应-2]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults:check" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"vault_ids\":[\"${VAULT_ID}\"]}"
```

## 读取库 [#读取库]

`GET /vault/v1/vaults/{vault_id}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault" | 是 | 对象类型 |
| display_name | string | 是 | 显示名称，1–255 个字符 |
| metadata | object | 是 | 自定义标签最多 16 对，键最长 64 字符，值最长 512 字符 |
| status | "active" / "archived" | 是 | 状态 |
| secret_count | integer | 是 | 有效 Secret 数 |
| needs_reauthorization_count | integer | 是 | 续期失败、需要重新授权的 OAuth Secret 数 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-3]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |

```bash
curl "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 更新库 [#更新库]

`POST /vault/v1/vaults/{vault_id}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |

### 请求体 [#请求体-2]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| display_name | string | 否 | 显示名称，1–255 个字符 |
| metadata | object | 否 | 按键合并：字符串写入，null 删除，省略的键保留；自定义标签最多 16 对 |

### 响应 [#响应-4]

#### HTTP 200 [#http-200-4]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault" | 是 | 对象类型 |
| display_name | string | 是 | 显示名称，1–255 个字符 |
| metadata | object | 是 | 自定义标签最多 16 对，键最长 64 字符，值最长 512 字符 |
| status | "active" / "archived" | 是 | 状态 |
| secret_count | integer | 是 | 有效 Secret 数 |
| needs_reauthorization_count | integer | 是 | 续期失败、需要重新授权的 OAuth Secret 数 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-4]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| VAULT_INVALID_STATE | 409 | 向已归档的库或 Secret 写入；改用有效资源 | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"metadata":{"team":"growth"}}'
```

## 删除库 [#删除库]

`DELETE /vault/v1/vaults/{vault_id}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |

### 响应 [#响应-5]

#### HTTP 200 [#http-200-5]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_deleted" | 是 | 对象类型 |

### 错误响应 [#错误响应-5]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |

```bash
curl -X DELETE "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 归档库 [#归档库]

`POST /vault/v1/vaults/{vault_id}/archive`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |

### 响应 [#响应-6]

#### HTTP 200 [#http-200-6]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault" | 是 | 对象类型 |
| display_name | string | 是 | 显示名称，1–255 个字符 |
| metadata | object | 是 | 自定义标签最多 16 对，键最长 64 字符，值最长 512 字符 |
| status | "active" / "archived" | 是 | 状态 |
| secret_count | integer | 是 | 有效 Secret 数 |
| needs_reauthorization_count | integer | 是 | 续期失败、需要重新授权的 OAuth Secret 数 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-6]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/archive" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 查看事件 [#查看事件]

`GET /vault/v1/vaults/{vault_id}/events`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |
| secret | query | Secret 名称或 vsec_ 开头的 ID。 |
| cursor | query | 上一页返回的 next_cursor。 |
| limit | query | 每页条数。 (默认: 50) (1–200) |

### 响应 [#响应-7]

#### HTTP 200 [#http-200-7]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | VaultEvent[] | 是 | 条目数组 |
| data[].id | uuid | 是 | 对象标识符 |
| data[].type | "vault.created" / "vault.updated" / "vault.archived" / "vault.deleted" / "vault_secret.created" / "vault_secret.updated" / "vault_secret.archived" / "vault_secret.deleted" / "vault_secret.used" / "vault_secret.refreshed" / "vault_secret.refresh_failed" / "vault_authorization.completed" / "vault_authorization.failed" / "vault_authorization.expired" | 是 | 对象类型 |
| data[].secret_id | string / null | 是 | 关联的 Secret ID；未关联时为 null |
| data[].secret_name | string / null | 是 | 关联的 Secret 名称 |
| data[].at | date-time | 是 | 事件或错误发生时间 |
| data[].detail | object / null | 是 | 事件详情，不含 Secret 值；更新事件的 changed 列出变更字段 |
| data[].detail.changed | string[] | 否 | 本次更新的字段名，例如 value、allowed_hosts |
| next_cursor | string / null | 是 | 下一页游标；没有后续时为 null |

### 错误响应 [#错误响应-7]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

```bash
curl "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/events" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## Vault [#vault]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault" | 是 | 对象类型 |
| display_name | string | 是 | 显示名称，1–255 个字符 |
| metadata | object | 是 | 自定义标签最多 16 对，键最长 64 字符，值最长 512 字符 |
| status | "active" / "archived" | 是 | 状态 |
| secret_count | integer | 是 | 有效 Secret 数 |
| needs_reauthorization_count | integer | 是 | 续期失败、需要重新授权的 OAuth Secret 数 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

## VaultPage [#vaultpage]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | Vault[] | 是 | 条目数组 |
| data[].id | string | 是 | 对象标识符 |
| data[].type | "vault" | 是 | 对象类型 |
| data[].display_name | string | 是 | 显示名称，1–255 个字符 |
| data[].metadata | object | 是 | 自定义标签最多 16 对，键最长 64 字符，值最长 512 字符 |
| data[].status | "active" / "archived" | 是 | 状态 |
| data[].secret_count | integer | 是 | 有效 Secret 数 |
| data[].needs_reauthorization_count | integer | 是 | 续期失败、需要重新授权的 OAuth Secret 数 |
| data[].created_at | date-time | 是 | 创建时间 |
| data[].updated_at | date-time | 是 | 更新时间 |
| data[].archived_at | date-time / null | 是 | 归档时间；未归档时为 null |
| next_cursor | string / null | 是 | 下一页游标；没有后续时为 null |

## VaultEvent [#vaultevent]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | uuid | 是 | 对象标识符 |
| type | "vault.created" / "vault.updated" / "vault.archived" / "vault.deleted" / "vault_secret.created" / "vault_secret.updated" / "vault_secret.archived" / "vault_secret.deleted" / "vault_secret.used" / "vault_secret.refreshed" / "vault_secret.refresh_failed" / "vault_authorization.completed" / "vault_authorization.failed" / "vault_authorization.expired" | 是 | 对象类型 |
| secret_id | string / null | 是 | 关联的 Secret ID；未关联时为 null |
| secret_name | string / null | 是 | 关联的 Secret 名称 |
| at | date-time | 是 | 事件或错误发生时间 |
| detail | object / null | 是 | 事件详情，不含 Secret 值；更新事件的 changed 列出变更字段 |
| detail.changed | string[] | 否 | 本次更新的字段名，例如 value、allowed_hosts |

# Secret

添加、导入和更新 Secret；值只写，校验与续期仅用于 OAuth Secret。

[指南 →](/docs/cloud/services/vault/quickstart)

[基础地址与鉴权](/docs/api/native/vault)

导入同名 Secret 只替换值；只有该行自己的 allowed\_hosts 才能改变原域名，顶层默认域名不覆盖已有域名。新建行优先使用该行域名，否则使用顶层默认域名。逐行失败在 HTTP 200 的 failed 中返回（包括 SECRET\_TOO\_LARGE、VAULT\_LIMIT\_EXCEEDED、INVALID\_PARAMS），其它行仍然写入。用非法名称查找 Secret 返回 404 SECRET\_NOT\_FOUND。

## 列出 Secret [#列出-secret]

`GET /vault/v1/vaults/{vault_id}/secrets`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |
| cursor | query | 上一页返回的 next_cursor。 |
| limit | query | 每页条数。 (默认: 50) (1–200) |
| include_archived | query | 是否包含已归档的条目。 (默认: false) |

### 响应 [#响应]

#### HTTP 200 [#http-200]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | Secret[] | 是 | 条目数组 |
| data[].id | string | 是 | 对象标识符 |
| data[].type | "vault_secret" | 是 | 对象类型 |
| data[].vault_id | string | 是 | 库 ID |
| data[].name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| data[].kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| data[].allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| data[].description | string / null | 是 | 备注；更新时 null 清除，省略则保留 |
| data[].metadata | object | 是 | 自定义标签最多 16 对；source、template 为系统保留键，不占这 16 对且不能由调用方写入 |
| data[].status | "active" / "refreshing" / "refresh_failed" / "archived" | 是 | 状态 |
| data[].oauth | SecretOAuthSummary / null | 是 | OAuth 摘要；kind 为 static 时为 null |
| data[].oauth.expires_at | date-time / null | 是 | 过期时间 |
| data[].oauth.last_refreshed_at | date-time / null | 是 | 最近一次续期时间 |
| data[].oauth.next_refresh_at | date-time / null | 是 | 下次计划续期时间 |
| data[].oauth.scope | string / null | 是 | 授权范围 |
| data[].oauth.last_error | object / null | 是 | 最近一次续期失败 |
| data[].oauth.last_error.code | string | 是 | 稳定的错误码 |
| data[].oauth.last_error.message | string | 是 | 可读的错误说明 |
| data[].oauth.last_error.at | date-time | 是 | 事件或错误发生时间 |
| data[].version | integer | 是 | 值每次变化时递增 |
| data[].last_used_at | date-time / null | 是 | 最近一次被使用的时间 |
| data[].created_at | date-time | 是 | 创建时间 |
| data[].updated_at | date-time | 是 | 更新时间 |
| data[].archived_at | date-time / null | 是 | 归档时间；未归档时为 null |
| next_cursor | string / null | 是 | 下一页游标；没有后续时为 null |

### 错误响应 [#错误响应]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

```bash
curl "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 添加 Secret [#添加-secret]

`POST /vault/v1/vaults/{vault_id}/secrets`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |

### 请求体 [#请求体]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| value | string | 是 | Secret 的值，只写，不会返回；最大 16 KiB |
| allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| description | string / null | 否 | 备注；更新时 null 清除，省略则保留 |
| metadata | object | 否 | 自定义标签最多 16 对；source、template 为系统保留键，不占这 16 对且不能由调用方写入 |
| template_id | "github" / "openai" / "anthropic" / "stripe" | 否 | 仅支持 static 模板 ID；记录为 metadata.template |
| kind | "static" | 否 | 只能为 static；OAuth Secret 通过一键授权创建 |

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_secret" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| description | string / null | 是 | 备注；更新时 null 清除，省略则保留 |
| metadata | object | 是 | 自定义标签最多 16 对；source、template 为系统保留键，不占这 16 对且不能由调用方写入 |
| status | "active" / "refreshing" / "refresh_failed" / "archived" | 是 | 状态 |
| oauth | SecretOAuthSummary / null | 是 | OAuth 摘要；kind 为 static 时为 null |
| oauth.expires_at | date-time / null | 是 | 过期时间 |
| oauth.last_refreshed_at | date-time / null | 是 | 最近一次续期时间 |
| oauth.next_refresh_at | date-time / null | 是 | 下次计划续期时间 |
| oauth.scope | string / null | 是 | 授权范围 |
| oauth.last_error | object / null | 是 | 最近一次续期失败 |
| oauth.last_error.code | string | 是 | 稳定的错误码 |
| oauth.last_error.message | string | 是 | 可读的错误说明 |
| oauth.last_error.at | date-time | 是 | 事件或错误发生时间 |
| version | integer | 是 | 值每次变化时递增 |
| last_used_at | date-time / null | 是 | 最近一次被使用的时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-1]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| VAULT_INVALID_STATE | 409 | 向已归档的库或 Secret 写入；改用有效资源 | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |
| SECRET_CONFLICT | 409 | 创建时名称已占用；更换名称或更新已有 Secret | validation_failure | none | 否 |
| VAULT_LIMIT_EXCEEDED | 400 | 超过有效 Secret 数量上限；先清理不用的 Secret | validation_failure | none | 否 |
| SECRET_TOO_LARGE | 413 | 值超过 16384 字节；缩小值后重试 | validation_failure | none | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"GITHUB_TOKEN","value":"ghp_example","allowed_hosts":["api.github.com"]}'
```

## 批量导入 [#批量导入]

`POST /vault/v1/vaults/{vault_id}/secrets:import`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |

### 请求体 [#请求体-1]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| lines | ImportLine[] | 否 | 逐行导入的 Secret |
| lines[].name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| lines[].value | string | 是 | Secret 的值，只写，不会返回；最大 16 KiB |
| lines[].allowed_hosts | string[] | 否 | 新建时用本行域名或导入的默认域名；替换时仅本行显式 allowed_hosts 才会更新域名 |
| dotenv | string | 否 | .env 格式的 KEY=VALUE 文本；与 lines 二选一 |
| allowed_hosts | string[] | 否 | 新建时用本行域名或导入的默认域名；替换时仅本行显式 allowed_hosts 才会更新域名 |

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| created | string[] | 是 | 新建的 Secret 名称 |
| replaced | string[] | 是 | 被替换的 Secret 名称 |
| failed | object[] | 是 | 失败的行 |
| failed[].line | integer | 是 | 失败行号，从 1 开始 |
| failed[].name | string / null | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| failed[].code | "VAULT_NOT_FOUND" / "SECRET_NOT_FOUND" / "AUTHORIZATION_NOT_FOUND" / "SECRET_CONFLICT" / "VAULT_INVALID_STATE" / "VAULT_LIMIT_EXCEEDED" / "INVALID_PARAMS" / "SECRET_KIND_MISMATCH" / "VALIDATE_UNSUPPORTED" / "SECRET_TOO_LARGE" / "RATE_LIMITED" / "AUTHORIZATION_EXPIRED" / "OAUTH_DISCOVERY_FAILED" / "OAUTH_REGISTRATION_UNSUPPORTED" / "OAUTH_ISSUER_MISMATCH" / "OAUTH_STATE_INVALID" / "OAUTH_EXCHANGE_FAILED" / "NOT_IMPLEMENTED" | 是 | 稳定的错误码 |
| failed[].message | string | 是 | 可读的错误说明 |

### 错误响应 [#错误响应-2]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| VAULT_INVALID_STATE | 409 | 向已归档的库或 Secret 写入；改用有效资源 | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets:import" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"dotenv":"OPENAI_API_KEY=sk-example\nLINEAR_API_KEY=lin_example","allowed_hosts":["api.openai.com","api.linear.app"]}'
```

## 读取 Secret [#读取-secret]

`GET /vault/v1/vaults/{vault_id}/secrets/{secret}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |
| secret | path | Secret 名称或 vsec_ 开头的 ID。 |

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_secret" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| description | string / null | 是 | 备注；更新时 null 清除，省略则保留 |
| metadata | object | 是 | 自定义标签最多 16 对；source、template 为系统保留键，不占这 16 对且不能由调用方写入 |
| status | "active" / "refreshing" / "refresh_failed" / "archived" | 是 | 状态 |
| oauth | SecretOAuthSummary / null | 是 | OAuth 摘要；kind 为 static 时为 null |
| oauth.expires_at | date-time / null | 是 | 过期时间 |
| oauth.last_refreshed_at | date-time / null | 是 | 最近一次续期时间 |
| oauth.next_refresh_at | date-time / null | 是 | 下次计划续期时间 |
| oauth.scope | string / null | 是 | 授权范围 |
| oauth.last_error | object / null | 是 | 最近一次续期失败 |
| oauth.last_error.code | string | 是 | 稳定的错误码 |
| oauth.last_error.message | string | 是 | 可读的错误说明 |
| oauth.last_error.at | date-time | 是 | 事件或错误发生时间 |
| version | integer | 是 | 值每次变化时递增 |
| last_used_at | date-time / null | 是 | 最近一次被使用的时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-3]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| SECRET_NOT_FOUND | 404 | Secret 不存在，包括用非法名称查找；检查名称或 ID | validation_failure | none | 否 |

```bash
curl "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets/GITHUB_TOKEN" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 更新 Secret [#更新-secret]

`POST /vault/v1/vaults/{vault_id}/secrets/{secret}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |
| secret | path | Secret 名称或 vsec_ 开头的 ID。 |

### 请求体 [#请求体-2]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| value | string | 否 | Secret 的值，只写，不会返回；最大 16 KiB |
| allowed_hosts | string[] | 否 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| description | string / null | 否 | 备注；更新时 null 清除，省略则保留 |
| metadata | object | 否 | 按键合并：字符串写入，null 删除，省略的键保留；source、template 为保留键 |

### 响应 [#响应-4]

#### HTTP 200 [#http-200-4]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_secret" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| description | string / null | 是 | 备注；更新时 null 清除，省略则保留 |
| metadata | object | 是 | 自定义标签最多 16 对；source、template 为系统保留键，不占这 16 对且不能由调用方写入 |
| status | "active" / "refreshing" / "refresh_failed" / "archived" | 是 | 状态 |
| oauth | SecretOAuthSummary / null | 是 | OAuth 摘要；kind 为 static 时为 null |
| oauth.expires_at | date-time / null | 是 | 过期时间 |
| oauth.last_refreshed_at | date-time / null | 是 | 最近一次续期时间 |
| oauth.next_refresh_at | date-time / null | 是 | 下次计划续期时间 |
| oauth.scope | string / null | 是 | 授权范围 |
| oauth.last_error | object / null | 是 | 最近一次续期失败 |
| oauth.last_error.code | string | 是 | 稳定的错误码 |
| oauth.last_error.message | string | 是 | 可读的错误说明 |
| oauth.last_error.at | date-time | 是 | 事件或错误发生时间 |
| version | integer | 是 | 值每次变化时递增 |
| last_used_at | date-time / null | 是 | 最近一次被使用的时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-4]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| SECRET_NOT_FOUND | 404 | Secret 不存在，包括用非法名称查找；检查名称或 ID | validation_failure | none | 否 |
| VAULT_INVALID_STATE | 409 | 向已归档的库或 Secret 写入；改用有效资源 | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |
| SECRET_TOO_LARGE | 413 | 值超过 16384 字节；缩小值后重试 | validation_failure | none | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets/GITHUB_TOKEN" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"value":"ghp_rotated"}'
```

## 删除 Secret [#删除-secret]

`DELETE /vault/v1/vaults/{vault_id}/secrets/{secret}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |
| secret | path | Secret 名称或 vsec_ 开头的 ID。 |

### 响应 [#响应-5]

#### HTTP 200 [#http-200-5]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_secret_deleted" | 是 | 对象类型 |

### 错误响应 [#错误响应-5]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| SECRET_NOT_FOUND | 404 | Secret 不存在，包括用非法名称查找；检查名称或 ID | validation_failure | none | 否 |

```bash
curl -X DELETE "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets/GITHUB_TOKEN" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 归档 Secret [#归档-secret]

`POST /vault/v1/vaults/{vault_id}/secrets/{secret}/archive`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |
| secret | path | Secret 名称或 vsec_ 开头的 ID。 |

### 响应 [#响应-6]

#### HTTP 200 [#http-200-6]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_secret" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| description | string / null | 是 | 备注；更新时 null 清除，省略则保留 |
| metadata | object | 是 | 自定义标签最多 16 对；source、template 为系统保留键，不占这 16 对且不能由调用方写入 |
| status | "active" / "refreshing" / "refresh_failed" / "archived" | 是 | 状态 |
| oauth | SecretOAuthSummary / null | 是 | OAuth 摘要；kind 为 static 时为 null |
| oauth.expires_at | date-time / null | 是 | 过期时间 |
| oauth.last_refreshed_at | date-time / null | 是 | 最近一次续期时间 |
| oauth.next_refresh_at | date-time / null | 是 | 下次计划续期时间 |
| oauth.scope | string / null | 是 | 授权范围 |
| oauth.last_error | object / null | 是 | 最近一次续期失败 |
| oauth.last_error.code | string | 是 | 稳定的错误码 |
| oauth.last_error.message | string | 是 | 可读的错误说明 |
| oauth.last_error.at | date-time | 是 | 事件或错误发生时间 |
| version | integer | 是 | 值每次变化时递增 |
| last_used_at | date-time / null | 是 | 最近一次被使用的时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-6]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| SECRET_NOT_FOUND | 404 | Secret 不存在，包括用非法名称查找；检查名称或 ID | validation_failure | none | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets/GITHUB_TOKEN/archive" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 校验 Secret [#校验-secret]

`POST /vault/v1/vaults/{vault_id}/secrets/{secret}/validate`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |
| secret | path | Secret 名称或 vsec_ 开头的 ID。 |

### 响应 [#响应-7]

#### HTTP 200 [#http-200-7]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| type | "vault_secret_validation" | 是 | 对象类型 |
| secret_id | string | 是 | 关联的 Secret ID；未关联时为 null |
| vault_id | string | 是 | 库 ID |
| validated_at | date-time | 是 | 校验时间 |
| has_refresh_token | boolean | 是 | 是否保存了刷新令牌 |
| status | "valid" / "invalid" / "unknown" | 是 | 状态 |
| probe | object | 是 | 探测请求 |
| probe.method | "GET" | 是 | 探测方式，当前为 GET |
| probe.http_response | HttpCapture / null | 是 | HTTP 响应摘要；未收到响应时为 null |
| probe.http_response.status_code | integer | 是 | HTTP 状态码 |
| probe.http_response.content_type | string / null | 是 | 响应内容类型，或 null |
| probe.http_response.body | string | 是 | 已脱敏的响应正文 |
| probe.http_response.body_truncated | boolean | 是 | 正文是否被截断 |
| refresh | object | 是 | 续期结果 |
| refresh.status | "succeeded" / "failed" / "connect_error" / "no_refresh_token" / "skipped" | 是 | 状态 |
| refresh.http_response | HttpCapture / null | 是 | HTTP 响应摘要；未收到响应时为 null |
| refresh.http_response.status_code | integer | 是 | HTTP 状态码 |
| refresh.http_response.content_type | string / null | 是 | 响应内容类型，或 null |
| refresh.http_response.body | string | 是 | 已脱敏的响应正文 |
| refresh.http_response.body_truncated | boolean | 是 | 正文是否被截断 |

### 错误响应 [#错误响应-7]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| SECRET_NOT_FOUND | 404 | Secret 不存在，包括用非法名称查找；检查名称或 ID | validation_failure | none | 否 |
| VALIDATE_UNSUPPORTED | 400 | 对 static Secret 校验；校验仅支持 OAuth Secret | validation_failure | none | 否 |
| RATE_LIMITED | 429 | 一分钟内超过授权或校验额度；等待下一窗口 | rate_limit | wait_then_retry | 是 |

仅适用于 OAuth Secret。先完成一键授权，并将返回的 secret\_id 设为 OAUTH\_SECRET\_ID；不要使用 static Secret。

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets/${OAUTH_SECRET_ID}/validate" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 续期 Secret [#续期-secret]

`POST /vault/v1/vaults/{vault_id}/secrets/{secret}/refresh`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| vault_id | path | 库 ID。 |
| secret | path | Secret 名称或 vsec_ 开头的 ID。 |

### 请求体 [#请求体-3]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| reason | "unauthorized" | 否 | 触发续期的原因 |

### 响应 [#响应-8]

#### HTTP 200 [#http-200-8]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_secret" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| description | string / null | 是 | 备注；更新时 null 清除，省略则保留 |
| metadata | object | 是 | 自定义标签最多 16 对；source、template 为系统保留键，不占这 16 对且不能由调用方写入 |
| status | "active" / "refreshing" / "refresh_failed" / "archived" | 是 | 状态 |
| oauth | SecretOAuthSummary / null | 是 | OAuth 摘要；kind 为 static 时为 null |
| oauth.expires_at | date-time / null | 是 | 过期时间 |
| oauth.last_refreshed_at | date-time / null | 是 | 最近一次续期时间 |
| oauth.next_refresh_at | date-time / null | 是 | 下次计划续期时间 |
| oauth.scope | string / null | 是 | 授权范围 |
| oauth.last_error | object / null | 是 | 最近一次续期失败 |
| oauth.last_error.code | string | 是 | 稳定的错误码 |
| oauth.last_error.message | string | 是 | 可读的错误说明 |
| oauth.last_error.at | date-time | 是 | 事件或错误发生时间 |
| version | integer | 是 | 值每次变化时递增 |
| last_used_at | date-time / null | 是 | 最近一次被使用的时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

### 错误响应 [#错误响应-8]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| SECRET_NOT_FOUND | 404 | Secret 不存在，包括用非法名称查找；检查名称或 ID | validation_failure | none | 否 |
| VAULT_INVALID_STATE | 409 | 向已归档的库或 Secret 写入；改用有效资源 | validation_failure | none | 否 |
| SECRET_KIND_MISMATCH | 400 | 对 static Secret 续期或执行不匹配种类的操作；使用 OAuth Secret | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

仅适用于 OAuth Secret。先完成一键授权，并将返回的 secret\_id 设为 OAUTH\_SECRET\_ID；不要使用 static Secret。

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/vaults/${VAULT_ID}/secrets/${OAUTH_SECRET_ID}/refresh" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"reason":"unauthorized"}'
```

## Secret [#secret]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_secret" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| description | string / null | 是 | 备注；更新时 null 清除，省略则保留 |
| metadata | object | 是 | 自定义标签最多 16 对；source、template 为系统保留键，不占这 16 对且不能由调用方写入 |
| status | "active" / "refreshing" / "refresh_failed" / "archived" | 是 | 状态 |
| oauth | SecretOAuthSummary / null | 是 | OAuth 摘要；kind 为 static 时为 null |
| oauth.expires_at | date-time / null | 是 | 过期时间 |
| oauth.last_refreshed_at | date-time / null | 是 | 最近一次续期时间 |
| oauth.next_refresh_at | date-time / null | 是 | 下次计划续期时间 |
| oauth.scope | string / null | 是 | 授权范围 |
| oauth.last_error | object / null | 是 | 最近一次续期失败 |
| oauth.last_error.code | string | 是 | 稳定的错误码 |
| oauth.last_error.message | string | 是 | 可读的错误说明 |
| oauth.last_error.at | date-time | 是 | 事件或错误发生时间 |
| version | integer | 是 | 值每次变化时递增 |
| last_used_at | date-time / null | 是 | 最近一次被使用的时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |
| archived_at | date-time / null | 是 | 归档时间；未归档时为 null |

## SecretOAuthSummary [#secretoauthsummary]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| expires_at | date-time / null | 是 | 过期时间 |
| last_refreshed_at | date-time / null | 是 | 最近一次续期时间 |
| next_refresh_at | date-time / null | 是 | 下次计划续期时间 |
| scope | string / null | 是 | 授权范围 |
| last_error | object / null | 是 | 最近一次续期失败 |
| last_error.code | string | 是 | 稳定的错误码 |
| last_error.message | string | 是 | 可读的错误说明 |
| last_error.at | date-time | 是 | 事件或错误发生时间 |

## ImportLine [#importline]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| value | string | 是 | Secret 的值，只写，不会返回；最大 16 KiB |
| allowed_hosts | string[] | 否 | 新建时用本行域名或导入的默认域名；替换时仅本行显式 allowed_hosts 才会更新域名 |

## ImportResult [#importresult]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| created | string[] | 是 | 新建的 Secret 名称 |
| replaced | string[] | 是 | 被替换的 Secret 名称 |
| failed | object[] | 是 | 失败的行 |
| failed[].line | integer | 是 | 失败行号，从 1 开始 |
| failed[].name | string / null | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| failed[].code | "VAULT_NOT_FOUND" / "SECRET_NOT_FOUND" / "AUTHORIZATION_NOT_FOUND" / "SECRET_CONFLICT" / "VAULT_INVALID_STATE" / "VAULT_LIMIT_EXCEEDED" / "INVALID_PARAMS" / "SECRET_KIND_MISMATCH" / "VALIDATE_UNSUPPORTED" / "SECRET_TOO_LARGE" / "RATE_LIMITED" / "AUTHORIZATION_EXPIRED" / "OAUTH_DISCOVERY_FAILED" / "OAUTH_REGISTRATION_UNSUPPORTED" / "OAUTH_ISSUER_MISMATCH" / "OAUTH_STATE_INVALID" / "OAUTH_EXCHANGE_FAILED" / "NOT_IMPLEMENTED" | 是 | 稳定的错误码 |
| failed[].message | string | 是 | 可读的错误说明 |

## SecretValidation [#secretvalidation]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| type | "vault_secret_validation" | 是 | 对象类型 |
| secret_id | string | 是 | 关联的 Secret ID；未关联时为 null |
| vault_id | string | 是 | 库 ID |
| validated_at | date-time | 是 | 校验时间 |
| has_refresh_token | boolean | 是 | 是否保存了刷新令牌 |
| status | "valid" / "invalid" / "unknown" | 是 | 状态 |
| probe | object | 是 | 探测请求 |
| probe.method | "GET" | 是 | 探测方式，当前为 GET |
| probe.http_response | HttpCapture / null | 是 | HTTP 响应摘要；未收到响应时为 null |
| probe.http_response.status_code | integer | 是 | HTTP 状态码 |
| probe.http_response.content_type | string / null | 是 | 响应内容类型，或 null |
| probe.http_response.body | string | 是 | 已脱敏的响应正文 |
| probe.http_response.body_truncated | boolean | 是 | 正文是否被截断 |
| refresh | object | 是 | 续期结果 |
| refresh.status | "succeeded" / "failed" / "connect_error" / "no_refresh_token" / "skipped" | 是 | 状态 |
| refresh.http_response | HttpCapture / null | 是 | HTTP 响应摘要；未收到响应时为 null |
| refresh.http_response.status_code | integer | 是 | HTTP 状态码 |
| refresh.http_response.content_type | string / null | 是 | 响应内容类型，或 null |
| refresh.http_response.body | string | 是 | 已脱敏的响应正文 |
| refresh.http_response.body_truncated | boolean | 是 | 正文是否被截断 |

## HttpCapture [#httpcapture]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| status_code | integer | 是 | HTTP 状态码 |
| content_type | string / null | 是 | 响应内容类型，或 null |
| body | string | 是 | 已脱敏的响应正文 |
| body_truncated | boolean | 是 | 正文是否被截断 |

# 模板

查询常用服务的模板 ID、Secret 名称、种类和允许域名。

[指南 →](/docs/cloud/services/vault/quickstart)

[基础地址与鉴权](/docs/api/native/vault)

| template_id | kind | 服务 |
| --- | --- | --- |
| github | static | GitHub (api.github.com, uploads.github.com) |
| openai | static | OpenAI |
| anthropic | static | Anthropic |
| stripe | static | Stripe |
| linear | oauth | Linear (CIMD) |
| atlassian | oauth | Atlassian (DCR) |

## 列出模板 [#列出模板]

`GET /vault/v1/templates`

### 响应 [#响应]

#### HTTP 200 [#http-200]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| data | VaultTemplate[] | 是 | 条目数组 |
| data[].id | string | 是 | 对象标识符 |
| data[].display_name | string | 是 | 显示名称，1–255 个字符 |
| data[].kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| data[].name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| data[].allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| data[].value_hint | string / null | 是 | 填写提示 |

### 错误响应 [#错误响应]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。
没有额外的领域错误。

```bash
curl "https://api.deepraxis.ai/vault/v1/templates" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## VaultTemplate [#vaulttemplate]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| display_name | string | 是 | 显示名称，1–255 个字符 |
| kind | "static" / "oauth" | 是 | static：你填写的值；oauth：授权得到、由平台续期 |
| name | string | 是 | 名称，库内唯一且不可改；1–128 个大写字母、数字或下划线，以字母或下划线开头 |
| allowed_hosts | string[] | 是 | 1–16 个域名、公网 IPv4 或 *.example.com；不匹配根域名。拒绝 IPv6、单标签主机、localhost、*.internal、平台域名及回环/链路本地/私网/CGNAT IPv4；规范化并去重 |
| value_hint | string / null | 是 | 填写提示 |

# 一键授权

让用户授权第三方服务，并管理一次性授权链接与回跳地址。

[指南 →](/docs/cloud/services/vault/quickstart)

[基础地址与鉴权](/docs/api/native/vault)

一键授权为支持 OAuth 的服务产生 kind 为 oauth 的 Secret。发起授权后把 connect\_url 交给最终用户；用户在确认页同意并在服务方完成授权后，Secret 写入库中，之后由平台续期。确认页、回调与客户端元数据三个地址不需要 API Key。

## 发起授权 [#发起授权]

`POST /vault/v1/authorizations`

### 请求体 [#请求体]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| vault_id | string | 是 | 库 ID |
| template_id | "linear" / "atlassian" | 否 | 支持授权的模板 ID；与 resource_url 二选一 |
| resource_url | string | 否 | 要授权的资源地址，例如 MCP 服务地址 |
| return_url | string | 否 | 授权结束后回到的地址；须在回跳地址白名单内 |

### 响应 [#响应]

#### HTTP 200 [#http-200]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_authorization" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| status | "pending" / "authorizing" / "completed" / "failed" / "expired" | 是 | 状态 |
| resource | string | 是 | 资源地址 |
| secret_name | string | 是 | 关联的 Secret 名称 |
| connect_url | string | 是 | 交给最终用户打开的确认页，30 分钟内有效、只能使用一次 |
| client_registration | "cimd" / "dcr" / null | 是 | cimd：通过客户端元数据 URL 注册；dcr：动态注册客户端；尚未注册时为 null |
| secret_id | string / null | 是 | 关联的 Secret ID；未关联时为 null |
| error | object / null | 是 | 失败原因 |
| error.code | string | 是 | 稳定的错误码 |
| error.message | string | 是 | 可读的错误说明 |
| expires_at | date-time | 是 | 过期时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |

### 错误响应 [#错误响应]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| VAULT_INVALID_STATE | 409 | 向已归档的库或 Secret 写入；改用有效资源 | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |
| RATE_LIMITED | 429 | 一分钟内超过授权或校验额度；等待下一窗口 | rate_limit | wait_then_retry | 是 |
| OAUTH_DISCOVERY_FAILED | 400 | 无法发现服务方 OAuth 配置；检查资源地址 | validation_failure | continue_from_problem | 否 |
| OAUTH_REGISTRATION_UNSUPPORTED | 400 | 服务方不接受自动客户端注册；手动添加凭据 | validation_failure | continue_from_problem | 否 |
| OAUTH_ISSUER_MISMATCH | 400 | 授权服务器与预期不一致；重新检查服务地址 | provider_upstream | retry_from_user | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/authorizations" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"vault_id\":\"${VAULT_ID}\",\"template_id\":\"linear\"}"
```

## 读取授权 [#读取授权]

`GET /vault/v1/authorizations/{authorization_id}`

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| authorization_id | path | 授权 ID。 |

### 响应 [#响应-1]

#### HTTP 200 [#http-200-1]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_authorization" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| status | "pending" / "authorizing" / "completed" / "failed" / "expired" | 是 | 状态 |
| resource | string | 是 | 资源地址 |
| secret_name | string | 是 | 关联的 Secret 名称 |
| connect_url | string | 是 | 交给最终用户打开的确认页，30 分钟内有效、只能使用一次 |
| client_registration | "cimd" / "dcr" / null | 是 | cimd：通过客户端元数据 URL 注册；dcr：动态注册客户端；尚未注册时为 null |
| secret_id | string / null | 是 | 关联的 Secret ID；未关联时为 null |
| error | object / null | 是 | 失败原因 |
| error.code | string | 是 | 稳定的错误码 |
| error.message | string | 是 | 可读的错误说明 |
| expires_at | date-time | 是 | 过期时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |

### 错误响应 [#错误响应-1]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| AUTHORIZATION_NOT_FOUND | 404 | 授权或确认链接不存在；重新发起授权 | validation_failure | none | 否 |

```bash
curl "https://api.deepraxis.ai/vault/v1/authorizations/${AUTHORIZATION_ID}" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 读取回跳地址 [#读取回跳地址]

`GET /vault/v1/settings/return_urls`

### 响应 [#响应-2]

#### HTTP 200 [#http-200-2]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| urls | string[] | 是 | https 地址，精确匹配，最多 10 个 |

### 错误响应 [#错误响应-2]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。
没有额外的领域错误。

```bash
curl "https://api.deepraxis.ai/vault/v1/settings/return_urls" \
  -H "Authorization: Bearer $PRAXIS_API_KEY"
```

## 设置回跳地址 [#设置回跳地址]

`PUT /vault/v1/settings/return_urls`

### 请求体 [#请求体-1]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| urls | string[] | 是 | https 地址，精确匹配，最多 10 个 |

### 响应 [#响应-3]

#### HTTP 200 [#http-200-3]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| urls | string[] | 是 | https 地址，精确匹配，最多 10 个 |

### 错误响应 [#错误响应-3]

缺少或无效的 API Key 返回 401 UNAUTHENTICATED。

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |

```bash
curl -X PUT "https://api.deepraxis.ai/vault/v1/settings/return_urls" \
  -H "Authorization: Bearer $PRAXIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"urls":["https://app.example.com/connected"]}'
```

## 授权回调 [#授权回调]

`GET /vault/v1/authorizations/callback` · 无需 API Key

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| code | query | 服务方返回的授权码。 |
| state | query | 发起授权时产生的一次性状态值。 |
| error | query | 服务方拒绝授权时返回的错误。 |
| iss | query | 服务方声明的授权服务器地址。 |

### 响应 [#响应-4]

#### HTTP 200 [#http-200-4]

**text/html**

浏览器显示的确认页或结果页。

#### HTTP 302 [#http-302]

通过 Location 响应头跳转到服务方授权页或已允许的回跳地址。

### 错误响应 [#错误响应-4]

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| OAUTH_STATE_INVALID | 400 | 回调 state 缺失、无效或重放；重新发起授权 | validation_failure | none | 否 |
| OAUTH_ISSUER_MISMATCH | 400 | 授权服务器与预期不一致；重新检查服务地址 | provider_upstream | retry_from_user | 否 |
| OAUTH_EXCHANGE_FAILED | 502 | 服务方拒绝授权码换令牌；重新授权 | provider_upstream | retry_from_user | 否 |
| AUTHORIZATION_EXPIRED | 410 | 授权链接超过 30 分钟或已使用；重新发起授权 | validation_failure | retry_from_user | 否 |

设置了 return\_url 时返回 302；未设置时返回 HTTP 200 结果页。

```bash
curl "https://api.deepraxis.ai/vault/v1/authorizations/callback"
```

## OAuth 客户端元数据 [#oauth-客户端元数据]

`GET /vault/v1/oauth/client.json` · 无需 API Key

### 响应 [#响应-5]

#### HTTP 200 [#http-200-5]

**application/json**

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| client_id | string | 是 | 客户端元数据 URL |
| client_name | string | 是 | 客户端显示名称 |
| redirect_uris | string[] | 是 | 允许的 OAuth 回调地址 |
| token_endpoint_auth_method | "none" | 是 | 令牌端点认证方式 |
| grant_types | "authorization_code" / "refresh_token"[] | 否 | 支持的授权类型 |
| response_types | "code"[] | 否 | 支持的授权响应类型 |

### 错误响应 [#错误响应-5]

没有额外的领域错误。

```bash
curl "https://api.deepraxis.ai/vault/v1/oauth/client.json"
```

## 授权确认页 [#授权确认页]

`GET /vault/v1/connect/{token}` · 无需 API Key

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| token | path | connect_url 中的一次性令牌。 |

### 响应 [#响应-6]

#### HTTP 200 [#http-200-6]

**text/html**

浏览器显示的确认页或结果页。

#### HTTP 410 [#http-410]

**text/html**

浏览器显示的确认页或结果页。

### 错误响应 [#错误响应-6]

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| AUTHORIZATION_NOT_FOUND | 404 | 授权或确认链接不存在；重新发起授权 | validation_failure | none | 否 |
| AUTHORIZATION_EXPIRED | 410 | 授权链接超过 30 分钟或已使用；重新发起授权 | validation_failure | retry_from_user | 否 |

无效链接返回 404；过期或已使用的链接返回 410，均为 HTML 页面。

```bash
curl "https://api.deepraxis.ai/vault/v1/connect/${TOKEN}"
```

## 继续授权 [#继续授权]

`POST /vault/v1/connect/{token}/continue` · 无需 API Key

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| token | path | connect_url 中的一次性令牌。 |

### 响应 [#响应-7]

#### HTTP 302 [#http-302-1]

通过 Location 响应头跳转到服务方授权页或已允许的回跳地址。

### 错误响应 [#错误响应-7]

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| AUTHORIZATION_NOT_FOUND | 404 | 授权或确认链接不存在；重新发起授权 | validation_failure | none | 否 |
| AUTHORIZATION_EXPIRED | 410 | 授权链接超过 30 分钟或已使用；重新发起授权 | validation_failure | retry_from_user | 否 |
| OAUTH_DISCOVERY_FAILED | 400 | 无法发现服务方 OAuth 配置；检查资源地址 | validation_failure | continue_from_problem | 否 |

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/connect/${TOKEN}/continue"
```

## 拒绝授权 [#拒绝授权]

`POST /vault/v1/connect/{token}/deny` · 无需 API Key

| 参数 | 位置 | 说明 |
| --- | --- | --- |
| token | path | connect_url 中的一次性令牌。 |

### 响应 [#响应-8]

#### HTTP 200 [#http-200-7]

**text/html**

浏览器显示的确认页或结果页。

#### HTTP 302 [#http-302-2]

通过 Location 响应头跳转到服务方授权页或已允许的回跳地址。

### 错误响应 [#错误响应-8]

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| AUTHORIZATION_NOT_FOUND | 404 | 授权或确认链接不存在；重新发起授权 | validation_failure | none | 否 |
| AUTHORIZATION_EXPIRED | 410 | 授权链接超过 30 分钟或已使用；重新发起授权 | validation_failure | retry_from_user | 否 |

设置了 return\_url 时返回 302；未设置时返回 HTTP 200 结果页。

```bash
curl -X POST "https://api.deepraxis.ai/vault/v1/connect/${TOKEN}/deny"
```

## Authorization [#authorization]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| id | string | 是 | 对象标识符 |
| type | "vault_authorization" | 是 | 对象类型 |
| vault_id | string | 是 | 库 ID |
| status | "pending" / "authorizing" / "completed" / "failed" / "expired" | 是 | 状态 |
| resource | string | 是 | 资源地址 |
| secret_name | string | 是 | 关联的 Secret 名称 |
| connect_url | string | 是 | 交给最终用户打开的确认页，30 分钟内有效、只能使用一次 |
| client_registration | "cimd" / "dcr" / null | 是 | cimd：通过客户端元数据 URL 注册；dcr：动态注册客户端；尚未注册时为 null |
| secret_id | string / null | 是 | 关联的 Secret ID；未关联时为 null |
| error | object / null | 是 | 失败原因 |
| error.code | string | 是 | 稳定的错误码 |
| error.message | string | 是 | 可读的错误说明 |
| expires_at | date-time | 是 | 过期时间 |
| created_at | date-time | 是 | 创建时间 |
| updated_at | date-time | 是 | 更新时间 |

## ReturnUrls [#returnurls]

| 字段 | 类型 / 枚举 | 必填 | 说明 |
| --- | --- | --- | --- |
| urls | string[] | 是 | https 地址，精确匹配，最多 10 个 |

# 错误码

错误响应体统一为下面的形状；code 是稳定的错误码，message 给人读。

```json
{
  "request_id": "req_example",
  "error": {
    "code": "SECRET_CONFLICT",
    "message": "A secret named GITHUB_TOKEN already exists",
    "kind": "validation_failure",
    "recovery": "none",
    "retryable": false
  }
}
```

错误体包含 request\_id，可用于定位请求。兼容接口使用下列错误形状；409 的类型为 conflict\_error，不可重试的错误带 x-should-retry: false。

```json
{
  "type": "error",
  "error": {
    "type": "conflict_error",
    "message": "A credential with this name already exists"
  },
  "request_id": "req_example"
}
```

| 错误码 | HTTP | 含义、触发条件与处理 | kind | recovery | 可重试 |
| --- | --- | --- | --- | --- | --- |
| VAULT_NOT_FOUND | 404 | 库不存在或不属于当前账户；检查库 ID | validation_failure | none | 否 |
| SECRET_NOT_FOUND | 404 | Secret 不存在，包括用非法名称查找；检查名称或 ID | validation_failure | none | 否 |
| AUTHORIZATION_NOT_FOUND | 404 | 授权或确认链接不存在；重新发起授权 | validation_failure | none | 否 |
| SECRET_CONFLICT | 409 | 创建时名称已占用；更换名称或更新已有 Secret | validation_failure | none | 否 |
| VAULT_INVALID_STATE | 409 | 向已归档的库或 Secret 写入；改用有效资源 | validation_failure | none | 否 |
| VAULT_LIMIT_EXCEEDED | 400 | 超过有效 Secret 数量上限；先清理不用的 Secret | validation_failure | none | 否 |
| INVALID_PARAMS | 400 | 字段、名称、域名、metadata、分页或回跳地址无效；修正请求 | validation_failure | none | 否 |
| SECRET_KIND_MISMATCH | 400 | 对 static Secret 续期或执行不匹配种类的操作；使用 OAuth Secret | validation_failure | none | 否 |
| VALIDATE_UNSUPPORTED | 400 | 对 static Secret 校验；校验仅支持 OAuth Secret | validation_failure | none | 否 |
| SECRET_TOO_LARGE | 413 | 值超过 16384 字节；缩小值后重试 | validation_failure | none | 否 |
| RATE_LIMITED | 429 | 一分钟内超过授权或校验额度；等待下一窗口 | rate_limit | wait_then_retry | 是 |
| AUTHORIZATION_EXPIRED | 410 | 授权链接超过 30 分钟或已使用；重新发起授权 | validation_failure | retry_from_user | 否 |
| OAUTH_DISCOVERY_FAILED | 400 | 无法发现服务方 OAuth 配置；检查资源地址 | validation_failure | continue_from_problem | 否 |
| OAUTH_REGISTRATION_UNSUPPORTED | 400 | 服务方不接受自动客户端注册；手动添加凭据 | validation_failure | continue_from_problem | 否 |
| OAUTH_ISSUER_MISMATCH | 400 | 授权服务器与预期不一致；重新检查服务地址 | provider_upstream | retry_from_user | 否 |
| OAUTH_STATE_INVALID | 400 | 回调 state 缺失、无效或重放；重新发起授权 | validation_failure | none | 否 |
| OAUTH_EXCHANGE_FAILED | 502 | 服务方拒绝授权码换令牌；重新授权 | provider_upstream | retry_from_user | 否 |
| NOT_IMPLEMENTED | 501 | 功能尚不支持；使用文档列出的替代方式 | execution_failed | none | 否 |

# Application API

（待译）

Application hosts your Workers: upload code and static assets as a version, deploy it, and serve it on its own `*.praxisusercontent.com` URL (use the `url` that publish returns). Concepts and behavior follow Cloudflare Workers (Workers, versions, deployments, static assets with `_headers`/`_redirects`, secrets, bindings), so Cloudflare experience applies. Differences: there are no Service Bindings, so applications call each other with fetch on their public URL; a deployment runs exactly one version at 100 percent (no gradual rollout); changing a secret creates a new version and deploys it. Application runtime data belongs in its own `d1`, `kv` or `r2` components; Database, File and Knowledge are shared content stores that applications can read through public APIs, not private runtime storage. Start with `praxis.application.publish`, which uploads, versions and deploys in one call.

## 基础地址 [#基础地址]

## 鉴权 [#鉴权]

Authorization: Bearer \<PRAXIS\_API\_KEY>

## 端点 [#端点]

* [获取账号子域](/docs/api/native/application/getSubdomain) — `GET /application/v1/subdomain`
* [修改账号子域](/docs/api/native/application/putSubdomain) — `PUT /application/v1/subdomain`
* [列出 Worker](/docs/api/native/application/listWorkers) — `GET /application/v1/workers`
* [创建 Worker](/docs/api/native/application/createWorker) — `POST /application/v1/workers`
* [获取 Worker](/docs/api/native/application/getWorker) — `GET /application/v1/workers/{worker_id}`
* [更新 Worker](/docs/api/native/application/updateWorker) — `PATCH /application/v1/workers/{worker_id}`
* [删除 Worker](/docs/api/native/application/deleteWorker) — `DELETE /application/v1/workers/{worker_id}`
* [恢复 Worker](/docs/api/native/application/restoreWorker) — `POST /application/v1/workers/{worker_id}/restore`
* [列出版本](/docs/api/native/application/listVersions) — `GET /application/v1/workers/{worker_id}/versions`
* [创建版本](/docs/api/native/application/createVersion) — `POST /application/v1/workers/{worker_id}/versions`
* [获取版本](/docs/api/native/application/getVersion) — `GET /application/v1/workers/{worker_id}/versions/{version_id}`
* [列出部署](/docs/api/native/application/listDeployments) — `GET /application/v1/workers/{worker_id}/deployments`
* [创建部署](/docs/api/native/application/createDeployment) — `POST /application/v1/workers/{worker_id}/deployments`
* [获取部署](/docs/api/native/application/getDeployment) — `GET /application/v1/workers/{worker_id}/deployments/{deployment_id}`
* [列出组件](/docs/api/native/application/listComponents) — `GET /application/v1/workers/{worker_id}/components`
* [列出密钥](/docs/api/native/application/listSecrets) — `GET /application/v1/workers/{worker_id}/secrets`
* [写入密钥](/docs/api/native/application/putSecret) — `PUT /application/v1/workers/{worker_id}/secrets/{name}`
* [删除密钥](/docs/api/native/application/deleteSecret) — `DELETE /application/v1/workers/{worker_id}/secrets/{name}`
* [列出授权](/docs/api/native/application/listGrants) — `GET /application/v1/workers/{worker_id}/grants`
* [创建授权](/docs/api/native/application/createGrant) — `POST /application/v1/workers/{worker_id}/grants`
* [删除授权](/docs/api/native/application/deleteGrant) — `DELETE /application/v1/workers/{worker_id}/grants/{grant_id}`
* [列出事件](/docs/api/native/application/listEvents) — `GET /application/v1/workers/{worker_id}/events`
* [创建静态资源上传会话](/docs/api/native/application/createAssetUploadSession) — `POST /application/v1/workers/{worker_id}/assets-upload-session`
* [上传静态资源](/docs/api/native/application/uploadAssets) — `POST /application/v1/assets/upload`

# 获取账号子域

`GET /application/v1/subdomain`

Return the account subdomain used in every Worker URL. A default is created on first use.

**支持状态: supported**

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| subdomain | string | Account subdomain, 8–32 lowercase letters and digits; part of every Worker URL. |

# 修改账号子域

`PUT /application/v1/subdomain`

Change the account subdomain. Every Worker moves to the new address at once; old addresses stop resolving.

**支持状态: supported**

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称        | 类型     | 说明                                                                              |
| --------- | ------ | ------------------------------------------------------------------------------- |
| subdomain | string | Account subdomain, 8–32 lowercase letters and digits; part of every Worker URL. |

```json
{
  "type": "object",
  "required": [
    "subdomain"
  ],
  "properties": {
    "subdomain": {
      "type": "string",
      "description": "Account subdomain, 8–32 lowercase letters and digits; part of every Worker URL.",
      "pattern": "^[a-z0-9]{8,32}$",
      "example": "acme1234"
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| subdomain | string | Account subdomain, 8–32 lowercase letters and digits; part of every Worker URL. |

# 列出 Worker

`GET /application/v1/workers`

List Workers in your account. Filter by status or by label with label.\<key>=\<value>.

**支持状态: supported**

## 参数 [#参数]

| 名称     | 位置    | 类型      | 必填    | 说明                                                                                                                                                                                                    |
| ------ | ----- | ------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| cursor | query | string  | false | next\_cursor from the previous page.                                                                                                                                                                  |
| limit  | query | integer | false | Items per page.                                                                                                                                                                                       |
| status | query | string  | false | Worker status: draft (no deployment yet), active (serving), suspended (stopped by an administrator), deleted (soft-deleted, restorable for 7 days), purging (resources being removed), purged (gone). |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Workers. |
| data[].id | string | Worker ID, prefixed wkr_. |
| data[].name | string | Unique per account; lowercase letters, digits and single hyphens. |
| data[].subdomain | object | Public address of the Worker. |
| data[].tags | array&lt;string&gt; | Up to 8 tags. |
| data[].observability | object | Observability settings. |
| data[].logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| data[].created_on | string | When the Worker was created. |
| data[].updated_on | string | When the Worker last changed. |
| data[].deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| data[].praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| next_cursor | string &#124; null | Cursor for the next page; null on the last page. |

# 创建 Worker

`POST /application/v1/workers`

Create a Worker. It serves nothing until a version is deployed.

**支持状态: supported**

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                    | 类型             | 说明                                                                                                                                                                                                                                                     |
| --------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| name                  | string         | Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved. |
| tags                  | array\<string> | Up to 8 tags.                                                                                                                                                                                                                                          |
| observability         | object         | Observability settings.                                                                                                                                                                                                                                |
| observability.enabled | boolean        | Collect logs.                                                                                                                                                                                                                                          |
| subdomain             | object         | Subdomain settings.                                                                                                                                                                                                                                    |
| subdomain.enabled     | boolean        | Serve the Worker on its public subdomain (default true).                                                                                                                                                                                               |
| praxis                | object         | Praxis settings.                                                                                                                                                                                                                                       |
| praxis.labels         | object         | Up to 16 labels.                                                                                                                                                                                                                                       |

```json
{
  "type": "object",
  "required": [
    "name"
  ],
  "properties": {
    "name": {
      "type": "string",
      "description": "Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved.",
      "pattern": "^(?!(?:www|api|admin|app|canary|canary-probe|status|docs|console)$)(?!.*--)[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$",
      "example": "my-app"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "maxItems": 8,
      "description": "Up to 8 tags."
    },
    "observability": {
      "type": "object",
      "description": "Observability settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Collect logs."
        }
      }
    },
    "subdomain": {
      "type": "object",
      "description": "Subdomain settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Serve the Worker on its public subdomain (default true)."
        }
      }
    },
    "praxis": {
      "type": "object",
      "description": "Praxis settings.",
      "required": [],
      "properties": {
        "labels": {
          "type": "object",
          "additionalProperties": {
            "type": "string"
          },
          "description": "Up to 16 labels."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Worker ID, prefixed wkr_. |
| name | string | Unique per account; lowercase letters, digits and single hyphens. |
| subdomain | object | Public address of the Worker. |
| subdomain.enabled | boolean | Whether the public subdomain serves this Worker. |
| subdomain.url | string | Public URL of the Worker. |
| tags | array&lt;string&gt; | Up to 8 tags. |
| observability | object | Observability settings. |
| observability.enabled | boolean | Whether logs are collected. |
| logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| created_on | string | When the Worker was created. |
| updated_on | string | When the Worker last changed. |
| deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| praxis.status | string | Worker status: draft (no deployment yet), active (serving), suspended (stopped by an administrator), deleted (soft-deleted, restorable for 7 days), purging (resources being removed), purged (gone). |
| praxis.current_deployment_id | string &#124; null | ID of the active deployment. |
| praxis.labels | object | Up to 16 key-value labels for your own grouping. |
| praxis.deleted_on | string &#124; null | When the Worker was deleted. |
| praxis.purge_on | string &#124; null | When a deleted Worker is permanently removed. |
| praxis.suspended_reason | string &#124; null | Why an administrator suspended the Worker. |

# 获取 Worker

`GET /application/v1/workers/{worker_id}`

Get a Worker. expand returns related objects in the same response.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置    | 类型     | 必填    | 说明                                                                   |
| ---------- | ----- | ------ | ----- | -------------------------------------------------------------------- |
| worker\_id | path  | string | true  | Worker ID (wkr\_…).                                                  |
| expand     | query | string | false | Comma-separated: versions, deployments, components, secrets, grants. |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Worker ID, prefixed wkr_. |
| name | string | Unique per account; lowercase letters, digits and single hyphens. |
| subdomain | object | Public address of the Worker. |
| subdomain.enabled | boolean | Whether the public subdomain serves this Worker. |
| subdomain.url | string | Public URL of the Worker. |
| tags | array&lt;string&gt; | Up to 8 tags. |
| observability | object | Observability settings. |
| observability.enabled | boolean | Whether logs are collected. |
| logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| created_on | string | When the Worker was created. |
| updated_on | string | When the Worker last changed. |
| deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| praxis.status | string | Worker status: draft (no deployment yet), active (serving), suspended (stopped by an administrator), deleted (soft-deleted, restorable for 7 days), purging (resources being removed), purged (gone). |
| praxis.current_deployment_id | string &#124; null | ID of the active deployment. |
| praxis.labels | object | Up to 16 key-value labels for your own grouping. |
| praxis.deleted_on | string &#124; null | When the Worker was deleted. |
| praxis.purge_on | string &#124; null | When a deleted Worker is permanently removed. |
| praxis.suspended_reason | string &#124; null | Why an administrator suspended the Worker. |
| expanded | object | Present only for the members named in expand. |
| expanded.versions | object | Versions of the Worker, newest first. |
| expanded.deployments | object | Deployments of the Worker, newest first. |
| expanded.components | array&lt;object&gt; | Components of the Worker. |
| expanded.secrets | array&lt;object&gt; | Secrets of the Worker (names only). |
| expanded.grants | array&lt;object&gt; | Grants of the Worker. |

# 更新 Worker

`PATCH /application/v1/workers/{worker_id}`

Change name, tags, observability, subdomain or labels. Omitted fields stay unchanged.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                    | 类型             | 说明                                                                                                                                                                                                                                                     |
| --------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| name                  | string         | Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved. |
| tags                  | array\<string> | Replaces the tags.                                                                                                                                                                                                                                     |
| observability         | object         | Observability settings.                                                                                                                                                                                                                                |
| observability.enabled | boolean        | Collect logs.                                                                                                                                                                                                                                          |
| subdomain             | object         | Subdomain settings.                                                                                                                                                                                                                                    |
| subdomain.enabled     | boolean        | Serve the Worker on its public subdomain.                                                                                                                                                                                                              |
| praxis                | object         | Praxis settings.                                                                                                                                                                                                                                       |
| praxis.labels         | object         | Replaces the labels.                                                                                                                                                                                                                                   |

```json
{
  "type": "object",
  "required": [],
  "properties": {
    "name": {
      "type": "string",
      "description": "Worker name, unique in your account: 3–40 lowercase letters, digits or hyphens, starting and ending with a letter or digit, with no two hyphens in a row. The names www, api, admin, app, canary, canary-probe, status, docs and console are reserved.",
      "pattern": "^(?!(?:www|api|admin|app|canary|canary-probe|status|docs|console)$)(?!.*--)[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$",
      "example": "my-app"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "maxItems": 8,
      "description": "Replaces the tags."
    },
    "observability": {
      "type": "object",
      "description": "Observability settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Collect logs."
        }
      }
    },
    "subdomain": {
      "type": "object",
      "description": "Subdomain settings.",
      "required": [
        "enabled"
      ],
      "properties": {
        "enabled": {
          "type": "boolean",
          "description": "Serve the Worker on its public subdomain."
        }
      }
    },
    "praxis": {
      "type": "object",
      "description": "Praxis settings.",
      "required": [],
      "properties": {
        "labels": {
          "type": "object",
          "additionalProperties": {
            "type": "string"
          },
          "description": "Replaces the labels."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Worker ID, prefixed wkr_. |
| name | string | Unique per account; lowercase letters, digits and single hyphens. |
| subdomain | object | Public address of the Worker. |
| subdomain.enabled | boolean | Whether the public subdomain serves this Worker. |
| subdomain.url | string | Public URL of the Worker. |
| tags | array&lt;string&gt; | Up to 8 tags. |
| observability | object | Observability settings. |
| observability.enabled | boolean | Whether logs are collected. |
| logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| created_on | string | When the Worker was created. |
| updated_on | string | When the Worker last changed. |
| deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| praxis.status | string | Worker status: draft (no deployment yet), active (serving), suspended (stopped by an administrator), deleted (soft-deleted, restorable for 7 days), purging (resources being removed), purged (gone). |
| praxis.current_deployment_id | string &#124; null | ID of the active deployment. |
| praxis.labels | object | Up to 16 key-value labels for your own grouping. |
| praxis.deleted_on | string &#124; null | When the Worker was deleted. |
| praxis.purge_on | string &#124; null | When a deleted Worker is permanently removed. |
| praxis.suspended_reason | string &#124; null | Why an administrator suspended the Worker. |

# 删除 Worker

`DELETE /application/v1/workers/{worker_id}`

Soft-delete a Worker. Unlike Cloudflare, deletion is reversible: it stops serving at once and can be restored with RestoreWorker for 7 days, after which it is purged.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Worker ID, prefixed wkr_. |
| name | string | Unique per account; lowercase letters, digits and single hyphens. |
| subdomain | object | Public address of the Worker. |
| subdomain.enabled | boolean | Whether the public subdomain serves this Worker. |
| subdomain.url | string | Public URL of the Worker. |
| tags | array&lt;string&gt; | Up to 8 tags. |
| observability | object | Observability settings. |
| observability.enabled | boolean | Whether logs are collected. |
| logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| created_on | string | When the Worker was created. |
| updated_on | string | When the Worker last changed. |
| deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| praxis.status | string | Worker status: draft (no deployment yet), active (serving), suspended (stopped by an administrator), deleted (soft-deleted, restorable for 7 days), purging (resources being removed), purged (gone). |
| praxis.current_deployment_id | string &#124; null | ID of the active deployment. |
| praxis.labels | object | Up to 16 key-value labels for your own grouping. |
| praxis.deleted_on | string &#124; null | When the Worker was deleted. |
| praxis.purge_on | string &#124; null | When a deleted Worker is permanently removed. |
| praxis.suspended_reason | string &#124; null | Why an administrator suspended the Worker. |

# 恢复 Worker

`POST /application/v1/workers/{worker_id}/restore`

Bring back a soft-deleted Worker within 7 days of deletion, with its versions and deployments. Cloudflare has no equivalent.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Worker ID, prefixed wkr_. |
| name | string | Unique per account; lowercase letters, digits and single hyphens. |
| subdomain | object | Public address of the Worker. |
| subdomain.enabled | boolean | Whether the public subdomain serves this Worker. |
| subdomain.url | string | Public URL of the Worker. |
| tags | array&lt;string&gt; | Up to 8 tags. |
| observability | object | Observability settings. |
| observability.enabled | boolean | Whether logs are collected. |
| logpush | boolean | Always false: unlike Cloudflare, Logpush is not offered. |
| created_on | string | When the Worker was created. |
| updated_on | string | When the Worker last changed. |
| deployed_on | string &#124; null | When the current deployment became active; null before the first deployment. |
| praxis | object | Platform fields: lifecycle status, labels, and soft-delete timestamps. |
| praxis.status | string | Worker status: draft (no deployment yet), active (serving), suspended (stopped by an administrator), deleted (soft-deleted, restorable for 7 days), purging (resources being removed), purged (gone). |
| praxis.current_deployment_id | string &#124; null | ID of the active deployment. |
| praxis.labels | object | Up to 16 key-value labels for your own grouping. |
| praxis.deleted_on | string &#124; null | When the Worker was deleted. |
| praxis.purge_on | string &#124; null | When a deleted Worker is permanently removed. |
| praxis.suspended_reason | string &#124; null | Why an administrator suspended the Worker. |

# 列出版本

`GET /application/v1/workers/{worker_id}/versions`

List the versions of a Worker, newest first, to pick one to deploy or inspect. Page with next\_cursor.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置    | 类型      | 必填    | 说明                                   |
| ---------- | ----- | ------- | ----- | ------------------------------------ |
| worker\_id | path  | string  | true  | Worker ID (wkr\_…).                  |
| cursor     | query | string  | false | next\_cursor from the previous page. |
| limit      | query | integer | false | Items per page.                      |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Versions, newest first. |
| data[].id | string | Version ID, prefixed ver_. |
| data[].number | integer | Per-Worker counter (v1, v2, …). |
| data[].created_on | string | When the version was created. |
| data[].main_module | string &#124; null | Entry module name, or null for a version containing only static assets. |
| data[].modules | array&lt;object&gt; | Module names and types; content is never returned. |
| data[].compatibility_date | string | Workers runtime compatibility date. |
| data[].compatibility_flags | array&lt;string&gt; | Runtime compatibility flags. |
| data[].bindings | array&lt;object&gt; | Bindings; secret values are never returned. |
| data[].assets | object &#124; null | Static asset settings. |
| data[].annotations | object | Free-form annotations. |
| data[].author_id | string &#124; null | Who created the version. |
| data[].source | string | Upload origin, e.g. api or sdk. |
| data[].urls | array&lt;string&gt; | Preview URLs of this version. |
| data[].praxis | object | Platform fields: owning Worker, build source, script size and asset manifest summary. |
| next_cursor | string &#124; null | Cursor for the next page; null on the last page. |

# 创建版本

`POST /application/v1/workers/{worker_id}/versions`

Upload code and bindings as a new version; a version serves nothing until deployed. Set deploy true to create the pending deployment in the same call. Rejected binding types return UNSUPPORTED.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                          | 类型             | 说明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| --------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| deploy                      | boolean        | Also create a deployment of this version (own face only; on the compatible face use the deploy query parameter).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| main\_module                | string         | Entry module name; must equal the name of one of modules. Defaults to the first module; omit it when there are no modules.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| modules                     | array\<object> | Inline modules.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| modules\[].name             | string         | Module file name.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| modules\[].content\_type    | string         | Module content type: application/javascript+module, text/javascript, application/javascript, application/wasm, text/plain, application/octet-stream, application/json or application/x-python. Omit it to use application/javascript+module.                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| modules\[].content\_base64  | string         | Module content, base64.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| compatibility\_date         | string         | Workers runtime compatibility date: a real date in YYYY-MM-DD form, not later than today (UTC). Defaults to today (UTC).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| compatibility\_flags        | array\<string> | Runtime compatibility flags.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| bindings                    | array\<object> | Bindings of this version.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| bindings\[].type            | string         | Binding type; see the binding description for what each needs and which are unavailable.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| bindings\[].name            | string         | Name of the binding in the Worker's env: 1–64 letters, digits or underscores, not starting with a digit; unique within a version.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| assets                      | object         | Static assets. Pass either manifest (every file already uploaded through an upload session) or jwt (the completion token from the last upload batch), not both.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| assets.config               | object         | Routing settings for the static assets.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| assets.manifest             | object         | Map of static file path to content hash and byte size. Paths start with /; the same hash must declare the same size. The root paths /\_headers and /\_redirects are response-header and redirect rule files and are not served as assets; same-named files in subdirectories are ordinary assets. \_headers allows at most 100 rules and 2000 characters per line (whitespace included); \_redirects allows at most 2000 static and 100 dynamic rules and 1000 characters per rule (whitespace included), and rules after the first dynamic rule count toward the dynamic quota. Exceeding a limit makes CreateVersion return INVALID\_PARAMS, with violations.field pointing at the manifest entry. |
| assets.jwt                  | string         | Completion token from the last assets/upload batch; it carries this version's manifest, so do not also pass manifest.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| annotations                 | object         | Free-form annotations.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| annotations.workers/message | string         | Version message.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| annotations.workers/tag     | string         | Version tag.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| praxis                      | object         | Praxis settings.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| praxis.source               | object         | Build source: \{type:inline}, \{type:machine, path} or \{type:file, file\_id}.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |

```json
{
  "type": "object",
  "required": [],
  "properties": {
    "deploy": {
      "type": "boolean",
      "description": "Also create a deployment of this version (own face only; on the compatible face use the deploy query parameter)."
    },
    "main_module": {
      "type": "string",
      "description": "Entry module name; must equal the name of one of modules. Defaults to the first module; omit it when there are no modules.",
      "example": "index.js"
    },
    "modules": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/application-Module"
      },
      "description": "Inline modules."
    },
    "compatibility_date": {
      "type": "string",
      "description": "Workers runtime compatibility date: a real date in YYYY-MM-DD form, not later than today (UTC). Defaults to today (UTC).",
      "format": "date",
      "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
      "example": "2026-01-01"
    },
    "compatibility_flags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "description": "Runtime compatibility flags."
    },
    "bindings": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/application-Binding"
      },
      "description": "Bindings of this version."
    },
    "assets": {
      "type": "object",
      "description": "Static assets. Pass either manifest (every file already uploaded through an upload session) or jwt (the completion token from the last upload batch), not both.",
      "required": [],
      "properties": {
        "config": {
          "$ref": "#/components/schemas/application-AssetsConfig",
          "description": "Routing settings for the static assets."
        },
        "manifest": {
          "$ref": "#/components/schemas/application-AssetManifest"
        },
        "jwt": {
          "type": "string",
          "description": "Completion token from the last assets/upload batch; it carries this version's manifest, so do not also pass manifest."
        }
      }
    },
    "annotations": {
      "type": "object",
      "description": "Free-form annotations.",
      "required": [],
      "properties": {
        "workers/message": {
          "type": "string",
          "description": "Version message."
        },
        "workers/tag": {
          "type": "string",
          "description": "Version tag."
        }
      }
    },
    "praxis": {
      "type": "object",
      "description": "Praxis settings.",
      "required": [],
      "properties": {
        "source": {
          "type": "object",
          "additionalProperties": true,
          "description": "Build source: {type:inline}, {type:machine, path} or {type:file, file_id}."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| version | object | The version that was created. |
| version.id | string | Version ID, prefixed ver_. |
| version.number | integer | Per-Worker counter (v1, v2, …). |
| version.created_on | string | When the version was created. |
| version.main_module | string &#124; null | Entry module name, or null for a version containing only static assets. |
| version.modules | array&lt;object&gt; | Module names and types; content is never returned. |
| version.compatibility_date | string | Workers runtime compatibility date. |
| version.compatibility_flags | array&lt;string&gt; | Runtime compatibility flags. |
| version.bindings | array&lt;object&gt; | Bindings; secret values are never returned. |
| version.assets | object &#124; null | Static asset settings. |
| version.annotations | object | Free-form annotations. |
| version.author_id | string &#124; null | Who created the version. |
| version.source | string | Upload origin, e.g. api or sdk. |
| version.urls | array&lt;string&gt; | Preview URLs of this version. |
| version.praxis | object | Platform fields: owning Worker, build source, script size and asset manifest summary. |
| deployment | object &#124; null | The pending deployment; null unless deploy was requested. |
| deployment.id | string | Deployment ID, prefixed dep_. |
| deployment.created_on | string | When the deployment was created. |
| deployment.source | string | Origin: api, sdk, console or rollback. |
| deployment.strategy | string | Rollout strategy. |
| deployment.versions | array&lt;object&gt; | Exactly one version at 100 percent. |
| deployment.annotations | object | Free-form annotations. |
| deployment.author_email | string &#124; null | Who created the deployment. |
| deployment.praxis | object | Platform fields: deployments run asynchronously, so track status, progress and error here. |

# 获取版本

`GET /application/v1/workers/{worker_id}/versions/{version_id}`

Get one version of a Worker with its modules, bindings and asset settings; secret values are never returned.

**支持状态: supported**

## 参数 [#参数]

| 名称          | 位置   | 类型     | 必填   | 说明                   |
| ----------- | ---- | ------ | ---- | -------------------- |
| worker\_id  | path | string | true | Worker ID (wkr\_…).  |
| version\_id | path | string | true | Version ID (ver\_…). |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Version ID, prefixed ver_. |
| number | integer | Per-Worker counter (v1, v2, …). |
| created_on | string | When the version was created. |
| main_module | string &#124; null | Entry module name, or null for a version containing only static assets. |
| modules | array&lt;object&gt; | Module names and types; content is never returned. |
| modules[].name | string | Module name. |
| modules[].content_type | string | MIME type. |
| compatibility_date | string | Workers runtime compatibility date. |
| compatibility_flags | array&lt;string&gt; | Runtime compatibility flags. |
| bindings | array&lt;object&gt; | Bindings; secret values are never returned. |
| bindings[].type | string | Binding type; see the binding description for what each needs and which are unavailable. |
| bindings[].name | string | Name of the binding in the Worker's env: 1–64 letters, digits or underscores, not starting with a digit; unique within a version. |
| assets | object &#124; null | Static asset settings. |
| assets.config | object | Routing settings for the static assets. |
| annotations | object | Free-form annotations. |
| annotations.workers/message | string | Version message. |
| annotations.workers/tag | string | Version tag. |
| author_id | string &#124; null | Who created the version. |
| source | string | Upload origin, e.g. api or sdk. |
| urls | array&lt;string&gt; | Preview URLs of this version. |
| praxis | object | Platform fields: owning Worker, build source, script size and asset manifest summary. |
| praxis.worker_id | string | Owning Worker. |
| praxis.source | object | Where the build came from: inline, machine (a tar.gz on a session machine) or file (an uploaded tar.gz). |
| praxis.size_bytes | integer | Script size in bytes. |
| praxis.assets_manifest | object &#124; null | Static asset manifest summary. |

# 列出部署

`GET /application/v1/workers/{worker_id}/deployments`

List the deployments of a Worker, newest first; the first active one is serving. Page with next\_cursor.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置    | 类型      | 必填    | 说明                                   |
| ---------- | ----- | ------- | ----- | ------------------------------------ |
| worker\_id | path  | string  | true  | Worker ID (wkr\_…).                  |
| cursor     | query | string  | false | next\_cursor from the previous page. |
| limit      | query | integer | false | Items per page.                      |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Deployments, newest first. |
| data[].id | string | Deployment ID, prefixed dep_. |
| data[].created_on | string | When the deployment was created. |
| data[].source | string | Origin: api, sdk, console or rollback. |
| data[].strategy | string | Rollout strategy. |
| data[].versions | array&lt;object&gt; | Exactly one version at 100 percent. |
| data[].annotations | object | Free-form annotations. |
| data[].author_email | string &#124; null | Who created the deployment. |
| data[].praxis | object | Platform fields: deployments run asynchronously, so track status, progress and error here. |
| next_cursor | string &#124; null | Cursor for the next page; null on the last page. |

# 创建部署

`POST /application/v1/workers/{worker_id}/deployments`

Deploy one version to serve the Worker. Unlike Cloudflare, a deployment holds exactly one version at 100 percent (no gradual rollout), so strategy must be percentage. Deployment is asynchronous; poll the deployment until praxis.status is active or failed.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称                          | 类型             | 说明                                                                   |
| --------------------------- | -------------- | -------------------------------------------------------------------- |
| strategy                    | string         | Rollout strategy.                                                    |
| versions                    | array\<object> | Exactly one version at 100 percent.                                  |
| versions\[].version\_id     | string         | Version to deploy.                                                   |
| versions\[].percentage      | number         | Must be 100.                                                         |
| force                       | boolean        | Own face only; on the compatible face use the force query parameter. |
| annotations                 | object         | Free-form annotations.                                               |
| annotations.workers/message | string         | Deployment message.                                                  |

```json
{
  "type": "object",
  "required": [
    "strategy",
    "versions"
  ],
  "properties": {
    "strategy": {
      "type": "string",
      "description": "Rollout strategy.",
      "enum": [
        "percentage"
      ],
      "x-enum-descriptions": {
        "percentage": "Split traffic by percentage; only a single version at 100 is accepted."
      },
      "example": "percentage"
    },
    "versions": {
      "type": "array",
      "description": "Exactly one version at 100 percent.",
      "items": {
        "type": "object",
        "required": [
          "version_id",
          "percentage"
        ],
        "properties": {
          "version_id": {
            "type": "string",
            "description": "Version to deploy."
          },
          "percentage": {
            "type": "number",
            "description": "Must be 100."
          }
        }
      }
    },
    "force": {
      "type": "boolean",
      "description": "Own face only; on the compatible face use the force query parameter."
    },
    "annotations": {
      "type": "object",
      "description": "Free-form annotations.",
      "required": [],
      "properties": {
        "workers/message": {
          "type": "string",
          "description": "Deployment message."
        }
      }
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Deployment ID, prefixed dep_. |
| created_on | string | When the deployment was created. |
| source | string | Origin: api, sdk, console or rollback. |
| strategy | string | Rollout strategy. |
| versions | array&lt;object&gt; | Exactly one version at 100 percent. |
| versions[].version_id | string | Deployed version. |
| versions[].percentage | number | Traffic share; always 100. |
| annotations | object | Free-form annotations. |
| annotations.workers/message | string | Deployment message. |
| annotations.workers/triggered_by | string | What triggered the deployment. |
| author_email | string &#124; null | Who created the deployment. |
| praxis | object | Platform fields: deployments run asynchronously, so track status, progress and error here. |
| praxis.worker_id | string | Owning Worker. |
| praxis.status | string | Deployment status: pending (queued), uploading (pushing components and assets), activating (switching traffic), active (serving), superseded (replaced by a later deployment), failed (see error), cancelled (replaced before it finished). |
| praxis.progress | object &#124; null | Upload progress. |
| praxis.error | object &#124; null | Why the deployment failed. |
| praxis.finished_on | string &#124; null | When the deployment reached a final status. |

# 获取部署

`GET /application/v1/workers/{worker_id}/deployments/{deployment_id}`

Get one deployment with its status and upload progress; poll this after CreateDeployment until praxis.status is active or failed.

**支持状态: supported**

## 参数 [#参数]

| 名称             | 位置   | 类型     | 必填   | 说明                                                                     |
| -------------- | ---- | ------ | ---- | ---------------------------------------------------------------------- |
| worker\_id     | path | string | true | Worker ID (wkr\_…).                                                    |
| deployment\_id | path | string | true | ID from the id of CreateDeployment or ListDeployments, prefixed dep\_. |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Deployment ID, prefixed dep_. |
| created_on | string | When the deployment was created. |
| source | string | Origin: api, sdk, console or rollback. |
| strategy | string | Rollout strategy. |
| versions | array&lt;object&gt; | Exactly one version at 100 percent. |
| versions[].version_id | string | Deployed version. |
| versions[].percentage | number | Traffic share; always 100. |
| annotations | object | Free-form annotations. |
| annotations.workers/message | string | Deployment message. |
| annotations.workers/triggered_by | string | What triggered the deployment. |
| author_email | string &#124; null | Who created the deployment. |
| praxis | object | Platform fields: deployments run asynchronously, so track status, progress and error here. |
| praxis.worker_id | string | Owning Worker. |
| praxis.status | string | Deployment status: pending (queued), uploading (pushing components and assets), activating (switching traffic), active (serving), superseded (replaced by a later deployment), failed (see error), cancelled (replaced before it finished). |
| praxis.progress | object &#124; null | Upload progress. |
| praxis.error | object &#124; null | Why the deployment failed. |
| praxis.finished_on | string &#124; null | When the deployment reached a final status. |

# 列出组件

`GET /application/v1/workers/{worker_id}/components`

List the databases, namespaces and buckets this Worker owns.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string | Component ID, prefixed cmp_. |
| [].worker_id | string | Owning Worker. |
| [].binding | string | Binding name in the Worker's env. |
| [].type | string | Component type: d1 database, kv namespace or r2 bucket. |
| [].status | string | Component status: provisioning, ready, failed, deleting or deleted. |
| [].location_hint | string | Always apac. |
| [].usage | object &#124; null | Storage usage. |
| [].usage.bytes | integer | Stored bytes. |
| [].usage.items | integer | Stored items. |
| [].created_on | string | When the component was created. |

# 列出密钥

`GET /application/v1/workers/{worker_id}/secrets`

List secret names and sources. Values are never returned.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].worker_id | string | Owning Worker. |
| [].name | string | Secret name, as seen by the Worker's env. |
| [].source | object | &#123;type: value&#125; for a stored value, or &#123;type: vault, vault_id, secret&#125; for a vault reference. Values are never returned. |
| [].updated_on | string | When the secret last changed. |

# 写入密钥

`PUT /application/v1/workers/{worker_id}/secrets/{name}`

Create or replace a secret by value or vault reference. Unlike Cloudflare, this derives a new version from the current one and deploys it, so the change is live only once that deployment is active.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                                                                                                       |
| ---------- | ---- | ------ | ---- | -------------------------------------------------------------------------------------------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…).                                                                                      |
| name       | path | string | true | Secret name as seen in the Worker's env: 1–64 letters, digits or underscores, not starting with a digit. |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称     | 类型     | 说明                                                                                                |
| ------ | ------ | ------------------------------------------------------------------------------------------------- |
| source | object | \{type: value, text} stores a value; \{type: vault, vault\_id, secret} references a vault secret. |

```json
{
  "type": "object",
  "required": [
    "source"
  ],
  "properties": {
    "source": {
      "type": "object",
      "additionalProperties": true,
      "description": "{type: value, text} stores a value; {type: vault, vault_id, secret} references a vault secret."
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| secret | object | The secret after the write; its value is not returned. |
| secret.worker_id | string | Owning Worker. |
| secret.name | string | Secret name, as seen by the Worker's env. |
| secret.source | object | &#123;type: value&#125; for a stored value, or &#123;type: vault, vault_id, secret&#125; for a vault reference. Values are never returned. |
| secret.updated_on | string | When the secret last changed. |
| deployment | object | The deployment of the version derived from this change. |
| deployment.id | string | Deployment ID, prefixed dep_. |
| deployment.created_on | string | When the deployment was created. |
| deployment.source | string | Origin: api, sdk, console or rollback. |
| deployment.strategy | string | Rollout strategy. |
| deployment.versions | array&lt;object&gt; | Exactly one version at 100 percent. |
| deployment.annotations | object | Free-form annotations. |
| deployment.author_email | string &#124; null | Who created the deployment. |
| deployment.praxis | object | Platform fields: deployments run asynchronously, so track status, progress and error here. |

# 删除密钥

`DELETE /application/v1/workers/{worker_id}/secrets/{name}`

Delete a secret. Unlike Cloudflare, this derives a new version without it and deploys that version.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                                                                                                       |
| ---------- | ---- | ------ | ---- | -------------------------------------------------------------------------------------------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…).                                                                                      |
| name       | path | string | true | Secret name as seen in the Worker's env: 1–64 letters, digits or underscores, not starting with a digit. |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| deployment | object | The deployment of the version derived without this secret. |
| deployment.id | string | Deployment ID, prefixed dep_. |
| deployment.created_on | string | When the deployment was created. |
| deployment.source | string | Origin: api, sdk, console or rollback. |
| deployment.strategy | string | Rollout strategy. |
| deployment.versions | array&lt;object&gt; | Exactly one version at 100 percent. |
| deployment.annotations | object | Free-form annotations. |
| deployment.author_email | string &#124; null | Who created the deployment. |
| deployment.praxis | object | Platform fields: deployments run asynchronously, so track status, progress and error here. |

# 列出授权

`GET /application/v1/workers/{worker_id}/grants`

List resources this Worker's platform token may access.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| [].id | string | Grant ID, prefixed grt_. |
| [].worker_id | string | Owning Worker. |
| [].resource | object | Granted resource. |
| [].resource.type | string | Resource type. |
| [].resource.id | string | Resource ID. |
| [].access | string | Access level. |
| [].created_on | string | When the grant was created. |

# 创建授权

`POST /application/v1/workers/{worker_id}/grants`

Let this Worker's platform token access one of your databases, folders or knowledge bases.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称            | 类型     | 说明                           |
| ------------- | ------ | ---------------------------- |
| resource      | object | Resource to grant.           |
| resource.type | string | Resource type.               |
| resource.id   | string | Resource ID in your account. |
| access        | string | Access level.                |

```json
{
  "type": "object",
  "required": [
    "resource",
    "access"
  ],
  "properties": {
    "resource": {
      "type": "object",
      "description": "Resource to grant.",
      "required": [
        "type",
        "id"
      ],
      "properties": {
        "type": {
          "type": "string",
          "description": "Resource type.",
          "enum": [
            "database",
            "folder",
            "knowledge"
          ],
          "x-enum-descriptions": {
            "database": "A database.",
            "folder": "A file folder.",
            "knowledge": "A knowledge base."
          },
          "example": "database"
        },
        "id": {
          "type": "string",
          "description": "Resource ID in your account.",
          "example": "db_01example"
        }
      }
    },
    "access": {
      "type": "string",
      "description": "Access level.",
      "enum": [
        "read",
        "read_write"
      ],
      "x-enum-descriptions": {
        "read": "Read only.",
        "read_write": "Read and write."
      },
      "example": "read"
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| id | string | Grant ID, prefixed grt_. |
| worker_id | string | Owning Worker. |
| resource | object | Granted resource. |
| resource.type | string | Resource type. |
| resource.id | string | Resource ID. |
| access | string | Access level. |
| created_on | string | When the grant was created. |

# 删除授权

`DELETE /application/v1/workers/{worker_id}/grants/{grant_id}`

Revoke a grant so this Worker's platform token can no longer access the granted resource. Takes effect for new requests at once.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |
| grant\_id  | path | string | true | Grant ID (grt\_…).  |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| deleted | boolean | Always true. |

# 列出事件

`GET /application/v1/workers/{worker_id}/events`

List lifecycle events of a Worker in sequence order.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置    | 类型      | 必填    | 说明                                        |
| ---------- | ----- | ------- | ----- | ----------------------------------------- |
| worker\_id | path  | string  | true  | Worker ID (wkr\_…).                       |
| after\_seq | query | integer | false | Return events after this sequence number. |
| limit      | query | integer | false | Items per page.                           |

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| data | array&lt;object&gt; | Events in sequence order. |
| data[].seq | integer | Monotonic sequence within the Worker. |
| data[].id | string | Event ID. |
| data[].type | string | Event type, e.g. deployment.status_active. |
| data[].processed_at | string | When the event was recorded. |
| data[].worker_id | string | Worker the event belongs to. |
| data[].version_id | string | Related version. |
| data[].deployment_id | string | Related deployment. |
| data[].component_id | string | Related component. |
| data[].detail | object | Event-specific detail. |
| next_cursor | string &#124; null | Cursor for the next page; null on the last page. |

# 创建静态资源上传会话

`POST /application/v1/workers/{worker_id}/assets-upload-session`

Declare the static file manifest. The answer lists the hashes still missing, grouped into upload batches, and an upload token.

**支持状态: supported**

## 参数 [#参数]

| 名称         | 位置   | 类型     | 必填   | 说明                  |
| ---------- | ---- | ------ | ---- | ------------------- |
| worker\_id | path | string | true | Worker ID (wkr\_…). |

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称       | 类型     | 说明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| -------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| manifest | object | Map of static file path to content hash and byte size. Paths start with /; the same hash must declare the same size. The root paths /\_headers and /\_redirects are response-header and redirect rule files and are not served as assets; same-named files in subdirectories are ordinary assets. \_headers allows at most 100 rules and 2000 characters per line (whitespace included); \_redirects allows at most 2000 static and 100 dynamic rules and 1000 characters per rule (whitespace included), and rules after the first dynamic rule count toward the dynamic quota. Exceeding a limit makes CreateVersion return INVALID\_PARAMS, with violations.field pointing at the manifest entry. |

```json
{
  "type": "object",
  "required": [
    "manifest"
  ],
  "properties": {
    "manifest": {
      "$ref": "#/components/schemas/application-AssetManifest"
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| jwt | string | Upload token, valid for one hour. |
| buckets | array&lt;array&lt;string&gt;&gt; | Hashes still missing, grouped into upload batches. |

# 上传静态资源

`POST /application/v1/assets/upload`

Upload one batch: files maps hash to base64 content. The last batch returns the completion token.

**支持状态: supported**

## 请求体 (application/json) [#请求体-applicationjson]

必填: true

| 名称    | 类型     | 说明                             |
| ----- | ------ | ------------------------------ |
| jwt   | string | Upload token from the session. |
| files | object | Hash → base64 file content.    |

```json
{
  "type": "object",
  "required": [
    "jwt",
    "files"
  ],
  "properties": {
    "jwt": {
      "type": "string",
      "description": "Upload token from the session."
    },
    "files": {
      "type": "object",
      "additionalProperties": {
        "type": "string"
      },
      "description": "Hash → base64 file content."
    }
  }
}
```

## 响应 [#响应]

### HTTP 200 [#http-200]

Success

**application/json**

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| jwt | string &#124; null | Completion token after the last batch; null for earlier batches. |

导出自 Praxis 文档 · 2026-10-20 · 共 490 页
