<!-- Generated from the prerendered /docs/ page. Do not edit independently. -->

来源：https://massrender.dev.framefuture.com/docs/

OpenAPI：https://massrender.dev.framefuture.com/openapi/render-public-v1.openapi.yaml

<a id="overview"></a>



# 把视频项目接入生产系统

万象渲染为不同视频代码项目提供统一的项目管理、鉴权和异步任务 API。可以从内置模板快速生成首个视频，也可以接入已有项目并继续二创；渲染运行时的部署、扩缩容与结果存储由平台处理。

**当前文档重点：**统一接入协议，以及已经通过阿里云函数计算验证分片并发渲染链路。

<a id="projects"></a>



## 支持的项目

平台按项目类型选择对应的构建与渲染适配器。两种项目都是上传构建产物创建版本， 渲染运行时的部署与扩缩容由平台处理。

| 项目类型 | 输入 | 接入方式 | 运行时 |
| --- | --- | --- | --- |
| hyperframes | 项目入口 + 渲染参数 | 项目构建产物 | 项目适配器 |
| remotion | compositionId + inputProps | 版本化 bundle | remotion-fc |

<a id="pricing"></a>



## 计费方式

### 仓库参考基础价

仓库参考基础价来自当前仓库默认配置，不代表部署价格、账号报价或最终账单。下表列出清晰度、16:9 横屏参考尺寸与渲染分钟费率。

参考尺寸仅展示 16:9 横屏示例。实际输出按清晰度档位缩放，并保留原始宽高比与横竖方向，竖屏或 4:3 内容不会因此变成 16:9 横屏。

| 清晰度 | 16:9 横屏参考尺寸（像素） | 仓库参考基础价 / 成片分钟 |
| --- | --- | --- |
| 标清 720p | 1280 × 720 | ¥0.35 |
| 高清 1080p | 1920 × 1080 | ¥0.50 |
| 超清 1440p | 2560 × 1440 | ¥0.80 |

### 账号适用费率

登录后从服务端获取当前账号适用的渲染单价。服务端在创建渲染任务时冻结适用费率。单价不是总价报价或费用上限。

### 最终计量账单

最终账单由服务端按采纳的计量项结算。渲染按实际成片秒数折算分钟，不足一分钟不按整分钟收取，等待时间不作为成片时长。成功结果缺少成片时长时，服务端可能改用已上报的计算时长作为兜底。

每个正数计量项取实际数量与该项最低数量的较大值，独立按 HALF\_UP 四舍五入到整数分，每个正数计量项最低 1 分。任务总额为各计量项金额之和。

启用的 ASR、嵌套 FFmpeg 等能力可能增加计量项，各有计量单位、费率和最低数量。渲染分钟单价不包含所有能力费用。

### 操作与结算

浏览与预览

浏览示例和当前登录预览不创建渲染任务，不产生渲染费用。

生成

生成会创建渲染任务，成功结果被服务端采纳后按计量项结算。

批量生成

一批包含多条独立的渲染任务，每条任务按各自结果结算。建议先验证一条成片效果，再提交整批内容。

重新生成与不确定的提交

重新生成会创建新任务。提交结果不确定时人工重复提交可能创建另一条收费任务，请先查看任务列表。

下载已有产物

下载或重签已有产物不会再次结算渲染费用。此说明不承诺产物保留期限或清理后的恢复。

普通失败

普通失败终态和取消终态不收费。派发异常后的晚到成功结果见下方说明。

请求取消

取消是尽力而为，完成先被采纳仍会结算。发出取消请求不等于已进入取消终态。

晚到的成功结果

本地派发超时或派发失败后，晚到的成功结果仍可能被采纳并结算一次。

当前预览说明不构成匿名试用或免费生成额度承诺。以上说明依据仓库实现，未验证部署费率或真实账单。

<a id="architecture"></a>



## 系统架构

服务层统一处理 API Key、项目和版本解析、参数校验、租户配额与任务状态；运行时层根据项目类型执行实际渲染。

业务系统  
Agent / App

→

万象渲染 API  
鉴权 / 项目 / 任务

→

Runtime Adapter  
按项目类型路由

→

Render Workers  
并行执行

→

对象存储  
状态 / 视频

<a id="quickstart"></a>



## 快速开始

1.  1
    
    ### 创建项目与版本
    
    选择 hyperframes，并上传对应的构建产物。每次发布生成不可变的项目版本。
    
2.  2
    
    ### 创建 API Key
    
    API Key 只应保存在服务端环境变量或密钥管理服务中，不要暴露在浏览器代码里。
    
3.  3
    
    ### 保存幂等键并提交
    
    指定不可变项目版本、渲染入口和业务参数。创建前保存稳定的 Idempotency-Key；网络超时后用同一个 key 和请求体重试。
    
4.  4
    
    ### 查询并下载结果
    
    接口异步返回 renderTaskId。主渲染任务不提供 Webhook；使用 GET 或 CLI wait 查询终态，完成后再获取下载地址。
    

<a id="authentication"></a>



## 认证方式

本地交互使用设备授权；Agent、CI 和服务端集成使用账号级 API Key，无需登录或打开 MassRender 网页。API Key 继承账号所属租户和账号权限；模板创建、更新与发布仍需对应模板管理权限。

### CLI 登录

`Authorization: Bearer <token>`

适合开发者本机，massrender login 自动保存凭据。

### Agent / CI

`X-API-KEY: <key>`

推荐自动化使用，只保存在密钥管理服务或环境变量。

### Web 控制台

`同源 Session Cookie`

仅供浏览器控制台使用，不应复制到自动化脚本。

```
export MASSRENDER_API_URL=/api/v1
export MASSRENDER_API_KEY=***

npx @massrender/cli auth status --json
npx @massrender/cli whoami --json
npx @massrender/cli capabilities --json
```

<a id="api"></a>



## 公开 API

外部服务使用控制台生成的账号级 API Key，通过`X-API-KEY`请求头访问。任务归属于该账号所在租户，费用规则见[计费方式](<https://massrender.dev.framefuture.com/docs/#pricing>)。请勿在浏览器前端暴露密钥。

### POST/api/v1/render-tasks

```
export MASSRENDER_IDEMPOTENCY_KEY="your-business-operation-id"

curl -X POST /api/v1/render-tasks \
  -H "X-API-KEY: $MASSRENDER_API_KEY" \
  -H "Idempotency-Key: $MASSRENDER_IDEMPOTENCY_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "projectVersionId": "pv_01J...",
    "compositionId": "DataReport",
    "inputProps": { "headline": "2026 年度增长", "metricValue": 1280 }
  }'
```

### GET/api/v1/render-tasks/:renderTaskId

```
curl /api/v1/render-tasks/rt_01J... \
  -H "X-API-KEY: $MASSRENDER_API_KEY"

{
  "renderTaskId": "rt_01J...",
  "status": "rendering",
  "progress": { "percent": 72, "completedChunks": 13, "totalChunks": 18 },
  "output": null
                }
```

### SDK 创建并查询

```
import {FfServerClient} from '@massrender/ff-server-sdk';

const client = new FfServerClient({
  baseUrl: process.env.MASSRENDER_API_URL,
  apiKey: async () => process.env.MASSRENDER_API_KEY,
});
const idempotencyKey = 'your-business-operation-id';
const task = await client.createRenderTask({
  projectVersionId: 'pv_01J...',
  entryId: 'DataReport',
  inputProps: {headline: '2026 年度增长', metricValue: 1280},
}, {idempotencyKey});
const current = await client.getRenderTask(task.renderTaskId);
```

只有创建前保存的 `Idempotency-Key`能防止重试创建第二个任务。相同 key 必须配合同一个请求体；不同请求体复用时返回`409 IDEMPOTENCY_KEY_REUSED`。

网络超时、429 或可重试 5xx 使用指数退避，并复用原 key。renderTaskId 只用于查询与追踪；取消是尽力而为。

OPENAPI 3.1 · 57 ENDPOINTS

展开端点可查看认证、参数、请求字段、响应 Schema 与示例。

[下载 OpenAPI YAML](<https://massrender.dev.framefuture.com/openapi/render-public-v1.openapi.yaml>)

搜索 API 端点

Base URL: /api/v1

### RenderTasks

15

get`/render-tasks`游标分页查询渲染任务+post`/render-tasks`创建渲染任务+get`/render-tasks/stats`任务队列月度聚合指标+post`/render-tasks/batch`批量并行创建渲染任务+post`/render-tasks/batch/import`上传 Excel 与图片/视频素材并创建批量渲染+get`/render-tasks/batches`查询当前租户的批量渲染批次+get`/render-tasks/batches/{renderBatchId}`查询批次逐行状态+get`/render-tasks/batches/{renderBatchId}/items/{itemId}`查询单个批量渲染项详情+post`/render-tasks/batches/{renderBatchId}/items/{itemId}/retry`显式重试失败的批量渲染项+get`/render-tasks/{renderTaskId}`查询渲染任务+get`/render-tasks/{renderTaskId}/input`查询渲染任务原始输入快照（用于再次创建）+get`/render-tasks/{renderTaskId}/trace`查询渲染任务链路视图（Langfuse 风格 span 树）+post`/render-tasks/{renderTaskId}/cancel`请求取消渲染任务+get`/render-tasks/{renderTaskId}/download`刷新渲染产物下载链接（实时重签 OSS URL，返回 200 + JSON）+post`/render-tasks/upload-signature`获取 bundle 上传签名（CLI 直传 OSS 用）+

### FfmpegTasks

3

get`/ffmpeg-tasks`查询当前租户的 FFmpeg 任务+post`/ffmpeg-tasks`创建通用 FFmpeg 任务+get`/ffmpeg-tasks/{taskId}`查询 FFmpeg 任务状态+

### RenderTemplates

6

get`/render-templates`列出可渲染的模板目录+post`/render-templates`创建或更新当前租户的私有渲染模板+get`/render-templates/{templateId}`查询单个模板详情（匿名可读）+put`/render-templates/{templateId}`更新当前租户的私有模板配置+delete`/render-templates/{templateId}`删除当前租户的私有模板+post`/render-templates/{templateId}/publish`发布模板（draft → published）+

### RenderProjects

4

get`/render-projects`列出当前租户的项目+post`/render-projects`创建渲染项目（CTR-006 幂等：按 slug 找或创建）+get`/render-projects/{projectId}`按 ID 查询项目+get`/render-projects/by-slug/{slug}`按 slug 查项目（CTR-006 §4.2）+

### PreviewSessions

3

post`/preview-sessions`创建短期 HyperFrames 预览会话+put`/preview-sessions/{sessionId}`更新预览变量+delete`/preview-sessions/{sessionId}`销毁预览会话+

### Marketplace

3

get`/marketplace/templates`浏览已发布市场模板+get`/marketplace/templates/{slug}`按 slug 查询市场模板详情+get`/marketplace/templates/{templateId}/releases/{releaseId}`查询一个公开的不可变 Release+

### Auth

4

post`/auth/device`CLI 设备授权 — 请求 device code+get`/auth/device/status`CLI 轮询设备授权状态+post`/auth/device/confirm`用户在浏览器确认 CLI 授权+post`/auth/device/logout`CLI 登出（注销 session）+

### Account

1

get`/account`返回当前用户、租户与认证类型+

### Billing

4

get`/account/balance`查询预付费余额与累计渲染消费+get`/usage/summary`查询本月、上月和近 30 天用量汇总+get`/usage/daily`查询最多 90 天的逐日用量+get`/pricing`查询当前租户生效的渲染价格+

### Capabilities

1

get`/capabilities`发现服务端引擎、质量档位和自动化能力+

### Skills

6

get`/skills`获取可执行技能目录+get`/skill-workflows`列出技能工作流的最新不可变版本+post`/skill-workflows`创建技能工作流及其首个不可变版本+get`/skill-workflows/{workflowId}/versions/{version}`获取指定的不可变工作流版本+post`/skill-workflows/{workflowId}/versions`为技能工作流创建新的不可变版本+post`/skill-workflow-runs`在云端执行固定版本的技能工作流+

### TempAssets

7

get`/temp-assets`列出当前租户未过期临时素材 + 配额+post`/temp-assets`上传临时素材（RFC 0004）+post`/temp-assets/upload-token`获取临时素材直传 OSS 凭证（大文件直传）+get`/temp-assets/quota`租户临时素材配额快照+post`/temp-assets/{assetId}/complete`完成临时素材直传注册+get`/temp-assets/{assetId}`查询单素材元数据（租户隔离，跨租户 404）+delete`/temp-assets/{assetId}`删除素材并释放配额（租户隔离，跨租户 404）+

<a id="cli-quickstart"></a>



## CLI 快速开始

万象渲染 CLI 让你从终端管理模板、上传 bundle 和发起渲染，自动处理鉴权和轮询。

0\. 安装 CLI（首次使用）

推荐：直接用 npx，免安装免 PATH

```
npx @massrender/cli
```

或全局安装：`npm install -g @massrender/cli`，安装后即可使用 `massrender` 命令 （当前版本 v0.2.2，要求 Node.js ≥ 22）。

1\. 配置企业认证

```
export MASSRENDER_API_URL=/api/v1
export MASSRENDER_API_KEY=***
npx @massrender/cli auth status --json
```

2\. 确认不可变项目版本

```
npx @massrender/cli project get <id-or-slug> --json
```

3\. Agent 幂等创建并等待任务

```
export MASSRENDER_IDEMPOTENCY_KEY="your-business-operation-id"
npx @massrender/cli render create \
  --project-version pv_01J... \
  --composition DataReport \
  --idempotency-key "$MASSRENDER_IDEMPOTENCY_KEY" \
  --props '{"headline":"2026 年度增长","metricValue":1280}' --json

npx @massrender/cli render wait <renderTaskId> --output=jsonl
npx @massrender/cli render download <renderTaskId> --file result.mp4 --json
```

<a id="cli-reference"></a>



## CLI 命令参考

下列资源命令都支持`--output text|json|jsonl`和 `--json`。

### 身份与能力

`massrender auth status`

验证凭据，并返回认证来源和 API 地址

`massrender whoami`

返回当前用户、租户与认证类型

`massrender capabilities`

返回引擎、质量档位、功能和输出格式

### 模板与项目

`massrender template list`

列出当前凭据可用的模板

`massrender template get <id-or-key>`

按模板 ID 或 key 查询详情

`massrender template schema <id-or-key>`

输出 inputProps 的 JSON Schema

`massrender project list`

列出当前租户的渲染项目

`massrender project get <id-or-slug>`

查询项目、composition 和最新可用版本

`massrender project upload [dir]`

上传并验证项目，可选注册模板

### 渲染任务

`massrender render create`

创建任务后立即返回；Agent 重试时传入并复用 --idempotency-key

`massrender render list`

按状态、项目和时间范围分页查询

`massrender render get <id>`

获取完整任务快照

`massrender render wait <id>`

轮询至完成、失败、取消或超时

`massrender render download <id>`

刷新下载 URL，或保存到本地文件

`massrender render cancel <id>`

请求取消任务（尽力而为，不保证一定停下）

`massrender render run`

创建并等待完成的一体化交互命令

### 金额与用量

`massrender billing balance`

查询预付费余额与累计渲染消费

`massrender billing usage`

查询月度汇总；--daily 查询最多 90 天逐日明细

`massrender billing pricing`

查询当前质量档位和每分钟价格

```
# 余额、价格与最多 90 天逐日用量
massrender billing balance --json
massrender billing pricing --json
massrender billing usage --daily --from 2026-07-01 --to 2026-07-30 --json

# 筛选任务；from/to 必须同时提供且范围不超过一个月
massrender render list --status completed --limit 50 --json
massrender render list --cursor <nextCursor> --json

# 未提供幂等键时，每次创建都会新建任务；结果不确定时复用原 key
massrender render create --project-version pv_01J... --composition DataReport   --idempotency-key "$MASSRENDER_IDEMPOTENCY_KEY" --json
```

<a id="machine-output"></a>



## 机器输出与错误处理

JSON 模式固定返回成功或失败信封。Agent 应先检查进程退出码，再读取`ok`和 `error.retryable`，不要解析人类文本。

### 成功

```
{
  "ok": true,
  "data": { "renderTaskId": "rt_01J...", "status": "queued" },
  "meta": { "requestId": "...", "timestamp": "..." }
}
```

### 失败

```
{
  "ok": false,
  "error": {
    "code": "RATE_LIMITED",
    "message": "请求过于频繁",
    "retryable": true
  },
  "meta": { "requestId": "...", "timestamp": "..." }
}
```

| 退出码 | 含义 | 建议 |
| --- | --- | --- |
| 0 | 命令成功 | 继续后续步骤 |
| 1 | CLI 本地错误 | 检查参数、文件和本地环境 |
| 2 | API 拒绝且不可重试 | 修正参数、状态或权限 |
| 3 | 未认证或无权限 | 更新 API Key / Token |
| 4 | 可重试错误或等待超时 | 指数退避后重试 |
| 5 | 渲染失败或取消 | 读取任务 error 后决定是否新建任务 |

<a id="lifecycle"></a>



## 任务生命周期

accepted→queued→rendering→combining→completed

任务失败时返回 `failed` 和结构化错误信息。客户端应使用指数退避轮询。renderTaskId 只用于查询与追踪，创建重试必须复用请求前保存的`Idempotency-Key`。

<a id="hyperframes-variables-troubleshooting"></a>



## 模板参数不生效排查（HyperFrames）

编写 HyperFrames 模板 `.html` 时，如果模板里的 JS 读参数用错了 `window` 属性名， 会导致「预览里改参数生效、走正式渲染任务出来的视频没生效」的分裂表现。这一节说明成因和唯一需要的一行代码修复。

**TL;DR**：模板脚本里读变量必须写成三段兜底：  
`window.__hyperframes?.getVariables?.() || window.__hfVariables || window.__HV_VARS__ || {}`

### 症状：怎么判断踩到了这个坑

-   在 studio 预览 / 本地 preview 里改参数是**生效**的；
-   但走正式 `/render-tasks` 出来的视频里，**文本参数（title / subtitle / 文案 等）没变**，还是默认值；
-   有些**颜色参数（accent、bg 等）却生效了**——因为它们同时通过 CSS `var(--xxx)` 走了另一条通道；
-   后端 API 请求体里 `inputProps` 的值是对的（浏览器网络面板里能看到改后的值）。

### 原因：预览和正式渲染注入的名字不一样

`@hyperframes/producer` 在正式渲染时，会**同时**做两件事把 `inputProps` 注入到页面：

| 通道 | 面向谁 | 注入形式 |
| --- | --- | --- |
| ① 编译期 | CSS `var(--xxx)` | `<style data-hf-composition-variables>:root { --accent: <值>; ... }</style>` |
| ② 运行时 | JS 代码 | `window.__hfVariables = {...}`（通过 `evaluateOnNewDocument`） |

而 studio / 本地预览 / ff-server 预览接口为了兼容历史模板，另外挂了两个别名。四个环境注入的 `window` 属性对照如下：

| 环境 | `__hyperframes` | `__hfVariables` | `__HV_VARS__` |
| --- | --- | --- | --- |
| HyperFramesStory 本地预览 | ✓ | ✗ | ✓ |
| MassRender studio 预览 | ✓ | ✗ | ✓ |
| ff-server 预览接口 | ✗ | ✓ | ✓ |
| 正式渲染（producer） | ✗ | ✓ | ✗ |

如果模板脚本里只读 `window.__HV_VARS__`（很多老 demo 就是这样写的），**正式渲染时 variables 就是空 {}**，所有 JS 里读的字段就都回退到默认值。 颜色能生效纯属侥幸——它同时借道通道 ① 的 CSS 自定义属性被注入了一遍。

### 解决方案：一行改动，三段兜底

❌ 错误写法（会踩坑）

```
// 只读一个别名，正式渲染下拿不到值
const variables = window.__HV_VARS__ || {};

// 更糟：不做保护，__hyperframes 不存在时会 TypeError
const variables = window.__hyperframes.getVariables();
```

✅ 正确写法（推荐所有模板都用这一段）

```
// 变量注入通道优先级：
//   1. window.__hyperframes.getVariables()  —— @hyperframes/producer runtime 官方 API
//                                              （sub-composition 作用域 / 未来 runtime 版本）
//   2. window.__hfVariables                —— 当前生产渲染管线 (evaluateOnNewDocument) 注入的名字
//   3. window.__HV_VARS__                  —— HyperFramesStory 预览 shim / MassRender 预览注入的名字
const variables =
  window.__hyperframes?.getVariables?.() ||
  window.__hfVariables ||
  window.__HV_VARS__ ||
  {};

// 后面照常用 variables.title / variables.subtitle / variables.accent ...
```

### 完整最小示例

```
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta data-composition-id="my-card" data-width="640" data-height="360">
  <style>
    body { margin: 0; background: #07111f; color: #fff; font-family: system-ui, sans-serif; }
    #stage { width: 640px; height: 360px; display: grid; place-content: center; text-align: center; }
    #badge { color: var(--accent); font-weight: 700; letter-spacing: .2em; }
    h1 { color: var(--accent); margin: 0; font-size: 48px; }
    p { color: #bfd7ea; }
  </style>
</head>
<body>
  <main id="stage"
        data-composition-id="my-card"
        data-duration="3"
        data-composition-variables='[
          {"id":"title","type":"string","label":"标题","default":"Hello"},
          {"id":"subtitle","type":"string","label":"副标题","default":"World"},
          {"id":"accent","type":"color","label":"强调色","default":"#38bdf8"}
        ]'>
    <div>
      <div id="badge">BRAND</div>
      <h1 id="title">Hello</h1>
      <p id="subtitle">World</p>
    </div>
  </main>

  <script>
    // ✅ 三段兜底：预览、正式渲染、未来 runtime 都能拿到值
    const variables =
      window.__hyperframes?.getVariables?.() ||
      window.__hfVariables ||
      window.__HV_VARS__ ||
      {};

    // CSS 变量：producer 在 <head> 里已经注入 :root { --accent: <值> }，
    // 这一行是给预览环境或旧运行时的兜底，保持写法一致。
    document.documentElement.style.setProperty('--accent', variables.accent || '#38bdf8');
    document.getElementById('title').textContent = variables.title || 'Hello';
    document.getElementById('subtitle').textContent = variables.subtitle || 'World';
  </script>
</body>
</html>
```

### 发布前自检清单

-   `<script>` 里读变量那一行，是否用了推荐的**三段兜底**？
-   除了 CSS `var(--xxx)`，**所有 JS 读的字段**都通过 `variables.<id>` 取值，且给了 `|| '默认值'` 兜底？
-   至少跑过**一次正式 render**（不是预览），确认 title / subtitle / 数组 等纯 JS 驱动的字段确实生效？

只在预览里跑不能证明模板参数在生产是好的——预览和生产的注入名字不一样。

<a id="ffmpeg-overview"></a>



## 通用 FFmpeg 执行器

除了模板渲染，万象渲染还提供通用的 FFmpeg 执行能力：你只传「外部 URL 输入」+ 「命令数组」+「输出文件名」，服务端把输入取到受控存储后在云函数上执行 ffmpeg。 适用于转码、加水印、截图、媒体信息查询等任意 ffmpeg 任务，无需预先制作模板。

### 安全模型

-   • ffmpeg 进程永不直连网络，输入由服务端 fetch 到受控存储
-   • 输入 URL 必须为公网 http(s)；私网和元数据地址会被拒绝
-   • 命令参数经从严白名单校验（option/filter/值域默认拒绝）
-   • `-i` 只能引用已声明的输入文件名

### 异步与会员体系

-   • 创建返回 202 + taskId，执行在云函数上异步进行
-   • 用 GET 轮询拿终态；`callbackUrl` 回调不保证送达，不应作为唯一判定来源
-   • 不依赖会员订阅，不因套餐过期或调用次数上限拦截
-   • 渲染任务的结算规则见[计费方式](<https://massrender.dev.framefuture.com/docs/#pricing>)

<a id="cli-ffmpeg"></a>



## FFmpeg 命令

FFmpeg 子命令在 `massrender ffmpeg` 命名空间下， 与渲染命令同样支持 `--json` 机器输出。

### FFmpeg 任务

`massrender ffmpeg create`

创建通用 FFmpeg 任务（异步提交后立即返回 taskId）

`massrender ffmpeg get <taskId>`

查询任务状态、产物下载 URL 或 ffprobe 结果

`massrender ffmpeg wait <taskId>`

轮询至完成或失败（--interval / --timeout 控制节奏）

### ffmpeg create 参数

| 参数 | 取值 | 说明 |
| --- | --- | --- |
| `--mode` | ffmpeg \| ffprobe | 执行模式；ffmpeg=转码/处理，ffprobe=媒体信息查询。默认 ffmpeg。 |
| `--profile` | standard \| highmem \| gpu | 规格档位。目前只开放 standard（2 vCPU / 3GB / 600 秒），highmem 与 gpu 尚未开通，传这两个值会被拒绝。 |
| `--input` | "name=url" | 输入文件声明，可重复；URL 必须为 http(s)。如 --input "main.mp4=https://cdn/a.mp4"。 |
| `--args` | shell 字符串 | ffmpeg/ffprobe 参数（支持引号）；-i 只能引用 --input 声明的文件名。 |
| `--output-file` | 文件名 | 输出文件名（mode=ffmpeg 必填，且 --args 最后一个参数必须指向它）。 |
| `--callback-url` | URL | 可选；任务进入终态时 POST 到该 URL 通知。 |

```
# 转码：1080p → 720p h264
massrender ffmpeg create \
  --input "main.mp4=https://cdn.example.com/input.mp4" \
  --args "-i main.mp4 -vf scale=-2:720 -c:a aac out.mp4" \
  --output-file out.mp4

# 多输入加水印（--args 支持引号）
massrender ffmpeg create \
  --input "main.mp4=https://cdn.example.com/input.mp4" \
  --input "logo.png=https://cdn.example.com/logo.png" \
  --args "-i main.mp4 -i logo.png -filter_complex [0:v][1:v]overlay=W-w-10:10 -c:a copy out.mp4" \
  --output-file out.mp4

# ffprobe 查询媒体信息（无需 --output-file）
massrender ffmpeg create --mode ffprobe \
  --input "main.mp4=https://cdn.example.com/input.mp4" \
  --args "-v error -print_format json -show_format -show_streams -i main.mp4"

# 轮询至终态并以 JSON 输出
massrender ffmpeg wait <ffmpeg-id> --json
```

<a id="api-ffmpeg"></a>



## FFmpeg RESTful API

外部服务通过 `X-API-KEY`或 Bearer Token 访问，认证方式与渲染任务一致。成功创建返回 202，任务异步执行； 用 GET 轮询状态。`callbackUrl` 回调不重试、不保证送达， 客户端应以 GET 轮询结果为准，不要只依赖回调。

### POST/api/v1/ffmpeg-tasks

```
# ffmpeg 模式：转码
curl -X POST /api/v1/ffmpeg-tasks \
  -H "X-API-KEY: $MASSRENDER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {"main.mp4": "https://cdn.example.com/input.mp4"},
    "commands": [["-i", "main.mp4", "-c:v", "libx264", "-pix_fmt", "yuv420p", "out.mp4"]],
    "output": {"fileName": "out.mp4"},
    "mode": "ffmpeg",
    "profile": "standard"
  }'

# → 202 Accepted
{"taskId": "ffmpeg-3f0e6a1f-...","status": "queued", "error": null}
```

```
# ffprobe 模式：媒体信息查询（无 output 字段）
curl -X POST /api/v1/ffmpeg-tasks \
  -H "X-API-KEY: $MASSRENDER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {"main.mp4": "https://cdn.example.com/input.mp4"},
    "commands": [["-v","error","-print_format","json","-show_format","-show_streams","-i","main.mp4"]],
    "mode": "ffprobe",
    "profile": "standard"
  }'
```

### GET/api/v1/ffmpeg-tasks/:taskId

```
curl /api/v1/ffmpeg-tasks/ffmpeg-3f0e6a1f-... \
  -H "X-API-KEY: $MASSRENDER_API_KEY"

{
  "taskId": "ffmpeg-3f0e6a1f-...",
  "status": "completed",
  "finalHttpUrl": "https://signed.example.com/.../out.mp4",
  "output": {
    "sizeInBytes": 60098, "width": 1280, "height": 720,
    "codec": "h264", "durationSeconds": 3.0
  },
  "probeResult": null,
  "error": null, "errorCode": null
}
```

### 错误码

| HTTP | code | 含义 |
| --- | --- | --- |
| 400 | `FFMPEG_INPUT_URL_FORBIDDEN` | 输入 URL 协议非 http(s)，或指向私网/元数据/localhost 地址 |
| 400 | `FFMPEG_COMMAND_URL_FORBIDDEN` | commands 里嵌入了网络 URL/协议（-i 只能引用已声明的输入文件名） |
| 400 | `FFMPEG_VALIDATION_ERROR` | 请求体或命令校验失败（option/filter 白名单、值域等） |
| 404 | `FFMPEG_TASK_NOT_FOUND` | 任务不存在，或归属校验不通过（任务归属另一租户） |
| 503 | `RENDER_SERVICE_UNAVAILABLE` | 渲染服务暂时不可用，可重试 |

任务进入 `failed` 终态时，`errorCode`字段携带任务级原因（`FFMPEG_TIMEOUT`、`FFMPEG_INPUT_FETCH_FAILED`、`FFMPEG_EXEC_FAILED` 等）。 下方结构化参考由 OpenAPI 规范自动生成。

<a id="temp-assets-overview"></a>



## 临时素材（素材库）

除了「外部 URL」输入，万象渲染还提供**临时素材**能力： 客户先把生产素材（视频、图片等）上传，服务端返回一个**内网`oss://`链接**。该链接只能回传给 ffmpeg 任务的 `inputs` 或渲染任务的`inputProps` 媒体变量作为消费凭证， 不能当作 HTTP URL 在浏览器直接打开。

### 生命周期与配额

-   • 素材存活默认 24h（TTL），过期后自动清理，不计入配额
-   • 配额按租户计，默认 10G；上传超过配额返回 409
-   • 单文件默认上限 2G，超过返回 413
-   • 删除素材立即释放配额

### 安全模型

-   • 素材按租户隔离，跨租户读取或删除一律返回 404
-   • 文件名经服务端 sanitize：路径分隔符、控制字符、保留控制名会被拒绝
-   • `oss://` 链接为内网消费凭证，bucket 私有，浏览器不可访问
-   • 上传并发按租户限流，防止单租户占满 worker

<a id="temp-assets-api"></a>



## 素材 RESTful API

通过 `X-API-KEY` 或 Bearer Token 访问， 认证方式与渲染任务一致。租户由登录态自动注入，客户端无需也无法指定租户。

### POST/api/v1/temp-assets

```
# 上传原始字节（raw body，不要 JSON 包装；文件名建议 percent-encode）
curl -X POST /api/v1/temp-assets \
  -H "X-API-KEY: $MASSRENDER_API_KEY" \
  -H "X-File-Name: hero.mp4" \
  -H "Content-Type: video/mp4" \
  --data-binary @hero.mp4

# → 201 Created
{
  "assetId": "ta_0123456789abcdef0123456789abcdef",
  "fileName": "hero.mp4",
  "sizeBytes": 1048576,
  "contentType": "video/mp4",
  "sha256": "a".repeat(64),
  "url": "oss://framefuture-video/remotion-fc-renders/temp-assets/tenant-xxx/ta_0123.../hero.mp4",
  "expiresAt": "2026-08-07T08:00:00.000Z",
  "quota": {"usedBytes": 1048576, "quotaBytes": 10737418240, "remainingBytes": 10736369664, "assetCount": 1}
}
```

### GET/api/v1/temp-assets · /api/v1/temp-assets/quota

```
# 列出未过期素材 + 配额
curl /api/v1/temp-assets -H "X-API-KEY: $MASSRENDER_API_KEY"

# 只取配额快照
curl /api/v1/temp-assets/quota -H "X-API-KEY: $MASSRENDER_API_KEY"
```

### GET/DELETE/api/v1/temp-assets/:assetId

```
# 单素材元数据
curl /api/v1/temp-assets/ta_0123456789abcdef0123456789abcdef -H "X-API-KEY: $MASSRENDER_API_KEY"

# 删除素材并释放配额
curl -X DELETE /api/v1/temp-assets/ta_0123456789abcdef0123456789abcdef \
  -H "X-API-KEY: $MASSRENDER_API_KEY"

# → 200 {"deleted": true, "tenantRef": "tenant-xxx", "quota": {...}}
```

### 消费方式

上传返回的 `oss://` 链接可回传给：

```
# FFmpeg 任务：把素材作为输入（inputs 值直接用 oss:// 链接）
curl -X POST /api/v1/ffmpeg-tasks \
  -H "X-API-KEY: $MASSRENDER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {"main.mp4": "oss://framefuture-video/remotion-fc-renders/temp-assets/tenant-xxx/ta_0123.../hero.mp4"},
    "commands": [["-i", "main.mp4", "-c:v", "libx264", "-pix_fmt", "yuv420p", "out.mp4"]],
    "output": {"fileName": "out.mp4"},
    "mode": "ffmpeg", "profile": "standard"
  }'
```

### 错误码

| HTTP | code | 含义 |
| --- | --- | --- |
| 400 | `VALIDATION_ERROR` | 缺/非法租户头、非法文件名、空 body |
| 409 | `TEMP_ASSET_QUOTA_EXCEEDED` | 租户配额超限（默认 10G） |
| 413 | `TEMP_ASSET_FILE_TOO_LARGE` | 单文件超过上限（默认 2G） |
| 404 | `TEMP_ASSET_NOT_FOUND` | 素材不存在，或不属于当前租户 |
| 429 | `TEMP_ASSET_UPLOAD_BUSY` | 租户并发上传超过上限，稍后重试 |
| 502 | `TEMP_ASSET_UPSTREAM_ERROR` | ff-server 无法到达渲染服务（网络层失败），可重试 |
| 503 | `RENDER_SERVICE_UNAVAILABLE` | 渲染服务暂时不可用，可重试 |

下方结构化参考由 OpenAPI 规范自动生成。

<a id="prepare-overview"></a>



## prepare 阶段

很多视频在正式渲染前需要先做一步准备：抽音轨、做语音识别、按文稿打轴、算出字幕分页。 万象渲染把这步交给你自己的代码——项目里声明一个 `prepare` 入口， 平台在渲染前执行它，把它返回的 `props` 作为这次渲染的`inputProps`。平台在这个过程中提供 ffmpeg、 ASR、存储和受限 HTTP 四类调用，怎么组合、分页规则是什么，都由你的代码决定。

### 任务状态

-   • 提交后平台先跑 prepare，这段时间任务对外是 `queued`，没有分片进度
-   • prepare 跑完才进入渲染，之后的状态和进度与不含 prepare 的任务一致
-   • prepare 期间不占用渲染并发，只占队列位置
-   • 终态时 `usage.prepare` 给出这次 prepare 的耗时、ffmpeg/ASR 调用次数、是否命中缓存和 props 体积
-   • 不含 prepare 的项目行为不变

### 运行约束

-   • 入口是随制品发布的 ESM 文件，不超过 2 MiB；制品里没有 node\_modules，依赖要自己打包进文件
-   • 单次预算 900 秒；超时或任务取消时 `ctx.signal` 中止，进行中的调用一并停止
-   • 平台凭证不会写进你的进程环境，能力调用由平台代为执行；但这层隔离挡不住恶意代码，不要执行来源不可信的 prepare 代码
-   • prepare 按租户开通，未开通时提交直接返回 403 `PREPARE_NOT_ENABLED`

声明方式随项目类型不同：Remotion 项目写在 `package.json` 的`massrender.prepare` 里；HyperFrames 项目写在项目清单的`entries[].prepare` 里。

```
// package.json（Remotion）
{
  "massrender": {
    "prepare": "prepare/main.mjs",
    "allowedHosts": ["api.example.com"]
  }
}

// prepare/main.mjs —— 最小骨架
export default async (ctx) => {
  const {video, script, language} = ctx.input;

  // ① 抽音轨
  const audio = await ctx.ffmpeg.run({
    inputs: {src: video.url},
    commands: [['-i', 'src', '-vn', '-c:a', 'aac', '-ar', '16000', '-ac', '1', 'narration.m4a']],
    output: {fileName: 'narration.m4a'},
  });

  // ② 有稿子打轴，没稿子纯识别
  const asr = script
    ? await ctx.asr.align({audio: audio.output.url, text: script, language})
    : await ctx.asr.transcribe({audio: audio.output.url, language});

  // ③ 返回的 props 直接成为渲染 inputProps
  return {
    props: {
      video,
      voiceover: audio.output,
      pages: [{
        text: asr.utterances.map((u) => u.text).join(''),
        start: 0,
        end: asr.audioSeconds ?? 0,
      }],
    },
    usage: {audioSeconds: asr.audioSeconds},
  };
};
```

<a id="prepare-capabilities"></a>



## 能力清单

四类调用的凭据都在平台侧，你的代码只拿到调用入口。每次调用都计入`usage`，费用以平台侧计数为准。

| 能力 | 作用 | 要点 |
| --- | --- | --- |
| `ctx.input` | 本次请求的 inputProps | 另有 `ctx.entryId` / `ctx.renderId` / `ctx.tenantRef` |
| `ctx.ffmpeg.run`<br>`ctx.ffmpeg.probe` | 执行 ffmpeg 命令 / 只取媒体信息 | 输入为逻辑名 → URL，参数走服务端白名单；`probe` 不产出 URL |
| `ctx.asr.align`<br>`ctx.asr.transcribe` | 按文稿对齐 / 纯识别，返回词级时间戳 | 需要提供方可访问的**公网音频**地址，不建议直接传视频地址 |
| `ctx.storage.putJson`<br>`ctx.storage.getJson` | 按租户隔离的 JSON 键值存储，用来跨次运行保留昂贵中间结果（打轴、转写等） | 仅 JSON、单对象 ≤ 8 MiB、键为相对路径；只能读写本租户的数据，没有列举/删除接口，也不会自动过期——同一 key 重复写即覆盖 |
| `ctx.http.fetch` | GET 外部接口 | 域名必须在声明里白名单化，未声明则完全禁用 |
| `ctx.log`<br>`ctx.signal` | 写日志 / 感知取消与超时 | 长任务应监听 `signal` 提前收尾，避免被强制终止 |

**关于 ctx.storage：**它是给**你自己的代码**用的缓存， 不是素材库（[临时素材](<https://massrender.dev.framefuture.com/docs/#temp-assets-overview>)）。存的是 JSON 而不是文件： 写对象用 `putJson(key, value)`，读回`getJson(key)` 得原值、没有则`null`。数据按租户隔离，其他租户读不到；单次运行最多 4 个并发调用排队，超出即等待，等待可被`ctx.signal` 中止。视频、音频这类大文件请走 ffmpeg 输出或素材库，storage 不支持。

**关于输出地址：**ffmpeg 产出的 `output.url`形态由引擎决定——Remotion 为有效期 7 天的预签名 HTTPS，HyperFrames 为默认 24 小时有效的租户临时素材`oss://`。写进 props 的应当是`url` 而不是`objectKey`，渲染阶段才能直接消费。

<a id="prepare-return"></a>



## 返回值与缓存

```
return {
  props,                               // 必填：这次渲染的 inputProps
  cacheable: false,                    // 可选：是否允许平台缓存本次结果
  usage: {audioSeconds: 42.5},         // 可选：仅为提示，计费以平台计数为准
};
```

-   • **props 必须满足 entry 的 inputSchema。**该 schema 由项目的默认参数反推，且不允许额外字段。prepare 多返回一个 key 就会判为`PREPARE_OUTPUT_INVALID`，所以默认参数要覆盖 prepare 会返回的全部顶层字段（例如字幕组件返回 `voiceover`，默认参数里就要有这个 key）。
-   • **默认不缓存。**设 `cacheable: true` 才按「制品 + prepare 路径 + entry + 输入」缓存 30 天； 但产出过 `output.url` 的那次运行永不缓存（URL 有效期远短于缓存）。 要复用昂贵计算，用 `ctx.storage`。
-   • ASR 结果平台另有缓存（默认 30 天）。缓存键是音频内容的 SHA-256，加上操作、语言和参考文本， 不含音频地址。每次用`ctx.ffmpeg.run` 重新抽音轨也会命中， 抽取参数（编码、码率、采样率）保持一致即可。命中时不再向识别服务提交，用量记在`usage.asrCachedCalls` /`usage.asrCachedAudioSeconds`， 不计入 `usage.audioSeconds`。结算规则见[计费方式](<https://massrender.dev.framefuture.com/docs/#pricing>)。
-   • props 超过 1 MiB 时平台会把它存到对象存储，任务详情里只保留引用。

<a id="prepare-troubleshooting"></a>



## 错误码与排查

prepare 阶段的失败会让任务以 `failed` 结束，回调`render.failed` 的`error.stage` 为`prepare`，`error.code` 是下表之一。查询任务时读`error.code` 判断原因。

| 错误码 | 含义 | 处理 |
| --- | --- | --- |
| `PREPARE_NOT_ENABLED` | 租户未开通 prepare，提交即被拒绝 | 联系平台开通；或提交一个未声明 prepare 的项目版本（平台不会跳过 prepare 继续渲染） |
| `PREPARE_INPUT_INVALID` | 传给平台的参数不合法：ffmpeg 的输入名/地址/输出名、ASR 缺音频或文稿、storage 的键，或 http.fetch 的请求本身 | 对照「能力清单」里对应那一行的要求逐项检查。域名不在白名单报的是 `MEDIA_UNREACHABLE`，不是这个码 |
| `PREPARE_ENTRY_NOT_FOUND` | 声明了 prepare，但制品里没有这个文件 | 确认构建把入口打进了发布产物 |
| `PREPARE_CODE_FAILED` | 代码抛错或没有返回结果 | 看任务日志里 `ctx.log` 的输出和错误尾部 |
| `PREPARE_OUTPUT_INVALID` | props 不满足 entry 的 inputSchema | 补齐默认参数里的字段，去掉 schema 之外的多余 key |
| `PREPARE_LIMIT_EXCEEDED` | 超出内存、体积或并发类上限，不可重试 | 减少一次性载入的数据量，分次写入 |
| `PREPARE_TIMEOUT` | 900 秒预算耗尽，或任务被取消 | 减少 ffmpeg/ASR 调用次数；ASR 结果会缓存，重跑通常更快 |
| `PREPARE_SANDBOX_UNAVAILABLE` | 执行环境异常，非你的代码问题 | 可重试；持续出现请联系平台 |
| `FFMPEG_TASK_FAILED` | ffmpeg 执行失败（含输入地址返回 4xx） | 确认输入地址可被服务端访问、命令参数在白名单内 |
| `MEDIA_UNREACHABLE` | 输入不可达，或域名不在白名单 | 改用公网可达地址；把域名加进 `allowedHosts` |
| `ASR_PROVIDER_FAILED` | 语音识别上游失败 | 可重试；持续失败请联系平台 |

一个容易误判的场景：用命令行工具生成预签名地址做调试，如果工具把额外的计时行混进了输出，或把路径里的`/` 编码成`%2F`，对象存储会返回 403`SignatureDoesNotMatch`，但在任务里看到的却是`FFMPEG_TASK_FAILED: input URL returned HTTP 403`。 判断方法：同一串地址用 curl 能取到、换另一个 HTTP 客户端却 403，问题在地址本身，不在权限。

<a id="remotion-fc"></a>



## FC 实现

使用阿里云函数计算 custom-container 运行时。编排器读取 composition metadata，并根据帧数动态拆分 chunk；多个 Worker 分片渲染，Combiner 使用 FFmpeg 合并最终 MP4。

### 无状态执行

bundle、job.json、chunk 和最终视频都保存在 OSS，函数实例可以弹性创建和回收。

### 动态并发

并发来自多个 FC Worker invocation；单个 Worker 内部保持顺序渲染，减少资源竞争。

### 浏览器复用

温实例复用 Chromium 进程，只为每次渲染创建页面，降低重复启动浏览器的固定开销。

### 可重入分片

稳定对象键和完成状态检查支持分片重试，Combiner 会根据 OSS 对象校正部分状态。

<a id="self-hosted"></a>



## 企业级 FC 自部署

对于要求数据不离开企业云账号、需要连接内网素材或希望独立管理资源成本的客户，万象渲染 可以协助将 Remotion FC 渲染链路部署到客户自己的阿里云环境。

企业业务系统

→

企业 API 网关

→

FC Orchestrator

→

FC Workers × N

→

企业 OSS

### 部署范围

FC custom-container、ACR 镜像、OSS 路径、VPC 网络、API 接入、日志与基础监控。

### 交付服务

环境评估、容量规划、部署验证、使用培训、版本升级和约定周期的技术支持。

价格：商务报价

通常由一次性实施费用与年度支持服务组成，阿里云资源费由企业自行承担。

[咨询自部署](<mailto:enterprise@massrender.com?subject=%E4%B8%87%E8%B1%A1%E6%B8%B2%E6%9F%93%20%E4%BC%81%E4%B8%9A%E8%87%AA%E9%83%A8%E7%BD%B2%E5%92%A8%E8%AF%A2>)

<a id="production"></a>



## 生产接入建议

-   业务后端负责保存 API Key，前端不直接调用渲染接口。
-   为每个项目使用不可变版本，发布新版本时保留回滚能力。
-   对提交接口设置租户配额、并发限制和输入参数校验。
-   创建请求前保存稳定的 Idempotency-Key；结果不确定时复用同一个 key 和请求体。
-   长耗时任务使用 GET 或 CLI wait 查询异步状态，不要保持同步 HTTP 连接等待视频完成。

### 准备接入你的第一个项目？

联系我们评估项目类型、运行依赖、并发目标和结果交付方式。

## 完整 OpenAPI 合约

````yaml
openapi: 3.1.0
info:
  title: MassRender Public Render API
  version: 1.0.0-draft
  description: |
    Web 与 CLI 调用 ff-server 的公开渲染任务契约。
    浏览器使用同源 Session Cookie，CLI 使用 Bearer Token，外部 REST API 使用 X-API-KEY。
jsonSchemaDialect: https://json-schema.org/draft/2020-12/schema
servers:
  - url: /api/v1
    description: Same-origin ff-server API
tags:
  - name: RenderTasks
  - name: FfmpegTasks
  - name: RenderTemplates
  - name: RenderProjects
  - name: PreviewSessions
  - name: Marketplace
  - name: Auth
  - name: Account
  - name: Billing
  - name: Capabilities
  - name: Skills
paths:
  /auth/device:
    post:
      tags: [Auth]
      operationId: requestDeviceCode
      summary: CLI 设备授权 — 请求 device code
      security: []
      responses:
        '200':
          description: device code + verification URL
          content:
            application/json:
              schema:
                type: object
                required: [device_code, user_code, verification_url, expires_in]
                properties:
                  device_code: {type: string}
                  user_code: {type: string}
                  verification_url: {type: string, format: uri}
                  expires_in: {type: integer}
                  interval: {type: integer}
  /auth/device/status:
    get:
      tags: [Auth]
      operationId: getDeviceStatus
      summary: CLI 轮询设备授权状态
      security: []
      parameters:
        - name: deviceCode
          in: query
          required: true
          schema: {type: string}
      responses:
        '200':
          description: pending / approved (含 token) / expired
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: {type: string, enum: [pending, approved, expired]}
                  token: {type: string}
                  tenantId: {type: integer}
                  expiresAt: {type: integer, description: '过期毫秒时间戳'}
  /auth/device/confirm:
    post:
      tags: [Auth]
      operationId: confirmDevice
      summary: 用户在浏览器确认 CLI 授权
      security:
        - sessionCookie: []
      parameters:
        - name: userCode
          in: query
          required: true
          schema: {type: string}
          description: Web 确认页展示的 user_code（公开短码，非 device_code）
      responses:
        '200':
          description: 已确认
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {description: user_code 不存在或已过期}
  /auth/device/logout:
    post:
      tags: [Auth]
      operationId: deviceLogout
      summary: CLI 登出（注销 session）
      security:
        - bearerToken: []
      responses:
        '200':
          description: 已注销
  /account:
    get:
      tags: [Account]
      operationId: getAccount
      summary: 返回当前用户、租户与认证类型
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 当前身份
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [userId, tenantId, authType]
                properties:
                  userId: {type: string}
                  tenantId: {type: string}
                  username: {type: string}
                  nickname: {type: string}
                  email: {type: string}
                  authType: {type: string, enum: [session, bearer, apiKey]}
        '401': {$ref: '#/components/responses/Unauthorized'}
  /account/balance:
    get:
      tags: [Billing]
      operationId: getAccountBalance
      summary: 查询预付费余额与累计渲染消费
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 金额单位为分，使用字符串避免精度损失
          content:
            application/json:
              schema:
                type: object
                required: [currency, balanceFen, renderConsumedFen]
                properties:
                  currency: {type: string, const: CNY}
                  balanceFen: {type: string, pattern: '^\d+$'}
                  renderConsumedFen: {type: string, pattern: '^\d+$'}
  /usage/summary:
    get:
      tags: [Billing]
      operationId: getUsageSummary
      summary: 查询本月、上月和近 30 天用量汇总
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 用量汇总
          content:
            application/json:
              schema: {$ref: '#/components/schemas/UsageSummary'}
  /usage/daily:
    get:
      tags: [Billing]
      operationId: getDailyUsage
      summary: 查询最多 90 天的逐日用量
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - {name: startDate, in: query, schema: {type: string, format: date}}
        - {name: endDate, in: query, schema: {type: string, format: date}}
        - {name: status, in: query, schema: {type: string}}
      responses:
        '200':
          description: 逐日用量
          content:
            application/json:
              schema: {$ref: '#/components/schemas/DailyUsage'}
  /pricing:
    get:
      tags: [Billing]
      operationId: getPricing
      summary: 查询当前租户生效的渲染价格
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 生效价格
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Pricing'}
  /capabilities:
    get:
      tags: [Capabilities]
      operationId: getCapabilities
      summary: 发现服务端引擎、质量档位和自动化能力
      security: []
      responses:
        '200':
          description: 能力描述
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true
  /skills:
    get:
      tags: [Skills]
      operationId: getSkills
      summary: 获取可执行技能目录
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 当前租户可发现的技能定义
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SkillCatalog'}
        '401': {$ref: '#/components/responses/Unauthorized'}
  /skill-workflows:
    get:
      tags: [Skills]
      operationId: listSkillWorkflows
      summary: 列出技能工作流的最新不可变版本
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 技能工作流列表
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SkillWorkflowList'}
        '401': {$ref: '#/components/responses/Unauthorized'}
    post:
      tags: [Skills]
      operationId: createSkillWorkflow
      summary: 创建技能工作流及其首个不可变版本
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CreateSkillWorkflowRequest'}
      responses:
        '201':
          description: 已创建首个不可变工作流版本
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SkillWorkflowVersion'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
  /skill-workflows/{workflowId}/versions/{version}:
    get:
      tags: [Skills]
      operationId: getSkillWorkflowVersion
      summary: 获取指定的不可变工作流版本
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: workflowId
          in: path
          required: true
          schema: {$ref: '#/components/schemas/SkillWorkflowId'}
        - name: version
          in: path
          required: true
          schema: {$ref: '#/components/schemas/SkillWorkflowVersionNumber'}
      responses:
        '200':
          description: 不可变工作流版本
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SkillWorkflowVersion'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
  /skill-workflows/{workflowId}/versions:
    post:
      tags: [Skills]
      operationId: createSkillWorkflowVersion
      summary: 为技能工作流创建新的不可变版本
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: workflowId
          in: path
          required: true
          schema: {$ref: '#/components/schemas/SkillWorkflowId'}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CreateSkillWorkflowVersionRequest'}
      responses:
        '201':
          description: 新的不可变工作流版本
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SkillWorkflowVersion'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
  /skill-workflow-runs:
    post:
      tags: [Skills]
      operationId: runSkillWorkflow
      summary: 在云端执行固定版本的技能工作流
      description: 使用同一个 Idempotency-Key 重试会返回同一次运行，不会创建第二个渲染任务。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          description: 本次工作流运行的稳定幂等键；重试必须复用同一值。
          schema: {type: string, minLength: 1, maxLength: 128, pattern: '\S'}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/RunSkillWorkflowRequest'}
      responses:
        '200':
          description: 渲染任务与本次运行冻结的工作流快照
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SkillWorkflowRun'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '402': {$ref: '#/components/responses/InsufficientBalance'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
  /render-tasks:
    post:
      tags: [RenderTasks]
      operationId: createRenderTask
      summary: 创建渲染任务
      description: >-
        可选 Idempotency-Key 提供创建幂等：网络超时后用同一个 key 重试，服务端复用
        同一次创建结果，不会产生第二个渲染任务；同一个 key 携带不同请求体时返回
        409 IDEMPOTENCY_KEY_REUSED。key 最长 128 字符；不带 key 时每次请求都按新任务
        处理（向后兼容）。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/TraceId'
        - name: Idempotency-Key
          in: header
          required: false
          description: 创建请求的稳定幂等键；重试时复用同一值，最长 128 字符。缺省时按新请求处理。
          schema: {type: string, maxLength: 128}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateRenderTaskRequest'
      responses:
        '200':
          description: 任务已创建并提交 Render；资金在任务完成后按后扣费模式结算
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RenderTask'
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '402': {$ref: '#/components/responses/InsufficientBalance'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
    get:
      tags: [RenderTasks]
      operationId: listRenderTasks
      summary: 游标分页查询渲染任务
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: status
          in: query
          schema: {$ref: '#/components/schemas/RenderTaskStatus'}
        - name: projectId
          in: query
          schema: {$ref: '#/components/schemas/ProjectId'}
        - name: from
          in: query
          description: 查询起点（含）；必须与 to 同时提供，区间不得超过一个自然月。
          schema: {type: string, format: date-time}
        - name: to
          in: query
          description: 查询终点（不含）；必须与 from 同时提供，区间不得超过一个自然月。
          schema: {type: string, format: date-time}
        - name: cursor
          in: query
          schema: {type: string, maxLength: 512}
        - name: limit
          in: query
          schema: {type: integer, minimum: 1, maximum: 100, default: 20}
      responses:
        '200':
          description: 任务列表
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items: {$ref: '#/components/schemas/RenderTask'}
                  nextCursor: {type: [string, 'null']}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
  /render-tasks/stats:
    get:
      tags: [RenderTasks]
      operationId: getRenderTaskStats
      summary: 任务队列月度聚合指标
      description: >-
        一次请求返回所选月的总数、分状态计数、费用合计与终态平均/P95 耗时，
        供控制台 KPI 使用，替代客户端全量翻页拉取后本地计算。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: from
          in: query
          description: 查询起点（含）；必须与 to 同时提供，区间不得超过一个自然月；缺省为当月。
          schema: {type: string, format: date-time}
        - name: to
          in: query
          description: 查询终点（不含）；必须与 from 同时提供，区间不得超过一个自然月。
          schema: {type: string, format: date-time}
      responses:
        '200':
          description: 月度聚合指标
          content:
            application/json:
              schema:
                type: object
                required: [from, to, total, byStatus, costFen]
                properties:
                  from: {type: string}
                  to: {type: string}
                  total: {type: integer, format: int64}
                  byStatus:
                    type: object
                    additionalProperties: {type: integer, format: int64}
                    description: 按状态计数；未出现的状态缺省，调用方按 0 处理。
                  costFen: {type: integer, format: int64}
                  averageDurationMs: {type: integer, format: int64}
                  p50DurationMs: {type: integer, format: int64, description: 终态任务端到端耗时的最近秩 P50（毫秒）；无有效样本时缺省。}
                  p95DurationMs: {type: integer, format: int64}
                  queueWait: {$ref: '#/components/schemas/PhaseDurationStats'}
                  execution: {$ref: '#/components/schemas/PhaseDurationStats'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
  /render-tasks/batch:
    post:
      tags: [RenderTasks]
      operationId: createBatchRenderTasks
      summary: 批量并行创建渲染任务
      description: >-
        持久化 1-1000 个任务为可追踪批次；租户级调度器按并发上限持续补位执行。
        可选 Idempotency-Key 提供创建幂等：网络超时后用同一个 key 重放返回同一批次，
        不会重复入队；同一个 key 携带不同请求体时返回 409 IDEMPOTENCY_KEY_REUSED。
        key 最长 128 字符，缺省时每次请求都创建新批次（向后兼容）。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/TraceId'
        - name: Idempotency-Key
          in: header
          required: false
          description: 创建批次的稳定幂等键；重试时复用同一值，最长 128 字符。缺省时按新批次处理。
          schema: {type: string, maxLength: 128}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CreateBatchRenderTasksRequest'}
      responses:
        '200':
          description: 批次已持久化并进入队列。
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CreateBatchRenderTasksResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '409':
          description: Idempotency-Key 已用于不同的批量创建请求（code=IDEMPOTENCY_KEY_REUSED）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
  /render-tasks/batch/import:
    post:
      tags: [RenderTasks]
      operationId: createBatchRenderTasksFromExcel
      summary: 上传 Excel 与图片/视频素材并创建批量渲染
      description: Excel 单元格填写同一请求中素材的文件名（或 asset:文件名），服务端上传并替换为临时 OSS 地址后创建现有批次。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/TraceId'
        - name: Idempotency-Key
          in: header
          required: false
          description: 重试同一次导入时复用的稳定请求键，最长 128 字符。
          schema: {type: string, maxLength: 128}
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [templateId, excel]
              properties:
                templateId: {type: string}
                name: {type: string, maxLength: 128}
                excel: {type: string, format: binary, description: 最大 10 MB 的 .xlsx 文件。}
                assets:
                  type: array
                  maxItems: 1000
                  items: {type: string, format: binary}
                qualityTier: {$ref: '#/components/schemas/QualityTier'}
                fps: {type: integer, enum: [24, 30, 60]}
                quality: {type: string, enum: [draft, standard, high]}
      responses:
        '200':
          description: 素材已绑定，批次已进入队列。
          content:
            application/json:
              schema:
                allOf:
                  - {$ref: '#/components/schemas/CreateBatchRenderTasksResponse'}
                  - type: object
                    required: [uploadedAssets, ignoredHeaders]
                    properties:
                      uploadedAssets: {type: integer, minimum: 0}
                      ignoredHeaders: {type: array, items: {type: string}}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
  /render-tasks/batches:
    get:
      tags: [RenderTasks]
      operationId: listRenderBatches
      summary: 查询当前租户的批量渲染批次
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - {name: from, in: query, required: true, schema: {type: string, format: date-time}}
        - {name: to, in: query, required: true, schema: {type: string, format: date-time}}
        - {name: page, in: query, required: false, schema: {type: integer, minimum: 1, default: 1}}
        - {name: pageSize, in: query, required: false, schema: {type: integer, minimum: 1, maximum: 100, default: 50}}
      responses:
        '200':
          description: 最近批次及汇总进度
          content:
            application/json:
              schema:
                type: object
                required: [items, concurrency, active, page, pageSize, total, hasMore]
                properties:
                  items: {type: array, items: {$ref: '#/components/schemas/RenderBatchSummary'}}
                  concurrency: {type: integer, minimum: 1, description: 当前租户的批量渲染并发上限，由服务端环境变量配置。}
                  active: {type: integer, minimum: 0, description: 当前租户所有批次占用的 dispatching/running 槽位数。}
                  page: {type: integer, minimum: 1}
                  pageSize: {type: integer, minimum: 1, maximum: 100}
                  total: {type: integer, minimum: 0}
                  hasMore: {type: boolean}
        '401': {$ref: '#/components/responses/Unauthorized'}
  /render-tasks/batches/{renderBatchId}:
    get:
      tags: [RenderTasks]
      operationId: getRenderBatch
      summary: 查询批次逐行状态
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - {name: renderBatchId, in: path, required: true, schema: {type: string}}
      responses:
        '200':
          description: 批次汇总与 Excel 逐行状态
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderBatchDetail'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
  /render-tasks/batches/{renderBatchId}/items/{itemId}:
    get:
      tags: [RenderTasks]
      operationId: getRenderBatchItem
      summary: 查询单个批量渲染项详情
      description: >-
        返回该行的当前状态、不可变原始输入快照（供“再次创建”预填）与按时间排列的
        尝试历史。attempts 最后一项始终是当前尝试。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - {name: renderBatchId, in: path, required: true, schema: {type: string}}
        - {name: itemId, in: path, required: true, schema: {type: string}}
      responses:
        '200':
          description: 批量渲染项详情
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderBatchItemDetail'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404':
          description: 批次或批量项不存在（code=RENDER_BATCH_NOT_FOUND 或 RENDER_BATCH_ITEM_NOT_FOUND）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
  /render-tasks/batches/{renderBatchId}/items/{itemId}/retry:
    post:
      tags: [RenderTasks]
      operationId: retryRenderBatchItem
      summary: 显式重试失败的批量渲染项
      description: |
        仅 status=failed 的批量项可重试。重试会复用该行创建时的原始输入、来源与输出
        参数（含 inputProps / templateId+templateReleaseId / output 等），不做任何
        默认值替换；这是一次新的计费渲染，不承诺免费重试。
        成功提交后批量项回到 pending 并分配新的 renderTaskId，响应与
        GET /render-tasks/batches/{renderBatchId}/items/{itemId} 相同。
        Idempotency-Key 必填（最长 128 字符）：网络超时或客户端重放时复用同一个 key，
        服务端只返回当前项，不推进尝试；同一 key 在后续尝试失败后重放仍然有效。
        每个批量项最多 20 次尝试（首次 + 最多 19 次重试），达到上限返回 409
        RETRY_LIMIT_REACHED。若关联渲染任务是派发超时/失败但晚到的 provider 回调仍可能
        补上并计费（可恢复派发失败），重试会被拒绝以避免双重计费，客户端应稍后刷新该项。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - {name: renderBatchId, in: path, required: true, schema: {type: string}}
        - {name: itemId, in: path, required: true, schema: {type: string}}
        - name: Idempotency-Key
          in: header
          required: true
          description: 本次重试的稳定幂等键；重试 HTTP 请求时复用同一值，最长 128 字符。
          schema: {type: string, minLength: 1, maxLength: 128}
      responses:
        '200':
          description: 重试已受理或幂等重放；返回该批量项的最新详情
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderBatchItemDetail'}
        '400':
          description: 缺少或非法 Idempotency-Key（code=INVALID_IDEMPOTENCY_KEY）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404':
          description: 批次或批量项不存在（code=RENDER_BATCH_NOT_FOUND 或 RENDER_BATCH_ITEM_NOT_FOUND）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
        '409':
          description: >-
            当前状态不可重试（code=RENDER_BATCH_ITEM_NOT_RETRYABLE，含并发重试时状态已变化）、
            重试次数已达上限（code=RETRY_LIMIT_REACHED）、关联渲染任务为可恢复派发失败且晚到
            回调仍可能计费（code=RENDER_BATCH_ITEM_RECOVERABLE_DISPATCH_FAILURE，应稍后刷新而
            不应盲目重试），或尝试历史损坏（code=RETRY_AUDIT_CORRUPTED）。
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
  /render-tasks/{renderTaskId}:
    get:
      tags: [RenderTasks]
      operationId: getRenderTask
      summary: 查询渲染任务
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/RenderTaskIdPath'
      responses:
        '200':
          description: 当前任务快照
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderTask'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
  /render-tasks/{renderTaskId}/input:
    get:
      tags: [RenderTasks]
      operationId: getRenderTaskInput
      summary: 查询渲染任务原始输入快照（用于再次创建）
      description: >-
        返回创建时持久化的输入快照，供“再次创建”预填。批量来源与含完整请求快照的
        独立任务返回完整输入；无法恢复完整请求（如老独立任务未捕获输出参数）时
        complete=false，客户端 MUST 提示用户重新确认输出参数后再创建，不能直接重放。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/RenderTaskIdPath'
      responses:
        '200':
          description: 原始输入快照
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderTaskInputSnapshot'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
  /render-tasks/{renderTaskId}/trace:
    get:
      tags: [RenderTasks]
      operationId: getRenderTaskTrace
      summary: 查询渲染任务链路视图（Langfuse 风格 span 树）
      description: |
        网关按租户校验任务归属后转发 render 内部 trace 端点。任务进行中可轮询：
        prepare 大阶段与每次 ctx 能力调用（ffmpeg/asr/storage）随执行逐条出现，
        完成后定格。schema 见 render-trace-v1。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/RenderTaskIdPath'
      responses:
        '200':
          description: 按开始时间升序的 span 列表
          content:
            application/json:
              schema: {$ref: './render-trace-v1.schema.json'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
  /render-tasks/{renderTaskId}/cancel:
    post:
      tags: [RenderTasks]
      operationId: cancelRenderTask
      summary: 请求取消渲染任务
      description: 取消是 best-effort；已发生的可计费执行仍可能被结算。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/RenderTaskIdPath'
        - $ref: '#/components/parameters/TraceId'
      responses:
        '200':
          description: 已接受取消请求
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderTask'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
  /render-tasks/{renderTaskId}/download:
    get:
      tags: [RenderTasks]
      operationId: downloadRenderTask
      summary: 刷新渲染产物下载链接（实时重签 OSS URL，返回 200 + JSON）
      description: |
        实时重签 OSS presigned URL，以 200 + JSON body `{downloadUrl, expiresAt}` 返回。
        Web/CLI 在现有 `output.downloadUrl` 过期或临过期时调用此端点换取新签名（CTR-008）。
        ff-server MUST 现场调 OSS `signatureUrl()`，禁止复用任务快照里的旧 URL。
        不做 302 重定向：浏览器 fetch 在 redirect:'manual' 下拿到 opaque-redirect
        filtered response，Location 头与响应体均不可读（CTR-008 §2.1）。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - $ref: '#/components/parameters/RenderTaskIdPath'
        - $ref: '#/components/parameters/TraceId'
      responses:
        '200':
          description: 重签成功，返回新的下载链接及其过期时刻
          content:
            application/json:
              schema: {$ref: '#/components/schemas/DownloadUrlResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409':
          description: 任务未到 completed 终态（含 failed/canceled），不可下载
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
        '410':
          description: OUTPUT_EXPIRED — 任务曾完成但 OSS 对象已被 GC，无法重签
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
        '500':
          description: INTERNAL_ERROR — OSS 重签失败等服务端错误，响应体 error.retryable 为 true 时可重试（CTR-008 §2.1）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
        '503':
          description: OSS 暂时不可达，可重试
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
  /render-tasks/upload-signature:
    post:
      tags: [RenderTasks]
      operationId: getBundleUploadSignature
      summary: 获取 bundle 上传签名（CLI 直传 OSS 用）
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: OSS POST Policy 签名 + bundleKeyPrefix
          content:
            application/json:
              schema: {$ref: '#/components/schemas/BundleUploadSignature'}
        '401': {$ref: '#/components/responses/Unauthorized'}
  /render-templates:
    get:
      tags: [RenderTemplates]
      operationId: listRenderTemplates
      summary: 列出可渲染的模板目录
      description: |
        返回当前可见的模板目录（Web 工作室 / 官网模板库共用此接口）。
        匿名可读：官网访客无需登录即可浏览公开模板目录，便于首屏渲染与 SEO。
        ff-server 已在 SaTokenConfigure.excludePathPatterns("/api/**") 放行，
        Controller 内部用 ensureTenantContext() 为匿名请求兜底租户上下文。
      security: []
      responses:
        '200':
          description: 模板列表
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items: {$ref: '#/components/schemas/RenderTemplate'}
    post:
      tags: [RenderTemplates]
      operationId: createRenderTemplate
      summary: 创建或更新当前租户的私有渲染模板
      description: |
        CLI `project upload` 上传并验证通过后，将选中的 composition 注册成模板。
        同一租户重复提交相同 templateKey 时更新原模板并保留 templateId。
        模板绑定 projectVersion + compositionId，后续 `render run --template <key>`
        唯一定位，无需再传 composition/bundle。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/SaveTemplateRequest'}
      responses:
        '200':
          description: 创建成功
          content:
            application/json:
              schema:
                type: object
                required: [templateId, status]
                properties:
                  templateId: {type: string}
                  status: {type: string, example: created}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
  /render-templates/{templateId}:
    get:
      tags: [RenderTemplates]
      operationId: getRenderTemplate
      summary: 查询单个模板详情（匿名可读）
      security: []
      parameters:
        - name: templateId
          in: path
          required: true
          schema: {type: string, minLength: 1, maxLength: 128}
      responses:
        '200':
          description: 模板详情
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderTemplate'}
        '404': {$ref: '#/components/responses/NotFound'}
    put:
      tags: [RenderTemplates]
      operationId: updateRenderTemplate
      summary: 更新当前租户的私有模板配置
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: templateId
          in: path
          required: true
          schema: {type: string, minLength: 1, maxLength: 128}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/UpdateTemplateRequest'}
      responses:
        '200':
          description: 更新成功
          content:
            application/json:
              schema:
                type: object
                required: [templateId, status]
                properties:
                  templateId: {type: string}
                  status: {type: string, example: updated}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
    delete:
      tags: [RenderTemplates]
      operationId: deleteRenderTemplate
      summary: 删除当前租户的私有模板
      description: |
        按模板 ID 或 template key 删除当前租户的私有模板。默认自动解析；
        引用同时匹配 ID 与 key 时返回 409，可通过 referenceType 明确指定。
        官方模板不能通过此接口删除。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: templateId
          in: path
          required: true
          description: template ID 或 template key
          schema: {type: string, minLength: 1, maxLength: 128}
        - name: referenceType
          in: query
          required: false
          description: 参数引用类型；auto 会同时检查 ID 与 key 并拒绝歧义匹配
          schema:
            type: string
            enum: [auto, id, key]
            default: auto
      responses:
        '200':
          description: 删除成功
          content:
            application/json:
              schema:
                type: object
                required: [templateId, templateKey, status]
                properties:
                  templateId: {type: string}
                  templateKey: {type: string}
                  status: {type: string, enum: [deleted]}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
  /render-templates/{templateId}/publish:
    post:
      tags: [RenderTemplates]
      operationId: publishRenderTemplate
      summary: 发布模板（draft → published）
      description: |
        createTemplate 默认创建为 draft，需发布后才对 listTemplates /
        render run --template 可见。CLI project upload 注册后自动调用。
        普通租户账号只能发布本租户模板；官方模板仍需要模板管理权限。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: templateId
          in: path
          required: true
          schema: {type: string, minLength: 1, maxLength: 128}
      responses:
        '200':
          description: 发布成功
          content:
            application/json:
              schema:
                type: object
                required: [templateId, status]
                properties:
                  templateId: {type: string}
                  status: {type: string, example: published}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
  /render-projects:
    post:
      tags: [RenderProjects]
      operationId: createRenderProject
      summary: 创建渲染项目（CTR-006 幂等：按 slug 找或创建）
      description: |
        幂等创建：ff-server 按 (tenant, slug) 查找。
        - 命中且 engine 匹配 → 200 OK + isExisting=true（复用已有 project）
        - engine 不匹配 → 409 Conflict PROJECT_SLUG_CONFLICT
        - 未命中 → 201 Created + isExisting=false

        CLI `project upload` 调用此接口。同一本地项目重复 upload 应得到同一 projectId。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CreateProjectRequest'}
      responses:
        '200':
          description: 复用已有项目（isExisting=true）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CreateProjectResult'}
        '201':
          description: 新建项目（isExisting=false）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CreateProjectResult'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '409':
          description: slug 已被占用（engine 不匹配）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
    get:
      tags: [RenderProjects]
      operationId: listRenderProjects
      summary: 列出当前租户的项目
      description: |
        返回当前租户的所有 active 项目。每个项目附带 latestReadyVersionId（若存在 ready 版本）。
        CLI 用此接口判断本地项目是否已注册（按 slug 匹配）。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 项目列表
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items: {$ref: '#/components/schemas/RenderProjectSummary'}
        '401': {$ref: '#/components/responses/Unauthorized'}
  /render-projects/{projectId}:
    get:
      tags: [RenderProjects]
      operationId: getRenderProject
      summary: 按 ID 查询项目
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: projectId
          in: path
          required: true
          schema: {$ref: '#/components/schemas/ProjectId'}
      responses:
        '200':
          description: 项目详情
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderProjectSummary'}
        '404': {$ref: '#/components/responses/NotFound'}
  /render-projects/by-slug/{slug}:
    get:
      tags: [RenderProjects]
      operationId: getRenderProjectBySlug
      summary: 按 slug 查项目（CTR-006 §4.2）
      description: |
        CLI `render run` 无 `--project-version` 时用此接口反查 latestReadyVersionId。
        返回 project 详情 + 最新 ready 版本的 projectVersionId + compositionIds。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: slug
          in: path
          required: true
          schema: {type: string, minLength: 1, maxLength: 128, pattern: '^[a-z0-9][a-z0-9._-]*$'}
      responses:
        '200':
          description: 项目详情（含 latestReadyVersionId + compositionIds）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/RenderProjectBySlugResult'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
  /ffmpeg-tasks:
    get:
      tags: [FfmpegTasks]
      operationId: listFfmpegTasks
      summary: 查询当前租户的 FFmpeg 任务
      description: |
        按创建时间降序列出归属当前租户的任务，先过滤再分页。默认列出自建任务；指定 parentRenderId 后只列出对应渲染的子任务。
        from 和 to 可单独使用。时间须含秒和时区（Z 或 ±HH:MM，偏移最多 18 小时），支持最多九位小数秒。两端都提供时 from 必须早于 to。
        翻页时保留原筛选条件，使用上一页返回的 nextCursor。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - {in: query, name: status, schema: {type: string, enum: [queued, running, completed, failed]}}
        - {in: query, name: parentRenderId, schema: {type: string}}
        - {in: query, name: from, description: 创建时间下界（含）, schema: {type: string, format: date-time}}
        - {in: query, name: to, description: 创建时间上界（不含）, schema: {type: string, format: date-time}}
        - {in: query, name: limit, schema: {type: integer, default: 20, minimum: 1, maximum: 100}}
        - {in: query, name: cursor, schema: {type: string}}
      responses:
        '200':
          description: 已按条件过滤的任务页
          content:
            application/json:
              schema:
                type: object
                required: [items, limit, hasMore]
                properties:
                  items:
                    type: array
                    items:
                      type: object
                      required: [taskId, status, mode, profile, createdAt, updatedAt]
                      properties:
                        taskId: {type: string}
                        status: {type: string, enum: [queued, running, completed, failed]}
                        mode: {type: string, enum: [ffmpeg, ffprobe]}
                        profile: {type: string, enum: [standard, highmem, gpu]}
                        output: {$ref: '#/components/schemas/FfmpegTaskOutput'}
                        error: {type: string}
                        errorCode: {type: string}
                        parentRenderId: {type: string}
                        createdAt: {type: string, format: date-time}
                        updatedAt: {type: string, format: date-time}
                  limit: {type: integer}
                  hasMore: {type: boolean}
                  nextCursor: {type: string, description: 有下一页时返回}
        '400':
          description: 日期格式无效或 from 大于等于 to，返回 FFMPEG_VALIDATION_ERROR。
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error: {$ref: '#/components/schemas/ErrorDetail'}
                  traceId: {type: string}
        '401': {$ref: '#/components/responses/Unauthorized'}
    post:
      tags: [FfmpegTasks]
      operationId: createFfmpegTask
      summary: 创建通用 FFmpeg 任务
      description: |
        RFC 0003 通用 FFmpeg 执行器。异步：成功返回 202 + taskId，
        客户端用 GET /ffmpeg-tasks/{taskId} 轮询或等 callbackUrl 回调。
        ffmpeg 永不直连网络——输入由服务端 fetch 到受控存储；
        gateway 层拒绝私网/元数据 URL 与 commands 里嵌入的协议 URL（SSRF 防护）。
        万向渲染不依赖会员订阅体系，不因套餐过期或调用次数上限拦截。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CreateFfmpegTaskRequest'}
      responses:
        '202':
          description: 任务已入队，执行在 FC 上异步进行
          content:
            application/json:
              schema:
                type: object
                required: [taskId, status]
                properties:
                  taskId: {$ref: '#/components/schemas/FfmpegTaskId'}
                  status: {type: string, enum: [queued]}
                  error: {type: [string, 'null']}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '503':
          description: 渲染服务暂时不可用（code=RENDER_SERVICE_UNAVAILABLE，可重试）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
  /ffmpeg-tasks/{taskId}:
    get:
      tags: [FfmpegTasks]
      operationId: getFfmpegTask
      summary: 查询 FFmpeg 任务状态
      description: |
        读服务端 job.json（引擎无关）。completed 时返回 7 天有效签名 URL（finalHttpUrl）。
        带归属校验（IDOR 防护）：任务持久化了 tenantRef 时，调用者身份必须匹配。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: taskId
          in: path
          required: true
          description: 任务 ID，形如 ffmpeg-<uuid>
          schema: {$ref: '#/components/schemas/FfmpegTaskId'}
      responses:
        '200':
          description: 任务状态快照
          content:
            application/json:
              schema: {$ref: '#/components/schemas/FfmpegTask'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '503':
          description: 渲染服务暂时不可用（code=RENDER_SERVICE_UNAVAILABLE，可重试）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ErrorResponse'}
  /temp-assets:
    post:
      tags: [TempAssets]
      operationId: uploadTempAsset
      summary: 上传临时素材（RFC 0004）
      description: |
        客户把生产素材以原始字节上传，ff-server 以租户身份转发到 render 服务内部
        /internal/v1/temp-assets。成功返回素材元数据 + 内网 oss:// 链接 + 配额快照。
        该 oss:// 链接只能回传给 ffmpeg 任务的 inputs 或渲染任务的 inputProps 变量，
        不能当作 HTTP URL 在浏览器打开（非 HTTP、bucket 私有）。
        body 为原始字节流，不要 JSON 包装；文件名经 percent-encode 放入 X-File-Name。
        素材按租户隔离，配额按租户计（默认 10G），超过返回 409。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: X-File-Name
          in: header
          required: false
          description: 素材文件名（建议 percent-encode；服务端会 sanitize，非法名返回 400）
          schema: {type: string}
      requestBody:
        required: true
        description: 原始字节。handler 接受任意 Content-Type（如 video/mp4）并存为素材 contentType。
        content:
          application/octet-stream:
            schema: {type: string, format: binary}
          '*/*':
            schema: {type: string, format: binary}
      responses:
        '201':
          description: 素材已上传，返回元数据 + 内网 oss:// 链接 + 配额
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetUploadResult'}
        '400': {$ref: '#/components/responses/TempAssetValidationError'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '409': {$ref: '#/components/responses/TempAssetQuotaExceeded'}
        '413': {$ref: '#/components/responses/TempAssetFileTooLarge'}
        '429': {$ref: '#/components/responses/TempAssetTooManyRequests'}
        '502': {$ref: '#/components/responses/TempAssetUpstreamError'}
        '503':
          description: 渲染服务不可用（RFC 0004 透传 render 状态码与 body；error 可能为字符串或结构化对象）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetServiceUnavailable'}
    get:
      tags: [TempAssets]
      operationId: listTempAssets
      summary: 列出当前租户未过期临时素材 + 配额
      description: |
        返回未过期（expiresAt 未到）的素材列表 + 配额快照。过期素材不返回，也不计入配额。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 素材列表 + 配额
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetListResult'}
        '400': {$ref: '#/components/responses/TempAssetValidationError'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '502': {$ref: '#/components/responses/TempAssetUpstreamError'}
        '503':
          description: 渲染服务不可用（RFC 0004 透传 render 状态码与 body；error 可能为字符串或结构化对象）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetServiceUnavailable'}
  /temp-assets/upload-token:
    post:
      tags: [TempAssets]
      operationId: createTempAssetUploadToken
      summary: 获取临时素材直传 OSS 凭证（大文件直传）
      description: |
        大文件直传方案第一步：render 生成限时预签名 PUT URL（uploadUrl），客户端把原始字节
        直接 PUT 到该 URL（绕过服务端 HTTP body 上限），随后调 POST /temp-assets/{assetId}/complete
        注册。签发时强制声明 sizeBytes 并做配额预留（超单文件 413、超配额 409）。

        **PUT 约束**：预签名 URL 的签名未包含 Content-Type，客户端 PUT 时必须**不带
        Content-Type 头**，否则会 403 SignatureDoesNotMatch。curl 使用 `-H 'Content-Type:'`；
        浏览器不要直接传带 type 的 File/Blob（fetch 会自动加该头），应传空 MIME 类型且
        无需全量读入内存的 `file.slice(0, file.size, '')`，并且不设置 Content-Type。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [fileName, sizeBytes]
              properties:
                fileName: {type: string, minLength: 1, maxLength: 128}
                contentType: {type: string}
                sizeBytes: {type: integer, minimum: 1, description: 声明的素材字节数（配额预检用）}
      responses:
        '201':
          description: 直传凭证 + 素材元信息
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetUploadToken'}
        '400': {$ref: '#/components/responses/TempAssetValidationError'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '409': {$ref: '#/components/responses/TempAssetQuotaExceeded'}
        '413': {$ref: '#/components/responses/TempAssetFileTooLarge'}
        '429': {$ref: '#/components/responses/TempAssetTooManyRequests'}
        '503':
          description: 渲染服务不可用（透传 render 状态码与 body）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetServiceUnavailable'}
  /temp-assets/quota:
    get:
      tags: [TempAssets]
      operationId: getTempAssetQuota
      summary: 租户临时素材配额快照
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      responses:
        '200':
          description: 配额快照
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetQuotaResult'}
        '400': {$ref: '#/components/responses/TempAssetValidationError'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '502': {$ref: '#/components/responses/TempAssetUpstreamError'}
        '503':
          description: 渲染服务不可用（RFC 0004 透传 render 状态码与 body；error 可能为字符串或结构化对象）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetServiceUnavailable'}
  /temp-assets/{assetId}/complete:
    post:
      tags: [TempAssets]
      operationId: completeTempAsset
      summary: 完成临时素材直传注册
      description: |
        大文件直传方案第二步：客户端已把对象 PUT 到 upload-token 给的预签名 URL 后调本端点；
        render 校验对象、计算 SHA-256、写入清单并返回素材元数据 + 配额。
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: assetId
          in: path
          required: true
          description: 素材 ID，形如 ta_<32 hex>
          schema: {$ref: '#/components/schemas/TempAssetId'}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [fileName]
              properties:
                fileName: {type: string, minLength: 1, maxLength: 128}
                contentType: {type: string}
      responses:
        '201':
          description: 素材已注册，返回元数据 + 内网 oss:// 链接 + 配额
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetWithQuota'}
        '400': {$ref: '#/components/responses/TempAssetValidationError'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '409': {$ref: '#/components/responses/TempAssetQuotaExceeded'}
        '413': {$ref: '#/components/responses/TempAssetFileTooLarge'}
        '503':
          description: 渲染服务不可用（透传 render 状态码与 body）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetServiceUnavailable'}
  /temp-assets/{assetId}:
    get:
      tags: [TempAssets]
      operationId: getTempAsset
      summary: 查询单素材元数据（租户隔离，跨租户 404）
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: assetId
          in: path
          required: true
          description: 素材 ID，形如 ta_<32 hex>
          schema: {$ref: '#/components/schemas/TempAssetId'}
      responses:
        '200':
          description: 素材元数据 + 配额
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetUploadResult'}
        '400': {$ref: '#/components/responses/TempAssetValidationError'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/TempAssetNotFound'}
        '502': {$ref: '#/components/responses/TempAssetUpstreamError'}
        '503':
          description: 渲染服务不可用（RFC 0004 透传 render 状态码与 body；error 可能为字符串或结构化对象）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetServiceUnavailable'}
    delete:
      tags: [TempAssets]
      operationId: deleteTempAsset
      summary: 删除素材并释放配额（租户隔离，跨租户 404）
      security:
        - sessionCookie: []
        - bearerToken: []
        - apiKey: []
      parameters:
        - name: assetId
          in: path
          required: true
          description: 素材 ID，形如 ta_<32 hex>
          schema: {$ref: '#/components/schemas/TempAssetId'}
      responses:
        '200':
          description: 已删除 + 释放后的配额快照
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetDeleteResult'}
        '400': {$ref: '#/components/responses/TempAssetValidationError'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/TempAssetNotFound'}
        '502': {$ref: '#/components/responses/TempAssetUpstreamError'}
        '503':
          description: 渲染服务不可用（RFC 0004 透传 render 状态码与 body；error 可能为字符串或结构化对象）
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TempAssetServiceUnavailable'}
  /preview-sessions:
    post:
      tags: [PreviewSessions]
      operationId: createPreviewSession
      summary: 创建短期 HyperFrames 预览会话
      description: |
        服务端按分支解析预览来源：私有项目分支校验租户对 projectVersion 的所有权；
        marketplace 分支根据 marketplaceTemplateId + marketplaceReleaseId 查找已发布的
        release（管理员租户可读 draft/testing），engine 必须为 hyperframes。两分支互斥
        （oneOf）。inputProps 只保存在短期会话中，禁止放入 previewUrl。previewUrl 必须
        指向独立 preview origin，并使用不可猜测、短期、只读 token；响应页面使用严格 CSP。

        安全注记：marketplace bundle 由第三方作者发布，浏览器 sandbox/CSP 无法阻止脚本
        通过 top-level navigation 外传 inputProps。当前实现由产品侧确认接受该风险。
      security:
        - sessionCookie: []
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CreatePreviewSessionRequest'}
      responses:
        '201':
          description: 会话已创建
          content:
            application/json:
              schema: {$ref: '#/components/schemas/PreviewSession'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
  /preview-sessions/{sessionId}:
    put:
      tags: [PreviewSessions]
      operationId: updatePreviewSession
      summary: 更新预览变量
      description: revision 必须等于当前版本；成功后原子递增，防止乱序更新覆盖新变量。
      security:
        - sessionCookie: []
      parameters:
        - $ref: '#/components/parameters/PreviewSessionIdPath'
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/UpdatePreviewSessionRequest'}
      responses:
        '200':
          description: 会话已更新
          content:
            application/json:
              schema: {$ref: '#/components/schemas/PreviewSession'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
    delete:
      tags: [PreviewSessions]
      operationId: deletePreviewSession
      summary: 销毁预览会话
      security:
        - sessionCookie: []
      parameters:
        - $ref: '#/components/parameters/PreviewSessionIdPath'
      responses:
        '204': {description: 会话已销毁或已经不存在}
        '401': {$ref: '#/components/responses/Unauthorized'}
  /marketplace/templates:
    get:
      tags: [Marketplace]
      operationId: listMarketplaceTemplates
      summary: 浏览已发布市场模板
      security: []
      parameters:
        - {name: categoryId, in: query, schema: {type: string, maxLength: 64}}
        - {name: tag, in: query, schema: {type: string, maxLength: 64}}
        - {name: featured, in: query, schema: {type: boolean}}
        - {name: cursor, in: query, schema: {type: string, maxLength: 512}}
        - {name: limit, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 20}}
      responses:
        '200':
          description: 仅返回 status=published 且存在 published currentStableRelease 的模板
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items: {type: array, items: {$ref: '#/components/schemas/MarketplaceTemplate'}}
                  nextCursor: {type: [string, 'null']}
  /marketplace/templates/{slug}:
    get:
      tags: [Marketplace]
      operationId: getMarketplaceTemplate
      summary: 按 slug 查询市场模板详情
      security: []
      parameters:
        - {name: slug, in: path, required: true, schema: {$ref: '#/components/schemas/MarketplaceTemplateSlug'}}
      responses:
        '200':
          description: 模板与当前稳定 Release
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [template, stableRelease]
                properties:
                  template: {$ref: '#/components/schemas/MarketplaceTemplate'}
                  stableRelease: {$ref: '#/components/schemas/PublicMarketplaceTemplateRelease'}
        '404': {$ref: '#/components/responses/NotFound'}
  /marketplace/templates/{templateId}/releases/{releaseId}:
    get:
      tags: [Marketplace]
      operationId: getMarketplaceTemplateRelease
      summary: 查询一个公开的不可变 Release
      security: []
      parameters:
        - {name: templateId, in: path, required: true, schema: {$ref: '#/components/schemas/MarketplaceTemplateId'}}
        - {name: releaseId, in: path, required: true, schema: {$ref: '#/components/schemas/MarketplaceTemplateReleaseId'}}
      responses:
        '200':
          description: 已发布 Release 的公开运行参数；来源、存储和测试字段不对匿名用户返回
          content:
            application/json:
              schema: {$ref: '#/components/schemas/PublicMarketplaceTemplateRelease'}
        '404': {$ref: '#/components/responses/NotFound'}
components:
  securitySchemes:
    sessionCookie:
      type: apiKey
      in: cookie
      name: Authentication
      description: Web 控制台使用的 Sa-Token Session Cookie（仅浏览器同源会话，REST/CLI 客户端不使用）。
    bearerToken:
      type: http
      scheme: bearer
      bearerFormat: MassRender access token
      description: CLI Personal/Service Access Token。
    apiKey:
      type: apiKey
      in: header
      name: X-API-KEY
      description: 控制台 API Key 页面生成的用户密钥。
  parameters:
    TraceId:
      name: X-Trace-Id
      in: header
      required: false
      schema: {type: string, minLength: 8, maxLength: 128}
    RenderTaskIdPath:
      name: renderTaskId
      in: path
      required: true
      schema: {$ref: '#/components/schemas/RenderTaskId'}
    PreviewSessionIdPath:
      name: sessionId
      in: path
      required: true
      schema: {type: string, pattern: '^ps_[A-Za-z0-9_-]{22,64}$'}
  responses:
    BadRequest:
      description: |
        请求格式错误。POST /render-tasks 在以下情况返回 400：
        - 同时传 entryId 和 compositionId 且两者不等 → code=ENTRY_SELECTOR_CONFLICT
        - 两者都未传 → code=ENTRY_SELECTOR_CONFLICT
        其他校验失败沿用既有错误码。
      content:
        application/json:
          schema: {$ref: '#/components/schemas/ErrorResponse'}
    Unauthorized:
      description: 未登录或凭据无效
      content:
        application/json:
          schema: {$ref: '#/components/schemas/ErrorResponse'}
    Forbidden:
      description: 凭据有效，但账号权限不足或租户套餐已到期
      content:
        application/json:
          schema: {$ref: '#/components/schemas/ErrorResponse'}
    InsufficientBalance:
      description: 可用余额不足，未创建 Render 执行
      content:
        application/json:
          schema: {$ref: '#/components/schemas/ErrorResponse'}
    Conflict:
      description: 幂等冲突或任务已进入不可取消终态
      content:
        application/json:
          schema: {$ref: '#/components/schemas/ErrorResponse'}
    Unprocessable:
      description: 项目版本、composition 或 inputProps 校验失败
      content:
        application/json:
          schema: {$ref: '#/components/schemas/ErrorResponse'}
    TooManyRequests:
      description: 租户并发或接口频率超过限制
      headers:
        Retry-After:
          schema: {type: integer, minimum: 1}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/ErrorResponse'}
    NotFound:
      description: 当前租户下不存在该任务
      content:
        application/json:
          schema: {$ref: '#/components/schemas/ErrorResponse'}
    TempAssetValidationError:
      description: 临时素材校验错误（缺/非法租户头、非法文件名、空 body 等），响应体为 {error, tenantRef}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/TempAssetErrorResponse'}
    TempAssetQuotaExceeded:
      description: 租户配额超限（code=TEMP_ASSET_QUOTA_EXCEEDED），响应体为 {error, tenantRef}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/TempAssetErrorResponse'}
    TempAssetFileTooLarge:
      description: 单文件超过大小上限（code=TEMP_ASSET_FILE_TOO_LARGE），响应体为 {error, tenantRef}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/TempAssetErrorResponse'}
    TempAssetTooManyRequests:
      description: 租户并发上传超过上限（code=TEMP_ASSET_UPLOAD_BUSY），稍后重试；响应体为 {error, tenantRef}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/TempAssetUploadBusyError'}
    TempAssetNotFound:
      description: 素材不存在或跨租户（IDOR 防护），响应体为 {error, tenantRef}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/TempAssetErrorResponse'}
    TempAssetUpstreamError:
      description: ff-server 无法到达 render 服务（RFC 0004），code=TEMP_ASSET_UPSTREAM_ERROR，可重试
      content:
        application/json:
          schema:
            type: object
            additionalProperties: false
            required: [error]
            properties:
              error:
                type: object
                additionalProperties: false
                required: [code, message, retryable]
                properties:
                  code: {const: TEMP_ASSET_UPSTREAM_ERROR}
                  message: {type: string}
                  retryable: {const: true}
  schemas:
    PhaseDurationStats:
      description: 所选月当前租户的终态渲染任务，按阶段独立取有效样本。零毫秒有效；无样本仅返回 sampleCount，旧版网关省略整个阶段。
      type: object
      required: [sampleCount]
      properties:
        sampleCount: {type: integer, minimum: 0}
        averageMs: {type: integer, format: int64, minimum: 0}
        p50Ms: {type: integer, format: int64, minimum: 0, description: 最近秩 P50}
        p95Ms: {type: integer, format: int64, minimum: 0, description: 最近秩 P95}
    TempAssetServiceUnavailable:
      type: object
      additionalProperties: true
      description: |
        render 服务不可用（RFC 0004 §4.5 原样透传 render 的状态码与 body，非通用
        ErrorResponse 的 {error, requestId, traceId}）。error 可能是 render 返回的
        字符串（如鉴权未配置时的 {error: "..."}），也可能是 {error: {code, message, retryable}}。
      required: [error]
      properties:
        error: {type: [string, object]}
    UsageMonthly:
      type: object
      required: [monthStart, consumeFen, renderMinutes, taskCount]
      properties:
        monthStart: {type: string, format: date}
        consumeFen: {type: string, pattern: '^\d+$'}
        renderMinutes: {type: integer, minimum: 0}
        taskCount: {type: integer, minimum: 0}
    UsageSummary:
      type: object
      required: [timezone, currentMonth, lastMonth, last30Days]
      properties:
        timezone: {type: string}
        currentMonth: {$ref: '#/components/schemas/UsageMonthly'}
        lastMonth: {$ref: '#/components/schemas/UsageMonthly'}
        last30Days:
          type: object
          required: [windowDays, totalTasks, successTasks, failedTasks, canceledTasks]
          properties:
            windowDays: {type: integer}
            totalTasks: {type: integer}
            successTasks: {type: integer}
            failedTasks: {type: integer}
            canceledTasks: {type: integer}
    DailyUsage:
      type: object
      required: [startDate, endDate, items]
      properties:
        startDate: {type: string, format: date}
        endDate: {type: string, format: date}
        items:
          type: array
          items:
            type: object
            required: [day, completed, failed, canceled, queued, total, consumeFen, renderMinutes]
            properties:
              day: {type: string, format: date}
              completed: {type: integer}
              failed: {type: integer}
              canceled: {type: integer}
              queued: {type: integer}
              total: {type: integer}
              consumeFen: {type: string, pattern: '^\d+$'}
              renderMinutes: {type: integer}
    Pricing:
      type: object
      required: [currency, billingUnit, defaultQualityTier, tiers]
      properties:
        currency: {type: string, const: CNY}
        billingUnit: {type: string, const: minute}
        defaultQualityTier: {type: string}
        tiers:
          type: array
          items:
            type: object
            required: [qualityTier, label, width, height, pricePerMinuteFen]
            properties:
              qualityTier: {type: string}
              label: {type: string}
              width: {type: integer}
              height: {type: integer}
              pricePerMinuteFen: {type: string, pattern: '^\d+(?:\.\d+)?$'}
    SkillId:
      type: string
      minLength: 1
      maxLength: 64
      pattern: '^[a-z][a-z0-9.-]*$'
    SkillVersion:
      type: string
      minLength: 1
      maxLength: 64
      pattern: '^[A-Za-z0-9][A-Za-z0-9._-]*$'
    SkillRef:
      type: object
      additionalProperties: false
      required: [id, version]
      properties:
        id: {$ref: '#/components/schemas/SkillId'}
        version: {$ref: '#/components/schemas/SkillVersion'}
    SkillExecutionTarget:
      type: string
      enum: [cloud]
    IntegratedSkillAvailability:
      type: object
      additionalProperties: false
      required: [kind]
      properties:
        kind: {const: integrated}
    DesignedSkillAvailability:
      type: object
      additionalProperties: false
      required: [kind, reason]
      properties:
        kind: {const: designed}
        reason: {type: string, minLength: 1, maxLength: 1000}
    UnavailableSkillAvailability:
      type: object
      additionalProperties: false
      required: [kind, reason]
      properties:
        kind: {const: unavailable}
        reason: {type: string, minLength: 1, maxLength: 1000}
    RequiresServiceAuthorizationSkillAvailability:
      type: object
      additionalProperties: false
      required: [kind, service, reason]
      properties:
        kind: {const: requires-service-authorization}
        service: {type: string, minLength: 1, maxLength: 128}
        reason: {type: string, minLength: 1, maxLength: 1000}
    SkillAvailability:
      oneOf:
        - {$ref: '#/components/schemas/IntegratedSkillAvailability'}
        - {$ref: '#/components/schemas/DesignedSkillAvailability'}
        - {$ref: '#/components/schemas/UnavailableSkillAvailability'}
        - {$ref: '#/components/schemas/RequiresServiceAuthorizationSkillAvailability'}
    SkillPermissionDisclosure:
      type: object
      additionalProperties: false
      required: [permission, description]
      properties:
        permission: {type: string, minLength: 1, maxLength: 128}
        description: {type: string, minLength: 1, maxLength: 1000}
    SkillDataDestinationDisclosure:
      type: object
      additionalProperties: false
      required: [destination, description]
      properties:
        destination: {type: string, minLength: 1, maxLength: 256}
        description: {type: string, minLength: 1, maxLength: 1000}
    SkillBillingMeter:
      type: object
      additionalProperties: false
      required: [meter, unit]
      properties:
        meter:
          type: string
          minLength: 1
          maxLength: 128
          pattern: '^[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]*$'
        unit: {type: string, minLength: 1, maxLength: 64}
    SkillFailureMode:
      type: object
      additionalProperties: false
      required: [code, description]
      properties:
        code: {type: string, minLength: 1, maxLength: 128, pattern: '^[A-Z][A-Z0-9_]*$'}
        description: {type: string, minLength: 1, maxLength: 1000}
    SkillRetryPolicy:
      type: object
      additionalProperties: false
      required: [mode, maxAttempts]
      properties:
        mode: {type: string, enum: [never, retryable-errors]}
        maxAttempts: {type: integer, minimum: 1, maximum: 10}
    SkillCancellationPolicy:
      type: object
      additionalProperties: false
      required: [mode]
      properties:
        mode: {type: string, enum: [unsupported, cooperative]}
    SkillTimeoutPolicy:
      type: object
      additionalProperties: false
      required: [mode, timeoutSeconds]
      properties:
        mode: {const: service-enforced}
        timeoutSeconds: {type: integer, minimum: 1, maximum: 86400}
    SkillDefinition:
      type: object
      additionalProperties: false
      required:
        - id
        - version
        - name
        - description
        - effect
        - inputSchema
        - outputSchema
        - parametersSchema
        - executionTargets
        - permissionDisclosures
        - dataDestinationDisclosures
        - billingMeters
        - preconditions
        - failureModes
        - retryPolicy
        - cancellationPolicy
        - timeoutPolicy
        - availability
      properties:
        id: {$ref: '#/components/schemas/SkillId'}
        version: {$ref: '#/components/schemas/SkillVersion'}
        name: {type: string, minLength: 1, maxLength: 128}
        description: {type: string, minLength: 1, maxLength: 2000}
        effect: {type: string, minLength: 1, maxLength: 1000}
        inputSchema: {type: object, additionalProperties: true, maxProperties: 200}
        outputSchema: {type: object, additionalProperties: true, maxProperties: 200}
        parametersSchema: {type: object, additionalProperties: true, maxProperties: 200}
        executionTargets:
          type: array
          minItems: 1
          maxItems: 4
          uniqueItems: true
          items: {$ref: '#/components/schemas/SkillExecutionTarget'}
        permissionDisclosures:
          type: array
          maxItems: 32
          items: {$ref: '#/components/schemas/SkillPermissionDisclosure'}
        dataDestinationDisclosures:
          type: array
          maxItems: 32
          items: {$ref: '#/components/schemas/SkillDataDestinationDisclosure'}
        billingMeters:
          type: array
          maxItems: 32
          items: {$ref: '#/components/schemas/SkillBillingMeter'}
        preconditions:
          type: array
          maxItems: 32
          items: {type: string, minLength: 1, maxLength: 1000}
        failureModes:
          type: array
          maxItems: 32
          items: {$ref: '#/components/schemas/SkillFailureMode'}
        retryPolicy: {$ref: '#/components/schemas/SkillRetryPolicy'}
        cancellationPolicy: {$ref: '#/components/schemas/SkillCancellationPolicy'}
        timeoutPolicy: {$ref: '#/components/schemas/SkillTimeoutPolicy'}
        availability: {$ref: '#/components/schemas/SkillAvailability'}
    SkillCatalog:
      type: object
      additionalProperties: false
      required: [items]
      properties:
        items:
          type: array
          maxItems: 100
          items: {$ref: '#/components/schemas/SkillDefinition'}
    SkillWorkflowId:
      type: string
      minLength: 1
      maxLength: 64
      pattern: '^swf_[A-Za-z0-9_-]+$'
    SkillWorkflowVersionNumber:
      type: integer
      minimum: 1
    SkillWorkflowActionId:
      type: string
      minLength: 1
      maxLength: 64
      pattern: '^[A-Za-z][A-Za-z0-9_-]*$'
    SkillWorkflowAction:
      type: object
      additionalProperties: false
      required: [actionId, skill, config, dependsOn]
      properties:
        actionId: {$ref: '#/components/schemas/SkillWorkflowActionId'}
        skill: {$ref: '#/components/schemas/SkillRef'}
        config:
          type: object
          additionalProperties: true
          maxProperties: 100
          description: 由所引用技能的 parametersSchema 校验的技能专属配置。
        dependsOn:
          type: array
          maxItems: 31
          uniqueItems: true
          description: 仅能引用同一 actions 数组中排在当前动作之前的 actionId。
          items: {$ref: '#/components/schemas/SkillWorkflowActionId'}
    CreateSkillWorkflowRequest:
      type: object
      additionalProperties: false
      required: [name, actions]
      properties:
        name: {type: string, minLength: 1, maxLength: 128}
        description: {type: string, maxLength: 2000}
        actions:
          type: array
          minItems: 1
          maxItems: 32
          description: 工作流动作的稳定执行顺序；依赖项必须指向更早的动作。
          items: {$ref: '#/components/schemas/SkillWorkflowAction'}
    CreateSkillWorkflowVersionRequest:
      type: object
      additionalProperties: false
      required: [name, actions]
      properties:
        name: {type: string, minLength: 1, maxLength: 128}
        description: {type: string, maxLength: 2000}
        actions:
          type: array
          minItems: 1
          maxItems: 32
          description: 新版本动作的稳定执行顺序；旧版本保持不可变。
          items: {$ref: '#/components/schemas/SkillWorkflowAction'}
    SkillWorkflowVersion:
      type: object
      additionalProperties: false
      required: [workflowId, version, digest, createdAt, name, actions]
      description: 可按 workflowId 和 version 永久寻址的不可变工作流快照。
      properties:
        workflowId: {$ref: '#/components/schemas/SkillWorkflowId'}
        version: {$ref: '#/components/schemas/SkillWorkflowVersionNumber'}
        digest: {type: string, pattern: '^[a-f0-9]{64}$'}
        createdAt: {type: string, format: date-time}
        name: {type: string, minLength: 1, maxLength: 128}
        description: {type: string, maxLength: 2000}
        actions:
          type: array
          minItems: 1
          maxItems: 32
          description: 按稳定执行顺序冻结的动作。
          items: {$ref: '#/components/schemas/SkillWorkflowAction'}
    SkillWorkflowList:
      type: object
      additionalProperties: false
      required: [items]
      properties:
        items:
          type: array
          maxItems: 100
          items: {$ref: '#/components/schemas/SkillWorkflowVersion'}
    SkillOutputOptions:
      type: object
      additionalProperties: false
      description: Skill 首个运行版本支持的输出覆盖；文件名、编码器和图片格式由固定 Release 决定，调用方不能覆盖。
      properties:
        qualityTier:
          type: string
          enum: [standard, hd, ultra]
          description: 质量档位。缺省时保持固定 Release 的原生参数。
        fps:
          type: integer
          enum: [24, 30, 60]
          description: 输出帧率。缺省时使用固定 Release 的原生帧率。
        quality:
          type: string
          enum: [draft, standard, high]
          description: 编码质量，与控制分辨率和计费的 qualityTier 相互独立。
        crf:
          type: integer
          minimum: 0
          maximum: 51
          description: 专家模式 CRF；数值越大文件越小。
        width:
          type: integer
          minimum: 64
          maximum: 7680
          multipleOf: 2
          description: 专家模式输出宽度；必须与 height 同时提供，宽高比不超过 4:1，且总像素数不得超过所选 qualityTier（缺省为 hd）的预算。
        height:
          type: integer
          minimum: 64
          maximum: 7680
          multipleOf: 2
          description: 专家模式输出高度；必须与 width 同时提供，宽高比不超过 4:1，且总像素数不得超过所选 qualityTier（缺省为 hd）的预算。
    RunSkillWorkflowRequest:
      type: object
      additionalProperties: false
      required: [executionTarget, workflowId, version, input]
      properties:
        executionTarget:
          type: object
          additionalProperties: false
          required: [kind]
          properties:
            kind: {const: cloud}
        workflowId: {$ref: '#/components/schemas/SkillWorkflowId'}
        version: {$ref: '#/components/schemas/SkillWorkflowVersionNumber'}
        input: {type: object, additionalProperties: true, maxProperties: 200}
        output: {$ref: '#/components/schemas/SkillOutputOptions'}
    SkillWorkflowRun:
      type: object
      additionalProperties: false
      required: [renderTask, workflowSnapshot]
      properties:
        renderTask: {$ref: '#/components/schemas/RenderTask'}
        workflowSnapshot: {$ref: '#/components/schemas/SkillWorkflowVersion'}
    CreatePreviewSessionRequest:
      type: object
      additionalProperties: false
      required: [entryId, inputProps]
      description: |-
        预览来源必须且只能提供 projectVersionId（私有项目分支）或 marketplaceTemplateId +
        marketplaceReleaseId（市场模板分支）中的一组；两者互斥（oneOf）。ff-server 会按
        分支解析对应 manifest：私有分支要求当前租户拥有该 project version 或该 version
        属于官方模板；marketplace 分支要求 release.status = published（管理员租户可读
        draft/testing）。
      properties:
        projectVersionId: {$ref: '#/components/schemas/ProjectVersionId'}
        marketplaceTemplateId: {$ref: '#/components/schemas/MarketplaceTemplateId'}
        marketplaceReleaseId: {$ref: '#/components/schemas/MarketplaceTemplateReleaseId'}
        entryId: {type: string, minLength: 1, maxLength: 128, pattern: '^[A-Za-z0-9][A-Za-z0-9._-]*$'}
        inputProps: {type: object, additionalProperties: true, maxProperties: 200}
      oneOf:
        - required: [projectVersionId]
          not: {anyOf: [{required: [marketplaceTemplateId]}, {required: [marketplaceReleaseId]}]}
        - required: [marketplaceTemplateId, marketplaceReleaseId]
          not: {required: [projectVersionId]}
    UpdatePreviewSessionRequest:
      type: object
      additionalProperties: false
      required: [revision, inputProps]
      properties:
        revision: {type: integer, minimum: 1}
        inputProps: {type: object, additionalProperties: true, maxProperties: 200}
    PreviewSession:
      type: object
      additionalProperties: false
      required: [sessionId, previewUrl, revision]
      properties:
        sessionId: {type: string, pattern: '^ps_[A-Za-z0-9_-]{22,64}$'}
        previewUrl:
          type: string
          format: uri
          description: 独立 preview origin 上的短期只读 URL，不包含 inputProps。
        revision: {type: integer, minimum: 1}
    RenderTaskId:
      type: string
      pattern: '^rt_[0-9A-HJKMNP-TV-Z]{26}$'
    ProviderRenderId:
      type: string
      pattern: '^rnd_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
      description: |
        渲染服务侧的任务 id（`rnd_<UUIDv7>`）。任务尚未被渲染服务接受时缺省。
        它也是关联 prepare 阶段派生的 ffmpeg 子任务的键（`GET /v1/ffmpeg-tasks?parentRenderId=`）。
    ProjectId:
      type: string
      pattern: '^prj_[0-9A-HJKMNP-TV-Z]{26}$'
    ProjectVersionId:
      type: string
      pattern: '^pv_[0-9A-HJKMNP-TV-Z]{26}$'
    MarketplaceTemplateId:
      type: string
      pattern: '^mtpl_[0-9A-HJKMNP-TV-Z]{26}$'
    MarketplaceTemplateReleaseId:
      type: string
      pattern: '^mrel_[0-9A-HJKMNP-TV-Z]{26}$'
    MarketplaceTemplateSlug:
      type: string
      minLength: 1
      maxLength: 128
      pattern: '^[a-z0-9][a-z0-9-]*$'
    RenderTaskStatus:
      type: string
      enum: [accepted, queued, rendering, combining, canceling, completed, failed, canceled]
    OutputOptions:
      type: object
      additionalProperties: false
      properties:
        fileName: {type: string, minLength: 1, maxLength: 255}
        codec:
          type: string
          enum: [h264, h265, vp8, vp9, prores, gif]
          default: h264
        imageFormat:
          type: string
          enum: [jpeg, png]
          default: jpeg
        qualityTier:
          type: string
          enum: [standard, hd, ultra]
          description: '质量档位（输出分辨率 + 计费单价）。缺省时渲染层保持 composition 原生参数，不发送该字段。各档分辨率见 QUALITY_TIER_SPECS。'
        fps:
          type: integer
          enum: [24, 30, 60]
          description: '输出帧率。缺省时使用模板或 composition 原生帧率。'
        quality:
          type: string
          enum: [draft, standard, high]
          description: '编码质量，与控制分辨率和计费的 qualityTier 相互独立。'
        crf:
          type: integer
          minimum: 0
          maximum: 51
          description: '专家模式 CRF；数值越大文件越小。'
        width:
          type: integer
          minimum: 64
          maximum: 7680
          multipleOf: 2
          description: '专家模式输出宽度；必须与 height 同时提供，宽高比不超过 4:1，且总像素数不得超过所选 qualityTier（缺省为 hd）的预算。'
        height:
          type: integer
          minimum: 64
          maximum: 7680
          multipleOf: 2
          description: '专家模式输出高度；必须与 width 同时提供，宽高比不超过 4:1，且总像素数不得超过所选 qualityTier（缺省为 hd）的预算。'
    QualityTier:
      type: string
      enum: [standard, hd, ultra]
      description: 'standard=720p、hd=1080p（默认）、ultra=1440p。档位越高分辨率越高、单价越贵。'
    CreateRenderTaskRequest:
      type: object
      additionalProperties: false
      description: |
        创建渲染任务。入口通过 `entryId` 选择（M3 起的权威字段）；
        `compositionId` 作为迁移期兼容别名保留——两者二选一，同时传必须相等，
        否则返回 400 ENTRY_SELECTOR_CONFLICT。M3 期间至少传一个。
        普通项目必须传 `projectVersionId`；市场模板改传成对的
        `templateId + templateReleaseId`，由 ff-server 解析固定 Release。
        （schema 层两者都设为可选；"至少一个"由服务端 EntrySelector 校验强制，
        详见 packages/contracts 的 resolveEntryId。）
      required: [inputProps]
      oneOf:
        - required: [projectVersionId]
          properties:
            projectVersionId: {$ref: '#/components/schemas/ProjectVersionId'}
            templateId: false
            templateReleaseId: false
        - required: [templateId, templateReleaseId]
          properties:
            projectVersionId: false
            templateId: {$ref: '#/components/schemas/MarketplaceTemplateId'}
            templateReleaseId: {$ref: '#/components/schemas/MarketplaceTemplateReleaseId'}
      properties:
        projectVersionId: {$ref: '#/components/schemas/ProjectVersionId'}
        entryId: {type: string, minLength: 1, maxLength: 128, description: '渲染入口 ID。Remotion 即 composition id；HyperFrames 即顶层 composition 的 data-composition-id。'}
        compositionId:
          type: string
          minLength: 1
          maxLength: 128
          deprecated: true
          description: '迁移期兼容别名，等价于 entryId。新代码应传 entryId；同时传两者时必须相等。'
        templateId: {$ref: '#/components/schemas/MarketplaceTemplateId'}
        templateReleaseId:
          allOf:
            - $ref: '#/components/schemas/MarketplaceTemplateReleaseId'
          description: 市场渲染必须固定不可变 Release；ff-server 将其解析为平台 snapshot 后再提交数据面。
        inputProps: {type: object, additionalProperties: true}
        rowLabel:
          type: string
          maxLength: 128
          description: 批量渲染行的展示名称（如商品名）；只用于控制台展示与失败定位，不进入 inputProps，也不参与渲染。
        bundleKeyPrefix: {type: string, minLength: 1, maxLength: 512, description: 'CLI 上传的 bundle 的 OSS key prefix（可选）'}
        output: {$ref: '#/components/schemas/OutputOptions'}
        clientMetadata:
          type: object
          additionalProperties: false
          properties:
            source: {type: string, maxLength: 64}
            templateId: {type: string, maxLength: 64}
        excelRow:
          type: integer
          minimum: 2
          description: 批量创建时的原始 Excel 行号，用于进度明细和失败定位；单条创建可省略。
    CreateBatchRenderTasksRequest:
      type: object
      additionalProperties: false
      required: [tasks]
      properties:
        name: {type: string, maxLength: 128}
        tasks:
          type: array
          minItems: 1
          maxItems: 1000
          items: {$ref: '#/components/schemas/CreateRenderTaskRequest'}
    RenderBatchError:
      type: object
      additionalProperties: false
      properties:
        code: {type: string}
        message: {type: string}
    RenderBatchSummary:
      type: object
      additionalProperties: false
      required: [renderBatchId, name, total, pending, running, completed, failed, status, createdAt, updatedAt, concurrency]
      properties:
        renderBatchId: {type: string}
        name: {type: string}
        total: {type: integer, minimum: 1, maximum: 1000}
        pending: {type: integer, minimum: 0, maximum: 1000}
        running: {type: integer, minimum: 0, maximum: 1000}
        completed: {type: integer, minimum: 0, maximum: 1000}
        failed: {type: integer, minimum: 0, maximum: 1000}
        status: {type: string, enum: [queued, running, completed, partial_failed, failed]}
        createdAt: {type: string, format: date-time}
        updatedAt: {type: string, format: date-time}
        concurrency: {type: integer, minimum: 1, description: 当前服务端配置的租户级批量渲染并发上限。}
    CreateBatchRenderTasksResponse:
      $ref: '#/components/schemas/RenderBatchSummary'
    RenderBatchItem:
      type: object
      additionalProperties: false
      required: [itemId, rowNumber, status]
      properties:
        itemId: {type: string}
        rowNumber: {type: integer, minimum: 2}
        rowLabel:
          type: [string, 'null']
          maxLength: 128
          description: 批量渲染行的展示名称（如商品名）；只用于展示与失败定位。
        componentId: {type: string}
        status: {type: string, enum: [pending, dispatching, running, completed, failed, canceled]}
        renderTaskId: {$ref: '#/components/schemas/RenderTaskId'}
        error: {$ref: '#/components/schemas/RenderBatchError'}
        attemptCount: {type: integer, minimum: 1, description: 已进行的尝试次数；首次执行即为 1，每次显式重试加 1。}
    RenderBatchDetail:
      type: object
      additionalProperties: false
      required: [renderBatchId, name, total, pending, running, completed, failed, status, createdAt, updatedAt, concurrency, items]
      properties:
        renderBatchId: {type: string}
        name: {type: string}
        total: {type: integer, minimum: 1, maximum: 1000}
        pending: {type: integer, minimum: 0, maximum: 1000}
        running: {type: integer, minimum: 0, maximum: 1000}
        completed: {type: integer, minimum: 0, maximum: 1000}
        failed: {type: integer, minimum: 0, maximum: 1000}
        status: {type: string, enum: [queued, running, completed, partial_failed, failed]}
        createdAt: {type: string, format: date-time}
        updatedAt: {type: string, format: date-time}
        concurrency: {type: integer, minimum: 1, description: 当前服务端配置的租户级批量渲染并发上限。}
        items: {type: array, maxItems: 1000, items: {$ref: '#/components/schemas/RenderBatchItem'}}
    RenderBatchAttempt:
      type: object
      additionalProperties: false
      required: [attempt, status]
      description: 一次执行尝试的审计记录（只读，按时间从旧到新排列）。
      properties:
        attempt: {type: integer, minimum: 1, description: 尝试序号，首次执行从 1 开始。}
        renderTaskId: {$ref: '#/components/schemas/RenderTaskId'}
        status: {type: string, description: 该次尝试的状态；最后一次尝试的状态与批量项当前状态一致。}
        error: {$ref: '#/components/schemas/RenderBatchError'}
        createdAt: {type: string, format: date-time, description: 该次尝试的开始时间。}
    RenderTaskInputSnapshot:
      type: object
      additionalProperties: false
      required: [input, complete]
      description: |
        渲染任务创建时的输入快照，供“再次创建”预填。
        `complete=false` 表示服务端只能恢复部分字段（通常是老任务没有持久化输出参数），
        客户端 MUST 提示用户重新确认后再创建，不能直接重放。
      properties:
        input: {$ref: '#/components/schemas/CreateRenderTaskRequest'}
        complete:
          type: boolean
          description: input 是否为完整可重放快照；false 时 output 等字段可能缺失。
    RenderBatchItemDetail:
      description: |
        单个批量渲染项详情：批次行状态 + 不可变原始输入快照 + 尝试历史。
        重试接口的响应用于同一 schema。
      allOf:
        - $ref: '#/components/schemas/RenderBatchItem'
        - type: object
          additionalProperties: false
          required: [batchId, createdAt, updatedAt, input, complete, attempts]
          properties:
            batchId: {type: string, description: 所属批次 ID（等价于路径参数 renderBatchId）。}
            createdAt: {type: string, format: date-time, description: 该批量项创建时间。}
            updatedAt: {type: string, format: date-time, description: 该批量项最后更新时间。}
            input: {$ref: '#/components/schemas/CreateRenderTaskRequest'}
            complete:
              type: boolean
              description: 批量项的输入快照始终完整，因此恒为 true。
            attempts:
              type: array
              description: 按时间从旧到新排列的尝试历史；最后一项是当前尝试，服务端重试幂等键不会返回。
              items: {$ref: '#/components/schemas/RenderBatchAttempt'}
    RenderProgress:
      type: object
      additionalProperties: false
      required: [completedChunks, totalChunks, percent]
      properties:
        completedChunks: {type: integer, minimum: 0}
        totalChunks: {type: integer, minimum: 0}
        percent: {type: number, minimum: 0, maximum: 100}
        stage:
          type: string
          enum: [materialize, execute, asr, ffmpeg, upload]
          description: |
            prepare 执行中的当前阶段（仅 status=preparing 时出现）。prepare 不产生
            分片，percent 恒为 0 无意义；消费方应展示阶段标签而非百分比。
    RenderOutput:
      type: object
      additionalProperties: false
      required: [downloadUrl, expiresAt, digest, sizeInBytes]
      description: |
        最终产物元数据。正常渲染必带 durationSeconds/width/height/codec；
        prepare-only 任务（客户代码在 prepare 阶段直接产出最终文件）可以是音频
        或通用文件，媒体字段缺省，绝不为它编造分辨率。fileName/contentType
        描述原始文件名与下载 MIME。
      properties:
        downloadUrl: {type: string, format: uri, pattern: '^https://'}
        expiresAt:
          type: string
          format: date-time
          description: |
            签名 URL 过期时刻（RFC 3339 UTC）。由 ff-server 填充，MUST 与同一响应的
            downloadUrl 同一次签发；render 服务不填此字段。客户端据此判断重签时机
            （CTR-008 §3.3）：now + 安全余量 ≥ expiresAt 即调 download 端点重签。
        digest: {type: string, pattern: '^sha256:[a-f0-9]{64}$'}
        sizeInBytes: {type: integer, minimum: 0}
        durationSeconds: {type: number, minimum: 0}
        width: {type: integer, minimum: 1}
        height: {type: integer, minimum: 1}
        codec: {type: string}
        fileName: {type: string, maxLength: 128}
        contentType: {type: string, maxLength: 128}
        # 客户代码附带的人类可读结果说明（如「未检测到语音，已原样返回原视频」），
        # 仅 prepare 任务可能出现；网关从 job.output 原样透传，客户端应展示给用户。
        note: {type: string, minLength: 1, maxLength: 500}
    DownloadUrlResponse:
      type: object
      additionalProperties: false
      required: [downloadUrl, expiresAt]
      description: |
        download 端点 200 响应体（CTR-008 §2.1）。downloadUrl 与 expiresAt
        MUST 同源同时刻签发（同一 OSS object、同一次 signatureUrl 调用）。
      properties:
        downloadUrl: {type: string, format: uri, pattern: '^https://'}
        expiresAt: {type: string, format: date-time}
    BillingSummary:
      type: object
      additionalProperties: false
      required: [currency, settledAmountInFen]
      description: |
        v1 后扣费摘要。任务完成后按实际用量结算；失败或取消不扣费。
        v1 不冻结资金，因此不暴露 reserved amount。
      properties:
        currency: {const: CNY}
        settledAmountInFen:
          type: integer
          minimum: 0
          description: 本次任务按实际用量结算的金额，单位：分。
        pricingVersion: {type: string}
    RenderCostItem:
      type: object
      additionalProperties: false
      required: [meter, quantity, billedQuantity, amountFen]
      description: |
        一条费用明细。meter 形如 `<capability>.<quantity>`，例如
        `render.outputSeconds`、`asr.audioSeconds`。客户端按 meter 泛化渲染，
        不要为某个能力写死字段。
      properties:
        meter: {type: string, pattern: '^[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]*$'}
        quantity: {type: number, minimum: 0, description: 实际计量数量（秒）。}
        billedQuantity: {type: number, minimum: 0, description: 计费数量（应用保底后）。}
        amountFen: {type: integer, minimum: 0, description: 该项费用，单位：分。}
    RenderCapabilityCall:
      type: object
      additionalProperties: false
      required: [capability, meters, cached, durationMs]
      description: 能力代理的一次调用记录（展示用；计费以 usage.meters 为准）。
      properties:
        capability: {type: string, pattern: '^[a-z][a-zA-Z0-9]*$'}
        op: {type: string, maxLength: 64}
        meters:
          type: object
          additionalProperties: {type: number, minimum: 0}
          propertyNames: {pattern: '^[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]*$'}
        cached: {type: boolean, description: 命中缓存（仍按命中时长计费）。}
        durationMs: {type: integer, minimum: 0}
    RenderTaskUsage:
      type: object
      additionalProperties: true
      description: |
        终态 usage 摘要：渲染计量 + 能力计量。`meters` 是计费口径，`capabilityCalls`
        只是展示（最多 50 条）。允许未知字段，便于新增能力时先发布计量再更新文档。
      properties:
        engine: {type: string}
        renderedFrames: {type: integer, minimum: 0}
        fcInvocations: {type: integer, minimum: 0}
        computeDurationMs: {type: integer, minimum: 0}
        prepare:
          type: object
          additionalProperties: true
          description: |
            prepare 阶段计量。`audioSeconds` 是提交给 ASR 提供方的音频秒数；
            `asrCachedAudioSeconds` 是未提交就交付的秒数（ASR 结果缓存命中，或 prepared
            props 缓存回放），两者之和等于 meters 中的 `asr.audioSeconds`。
          properties:
            entry: {type: string}
            codeDurationMs: {type: integer, minimum: 0}
            ffmpegCalls: {type: integer, minimum: 0}
            asrCalls: {type: integer, minimum: 0}
            cacheHit: {type: boolean}
            audioSeconds: {type: number, minimum: 0}
            asrCachedCalls: {type: integer, minimum: 0}
            asrCachedAudioSeconds: {type: number, minimum: 0}
            propsBytes: {type: integer, minimum: 0}
            mediaUrlsIssued: {type: integer, minimum: 0}
        meters:
          type: object
          additionalProperties: {type: number, minimum: 0}
          propertyNames: {pattern: '^[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]*$'}
        capabilityCalls:
          type: array
          maxItems: 50
          items: {$ref: '#/components/schemas/RenderCapabilityCall'}
        capabilityCallsTruncated: {type: integer, minimum: 0}
    RenderTask:
      type: object
      additionalProperties: false
      required: [renderTaskId, projectVersionId, compositionId, status, progress, createdAt, updatedAt]
      description: |
        渲染任务。M3 起 `entryId` 是权威入口字段；`compositionId` 作为兼容别名与 entryId
        同值保留，新代码应优先读 entryId，缺失时回退 compositionId。
      properties:
        renderTaskId: {$ref: '#/components/schemas/RenderTaskId'}
        projectVersionId: {$ref: '#/components/schemas/ProjectVersionId'}
        entryId: {type: string, minLength: 1, maxLength: 128, description: '渲染入口 ID（M3 起权威）。'}
        compositionId: {type: string, deprecated: true, description: '兼容别名，与 entryId 同值。'}
        templateId: {$ref: '#/components/schemas/MarketplaceTemplateId'}
        templateReleaseId: {$ref: '#/components/schemas/MarketplaceTemplateReleaseId'}
        status: {$ref: '#/components/schemas/RenderTaskStatus'}
        progress: {$ref: '#/components/schemas/RenderProgress'}
        providerRenderId: {$ref: '#/components/schemas/ProviderRenderId'}
        output:
          oneOf:
            - {$ref: '#/components/schemas/RenderOutput'}
            - {type: 'null'}
        billing:
          oneOf:
            - {$ref: '#/components/schemas/BillingSummary'}
            - {type: 'null'}
        costFen:
          type: integer
          minimum: 0
          description: 本次渲染实际扣费（分）= 渲染费 + 各能力费；ff-server 当前响应字段。
        costItems:
          type: array
          description: |
            费用明细，一项对应一个计量项（meter，形如 `<capability>.<quantity>`）。
            总额仍以 costFen 为准。老任务或未结算任务缺省。
          items: {$ref: '#/components/schemas/RenderCostItem'}
        usage:
          oneOf:
            - {$ref: '#/components/schemas/RenderTaskUsage'}
            - {type: 'null'}
        error:
          oneOf:
            - {$ref: '#/components/schemas/ErrorDetail'}
            - {type: 'null'}
        canCancel: {type: boolean}
        canRetry: {type: boolean}
        createdAt: {type: string, format: date-time}
        updatedAt: {type: string, format: date-time}
        completedAt: {type: [string, 'null'], format: date-time}
    ErrorDetail:
      type: object
      additionalProperties: false
      required: [code, message, retryable]
      properties:
        code: {type: string, pattern: '^[A-Z][A-Z0-9_]+$'}
        message: {type: string, maxLength: 2000}
        retryable: {type: boolean}
        stage:
          type: string
          enum: [accepted, planning, rendering, combining, publishing, canceling]
          description: 执行失败阶段，与 render-event schema 的 error.stage 对齐。
        chunkIndex:
          type: integer
          minimum: 0
          description: 失败关联的分片索引，仅 rendering 阶段分片失败时填充。
        details: {type: object, additionalProperties: true}
    BundleUploadSignature:
      type: object
      additionalProperties: false
      required: [accessId, host, dir, policy, signature, expire, bucket, bundleKeyPrefix]
      properties:
        accessId: {type: string}
        host: {type: string, description: 'OSS 上传地址，如 https://bucket.oss-cn-beijing.aliyuncs.com'}
        dir: {type: string, description: 'OSS key 前缀（含 OSS prefix），CLI 上传时 key = dir + 相对路径'}
        policy: {type: string, description: 'Base64 编码的 POST Policy'}
        signature: {type: string}
        expire: {type: integer, description: '过期时间戳（秒）'}
        maxFileSize: {type: integer}
        bucket: {type: string}
        bundleKeyPrefix: {type: string, description: '传给渲染的 bundle key prefix（不含 OSS prefix）'}
    ErrorResponse:
      type: object
      additionalProperties: false
      required: [error, requestId, traceId]
      properties:
        error: {$ref: '#/components/schemas/ErrorDetail'}
        requestId: {type: string}
        traceId: {type: string}
    TemplateFieldType:
      type: string
      enum: [text, color, url, number, checkbox, select, json]
      description: 模板参数字段的 UI 渲染类型，决定工作室表单控件。
    TemplateField:
      type: object
      additionalProperties: false
      required: [key, label, type, defaultValue]
      properties:
        key: {type: string, minLength: 1, maxLength: 64, description: 参数键，对应渲染 inputProps 的 key}
        label: {type: string, minLength: 1, maxLength: 64, description: 工作室表单展示名}
        type: {$ref: '#/components/schemas/TemplateFieldType'}
        defaultValue: {type: string, maxLength: 262144, description: 默认值（统一为字符串，number/checkbox/json 类型由客户端转换）}
        schemaType:
          type: string
          enum: [string, number, integer, boolean, array, object]
          description: 原始 JSON Schema 类型；json 控件用它区分 array/object。
        schema:
          type: object
          additionalProperties: true
          description: 对应 inputProps 属性的 JSON Schema，供客户端展示和预校验。
        required:
          type: boolean
          description: inputProps 根 schema 是否要求该属性存在。
        hidden:
          type: boolean
          description: >-
            仅为兼容旧输入保留的字段。不计入面向用户的可改项：工作室表单、批量编辑与示例工作簿
            不展示它；输入校验、默认值补齐与批量导入读取不变。网关未返回该属性时按「不是兼容字段」处理。
        options:
          type: array
          maxItems: 100
          description: select 控件的可选值及展示文本。
          items:
            type: object
            additionalProperties: false
            required: [value, label]
            properties:
              value: {type: string, maxLength: 256}
              label: {type: string, maxLength: 256}
    TemplateRenderConfig:
      type: object
      additionalProperties: false
      properties:
        fps: {type: integer, minimum: 1, maximum: 120}
        width: {type: integer, minimum: 1, maximum: 7680}
        height: {type: integer, minimum: 1, maximum: 4320}
        format: {type: string, maxLength: 16}
    SaveTemplateRequest:
      type: object
      additionalProperties: false
      required: [projectId, projectVersionId, compositionId, name, templateKey]
      description: 创建模板请求（CLI project upload 后注册 composition 为模板）
      properties:
        projectId: {type: string, description: 项目 ID}
        projectVersionId: {type: string, description: 关联的项目版本ID}
        compositionId: {type: string, description: 绑定的 composition ID}
        name: {type: string, minLength: 1, maxLength: 128, description: 模板显示名}
        description: {type: string, maxLength: 512}
        templateKey: {type: string, minLength: 1, maxLength: 128, pattern: '^[a-z0-9][a-z0-9._-]*$', description: 模板唯一key（render run --template 用）}
        coverUrl: {type: string, format: uri}
        category: {type: string, maxLength: 32, description: 模板分类（官网筛选tab）}
        coverFileId: {type: integer, format: int64}
        fields:
          type: array
          items: {$ref: '#/components/schemas/TemplateField'}
          description: 可调参数定义（从 build 的 schema 推导）
        renderConfigJson: {type: string, description: 渲染配置 JSON 字符串}
        sort: {type: integer}
    UpdateTemplateRequest:
      type: object
      additionalProperties: false
      properties:
        projectVersionId: {type: string}
        compositionId: {type: string}
        name: {type: string, minLength: 1, maxLength: 128}
        description: {type: string, maxLength: 512}
        templateKey: {type: string, minLength: 1, maxLength: 128, pattern: '^[a-z0-9][a-z0-9._-]*$'}
        coverUrl: {type: string, format: uri}
        category: {type: string, maxLength: 32}
        coverFileId: {type: integer, format: int64}
        fields:
          type: array
          items: {$ref: '#/components/schemas/TemplateField'}
        renderConfigJson: {type: string}
        sort: {type: integer}
    RenderTemplate:
      type: object
      additionalProperties: false
      required: [templateId, projectId, projectVersionId, compositionId, name, description, engine, templateKey, fields, status, sort]
      properties:
        templateId: {type: string, minLength: 1, maxLength: 128}
        projectId: {$ref: '#/components/schemas/ProjectId'}
        projectVersionId: {$ref: '#/components/schemas/ProjectVersionId'}
        compositionId: {type: string, minLength: 1, maxLength: 128}
        name: {type: string, minLength: 1, maxLength: 128}
        description: {type: string, maxLength: 1024}
        engine:
          type: string
          enum: [remotion, hyperframes, html-video]
        templateKey: {type: string, minLength: 1, maxLength: 64, description: CLI --template 引用的 key}
        coverUrl:
          type: [string, 'null']
          format: uri
          description: 官网卡片封面图 URL。为空时官网不展示该模板。
        category:
          type: [string, 'null']
          maxLength: 32
          description: 模板分类（如「营销推广」「数据报告」），由 ff-admin 录入，仅影响官网分组筛选。
        fields:
          type: array
          items: {$ref: '#/components/schemas/TemplateField'}
        renderConfig: {$ref: '#/components/schemas/TemplateRenderConfig'}
        status:
          type: integer
          enum: [0, 1, 2]
          description: 0=draft（草稿）, 1=published（已发布，官网展示）, 2=offline（已下架）。官网仅展示 status=1 的模板。
        sort: {type: integer, minimum: 0, description: 排序权重，越小越靠前}
    CreateProjectRequest:
      type: object
      additionalProperties: false
      description: |
        创建渲染项目请求（CTR-006 幂等）。ff-server 按 (tenant, slug) 找或创建。
        同 slug 已存在且 engine 匹配 → 复用；engine 冲突 → 409 PROJECT_SLUG_CONFLICT。
      required: [name, slug, engine]
      properties:
        name: {type: string, minLength: 1, maxLength: 128, description: 项目显示名（可改）}
        slug:
          type: string
          minLength: 1
          maxLength: 128
          pattern: '^[a-z0-9][a-z0-9._-]*$'
          description: 业务唯一键（不可改），tenant 内唯一。CLI 从 package.json name 推导。
        description: {type: string, maxLength: 1024}
        engine:
          type: string
          enum: [remotion, hyperframes, html-video]
    CreateProjectResult:
      type: object
      additionalProperties: false
      description: 创建/复用项目的结果。isExisting=true 表示复用了已有 project（200 OK）；false 表示新建（201 Created）。
      required: [projectId, isExisting]
      properties:
        projectId: {$ref: '#/components/schemas/ProjectId'}
        isExisting: {type: boolean, description: true=复用已有，false=新建}
    RenderProjectSummary:
      type: object
      additionalProperties: false
      description: listProjects 返回项（CTR-006 §4.3 扩展：含 slug + latestReadyVersionId）。
      required: [projectId, name, slug, engine]
      properties:
        projectId: {$ref: '#/components/schemas/ProjectId'}
        name: {type: string}
        slug: {type: string}
        engine:
          type: string
          enum: [remotion, hyperframes, html-video]
        latestReadyVersionId:
          allOf:
            - $ref: '#/components/schemas/ProjectVersionId'
          description: 项目下最新 ready 状态的 projectVersionId。无 ready 版本时不出现此字段。
    RenderProjectBySlugResult:
      type: object
      additionalProperties: false
      description: by-slug 查询结果（CTR-006 §4.2）。
      required: [projectId, name, slug, engine]
      properties:
        projectId: {$ref: '#/components/schemas/ProjectId'}
        name: {type: string}
        slug: {type: string}
        engine:
          type: string
          enum: [remotion, hyperframes, html-video]
        latestReadyVersionId:
          allOf:
            - $ref: '#/components/schemas/ProjectVersionId'
          description: 项目下最新 ready 状态的 projectVersionId。无 ready 版本时不出现此字段。
        compositionIds:
          type: array
          description: latestReadyVersion 的所有 composition id 列表。CLI 渲染时若只有一个可自动选；多个要求 --composition。
          items: {type: string, minLength: 1, maxLength: 128}
          minItems: 0
    MarketplaceTemplateStatus:
      type: string
      enum: [draft, published, offline]
    MarketplaceCompatibility:
      type: string
      enum: [compatible, breaking, unknown]
    MarketplaceTemplate:
      type: object
      additionalProperties: false
      required:
        [id, slug, ownerTenantId, title, description, tags, status, isFeatured, sortOrder, createdAt, updatedAt]
      properties:
        id: {$ref: '#/components/schemas/MarketplaceTemplateId'}
        slug: {$ref: '#/components/schemas/MarketplaceTemplateSlug'}
        ownerTenantId: {type: string, minLength: 1, maxLength: 64}
        creatorUserId: {type: [string, 'null'], maxLength: 64}
        title: {type: string, minLength: 1, maxLength: 128}
        subtitle: {type: [string, 'null'], maxLength: 256}
        description: {type: string, maxLength: 5000}
        categoryId: {type: [string, 'null'], maxLength: 64}
        tags:
          type: array
          maxItems: 20
          uniqueItems: true
          items: {type: string, minLength: 1, maxLength: 64}
        coverUrl: {type: [string, 'null'], format: uri}
        bannerUrl: {type: [string, 'null'], format: uri}
        previewVideoUrl: {type: [string, 'null'], format: uri}
        status: {$ref: '#/components/schemas/MarketplaceTemplateStatus'}
        currentStableReleaseId:
          oneOf:
            - {$ref: '#/components/schemas/MarketplaceTemplateReleaseId'}
            - {type: 'null'}
        isFeatured: {type: boolean}
        sortOrder: {type: integer, minimum: 0}
        createdAt: {type: string, format: date-time}
        updatedAt: {type: string, format: date-time}
        stableSpec:
          description: >
            当前稳定 Release 的结构化规格。仅公开目录（GET /marketplace/templates 及详情里的 template）
            返回；Release 的清单快照不可解析、清单未声明入口的 render 配置，或取值不合法时为 null。管理接口不填充。
          oneOf:
            - {$ref: '#/components/schemas/MarketplaceReleaseSpec'}
            - {type: 'null'}
        stableFields:
          description: >
            当前稳定 Release 面向用户的字段提示，供目录卡片判断「是否需要技术支持」。
            仅公开目录返回。网关无法解析输入快照、输入快照不是对象，或某个属性名为空或超过 128 个字符时为 null；
            没有属性时为空数组。是否需要技术支持由消费方判定。
          type: [array, 'null']
          items: {$ref: '#/components/schemas/MarketplaceFieldHint'}
    MarketplaceReleaseSpec:
      type: object
      additionalProperties: false
      description: >
        Release 入口的结构化规格，取自发布时冻结的 manifest 快照里该入口的 render 配置。
        durationSeconds 是默认内容下的成片时长；时长随变量素材变化的模板以实际输出为准。
        它描述该 Release 的默认输出，不代表用户改过输出设置后的结果。
      required: [durationSeconds, width, height, fps]
      properties:
        durationSeconds: {type: number, exclusiveMinimum: 0}
        width: {type: integer, minimum: 1}
        height: {type: integer, minimum: 1}
        fps: {type: integer, enum: [24, 30, 60]}
    MarketplaceFieldHint:
      type: object
      additionalProperties: false
      description: >
        面向用户的字段提示：只含判定「是否需要技术支持」所需的 key、类型、控件与兼容标记，
        不含标签与取值约束。网关只读取并透传，不做归类。
      required: [key, hidden, unresolved]
      properties:
        key: {type: string, minLength: 1, maxLength: 128}
        types:
          description: JSON Schema 属性声明的 type；未声明时为 null。
          type: [array, 'null']
          items: {type: string, maxLength: 32}
        control:
          description: 控件。先取 UI metadata（x-massrender-ui）里声明的控件，没有时取属性定义上的 control；都没有时为 null。
          type: [string, 'null']
          maxLength: 32
        hidden:
          description: 仅为兼容旧输入保留的字段；不计入面向用户的可改项。
          type: boolean
        unresolved:
          description: 属性经由 $ref 或组合关键字定义，未解析前无法判断是否结构化字段。
          type: boolean
    PublicMarketplaceTemplateRelease:
      type: object
      additionalProperties: false
      required:
        - id
        - templateId
        - releaseNumber
        - engineType
        - engineVersion
        - entryId
        - inputSchemaSnapshotJson
        - defaultsSnapshotJson
        - compatibility
        - createdAt
      properties:
        id: {$ref: '#/components/schemas/MarketplaceTemplateReleaseId'}
        templateId: {$ref: '#/components/schemas/MarketplaceTemplateId'}
        releaseNumber: {type: integer, minimum: 1}
        semanticVersion: {type: [string, 'null'], maxLength: 64}
        engineType:
          type: string
          enum: [remotion, hyperframes, html-video]
        engineVersion: {type: string, minLength: 1, maxLength: 64}
        entryId: {type: string, minLength: 1, maxLength: 128}
        inputSchemaSnapshotJson: {type: object, additionalProperties: true}
        defaultsSnapshotJson: {type: object, additionalProperties: true}
        spec:
          description: >
            入口的结构化规格。清单未声明入口的 render 配置，或取值不合法时为 null，消费方应如实展示
            「未提供」，不得从示例视频或说明文字反推。
          oneOf:
            - {$ref: '#/components/schemas/MarketplaceReleaseSpec'}
            - {type: 'null'}
        compatibility: {$ref: '#/components/schemas/MarketplaceCompatibility'}
        publishedAt: {type: [string, 'null'], format: date-time}
        createdAt: {type: string, format: date-time}
    TempAssetId:
      type: string
      pattern: '^ta_[0-9a-f]{32}$'
      description: 临时素材 ID，服务端生成，不可预测。
    TempAssetQuota:
      type: object
      additionalProperties: false
      required: [usedBytes, quotaBytes, remainingBytes, assetCount]
      description: 按租户计的临时素材配额快照（字节）。
      properties:
        usedBytes: {type: integer, minimum: 0}
        quotaBytes: {type: integer, minimum: 0}
        remainingBytes: {type: integer, minimum: 0}
        assetCount: {type: integer, minimum: 0}
    TempAssetUploadToken:
      type: object
      additionalProperties: false
      required: [assetId, tenantRef, fileName, objectKey, uploadUrl, urlExpiresAt, url]
      description: 直传 OSS 的预签名 PUT 凭证（大文件绕过服务端 HTTP body 上限）。
      properties:
        assetId: {$ref: '#/components/schemas/TempAssetId'}
        tenantRef: {type: string, minLength: 3, maxLength: 128}
        fileName: {type: string, minLength: 1, maxLength: 128}
        objectKey: {type: string, minLength: 1}
        uploadUrl:
          type: string
          description: 预签名 PUT URL，客户端把原始字节直接 PUT 到这里（只对该对象有效，限时）。
        urlExpiresAt: {type: string, format: date-time}
        url:
          type: string
          description: 内网 oss:// 链接（上传完成后可回传 ffmpeg/渲染消费）。
          pattern: '^oss://[a-z0-9][a-z0-9.-]*/[A-Za-z0-9._~!$&''()*+,;=:@%/-]+$'
    TempAsset:
      type: object
      additionalProperties: false
      required: [assetId, tenantRef, fileName, sizeBytes, url, objectKey, createdAt, expiresAt]
      description: 临时素材元数据。url 为内网 oss:// 链接，仅供 ffmpeg 输入 / 渲染变量回传。
      properties:
        assetId: {$ref: '#/components/schemas/TempAssetId'}
        tenantRef: {type: string, minLength: 3, maxLength: 128}
        fileName: {type: string, minLength: 1, maxLength: 128}
        sizeBytes: {type: integer, minimum: 1}
        contentType: {type: string}
        sha256:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: 素材内容 SHA-256（hex）。
        url:
          type: string
          description: 内网 oss:// 链接。仅供消费凭证回传（ffmpeg 输入 / 渲染变量），客户浏览器不可直接访问。
          pattern: '^oss://[a-z0-9][a-z0-9.-]*/[A-Za-z0-9._~!$&''()*+,;=:@%/-]+$'
        objectKey: {type: string, minLength: 1}
        createdAt: {type: string, format: date-time}
        expiresAt: {type: string, format: date-time}
    TempAssetWithQuota:
      type: object
      additionalProperties: false
      required: [assetId, tenantRef, fileName, sizeBytes, url, objectKey, createdAt, expiresAt, quota]
      description: |
        完整的临时素材元数据 + 配额快照。render 内部响应（toTempAssetResponse）给每个
        素材都带上当前配额，ff-server 原样透传，故 list 每项与上传响应均为该形状。
      properties:
        assetId: {$ref: '#/components/schemas/TempAssetId'}
        tenantRef: {type: string, minLength: 3, maxLength: 128}
        fileName: {type: string, minLength: 1, maxLength: 128}
        sizeBytes: {type: integer, minimum: 1}
        contentType: {type: string}
        sha256: {type: string, pattern: '^[a-f0-9]{64}$'}
        url:
          type: string
          description: 内网 oss:// 链接。仅供消费凭证回传（ffmpeg 输入 / 渲染变量）。
          pattern: '^oss://[a-z0-9][a-z0-9.-]*/[A-Za-z0-9._~!$&''()*+,;=:@%/-]+$'
        objectKey: {type: string, minLength: 1}
        createdAt: {type: string, format: date-time}
        expiresAt: {type: string, format: date-time}
        quota: {$ref: '#/components/schemas/TempAssetQuota'}
    TempAssetUploadResult:
      $ref: '#/components/schemas/TempAssetWithQuota'
    TempAssetListResult:
      type: object
      additionalProperties: false
      required: [tenantRef, quota, assets]
      description: 列出租户未过期素材 + 配额快照。每项素材均携带当前配额（与上传响应同形状）。
      properties:
        tenantRef: {type: string, minLength: 3, maxLength: 128}
        quota: {$ref: '#/components/schemas/TempAssetQuota'}
        assets:
          type: array
          items: {$ref: '#/components/schemas/TempAssetWithQuota'}
    TempAssetQuotaResult:
      type: object
      additionalProperties: false
      required: [tenantRef, quota]
      properties:
        tenantRef: {type: string, minLength: 3, maxLength: 128}
        quota: {$ref: '#/components/schemas/TempAssetQuota'}
    TempAssetDeleteResult:
      type: object
      additionalProperties: false
      required: [deleted, tenantRef, quota]
      properties:
        deleted: {const: true}
        tenantRef: {type: string, minLength: 3, maxLength: 128}
        quota: {$ref: '#/components/schemas/TempAssetQuota'}
    TempAssetErrorResponse:
      type: object
      additionalProperties: false
      description: |
        临时素材端点的错误响应体：{error, tenantRef}。ff-server 透传 render 内部
        /internal/v1/temp-assets 的错误体（含 tenantRef），不是通用 ErrorResponse
        （后者要求 {error, requestId, traceId}）；租户头缺失/非法时 tenantRef 为空串。
      required: [error, tenantRef]
      properties:
        error:
          type: object
          additionalProperties: false
          required: [code, message, retryable]
          properties:
            code:
              type: string
              enum: [VALIDATION_ERROR, TEMP_ASSET_QUOTA_EXCEEDED, TEMP_ASSET_FILE_TOO_LARGE, TEMP_ASSET_NOT_FOUND]
            message: {type: string}
            retryable: {const: false}
        tenantRef:
          type: string
          maxLength: 128
          description: 请求上下文租户；缺失/非法租户头（VALIDATION_ERROR）时为空字符串。
    TempAssetUploadBusyError:
      type: object
      additionalProperties: false
      description: |
        429 租户并发上传超限的专用错误包：retryable 为 true（与其余 temp-asset 4xx 不同），
        客户端应据此重试（带退避），不能与共享 TempAssetErrorResponse 的 retryable:false 混用。
      required: [error, tenantRef]
      properties:
        error:
          type: object
          additionalProperties: false
          required: [code, message, retryable]
          properties:
            code: {const: TEMP_ASSET_UPLOAD_BUSY}
            message: {type: string}
            retryable: {const: true}
        tenantRef:
          type: string
          maxLength: 128
    FfmpegTaskId:
      type: string
      pattern: '^ffmpeg-[A-Za-z0-9-]{8,64}$'
      description: FFmpeg 任务 ID，由服务端生成（UUID 派生）。
    CreateFfmpegTaskRequest:
      type: object
      required: [inputs, commands, mode, profile]
      description: |
        RFC 0003 POST /ffmpeg-tasks 请求体。ff-server 原样转发到 Render 服务。
        字段约束：inputs 1-16 条、commands MVP 仅支持单命令（长度 1，每条 1-1000 参数）。
        mode=ffmpeg 时 output 必填（且 commands 最后一个参数须等于 output.fileName）；
        mode=ffprobe 时不接受 output。安全模型：ffmpeg 永不直连网络，
        输入由服务端 fetch 到受控存储；命令参数经从严白名单校验。
      if:
        properties:
          mode:
            const: ffmpeg
      then:
        required: [output]
      properties:
        inputs:
          type: object
          propertyNames: {pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$'}
          additionalProperties:
            type: string
            maxLength: 2048
            anyOf:
              - {type: string, format: uri, pattern: '^https?://', description: '外部公网 URL（服务端 fetch 到受控存储）'}
              - {type: string, pattern: '^oss://[a-z0-9][a-z0-9.-]*/[A-Za-z0-9._~!$&''()*+,;=:@%/-]+$', description: '临时素材内网 oss:// 链接（POST /temp-assets 上传返回），服务端直接下载到受控存储'}
          minProperties: 1
          maxProperties: 16
          description: 逻辑输入文件名 → 外部来源 URL 或临时素材内网 oss:// 链接。键名须为 1-128 字符的字母/数字/._-（以字母数字开头）；http(s) 公网 URL 由服务端 fetch 到受控存储，oss:// 临时素材链接由服务端用 OSS SDK 下载，ffmpeg 永不直连网络。
        commands:
          type: array
          minItems: 1
          maxItems: 1
          description: MVP 只支持单命令（数组长度 1），每条命令 1-1000 个参数。
          items:
            type: array
            minItems: 1
            maxItems: 1000
            items: {type: string, minLength: 1}
        output:
          $ref: '#/components/schemas/FfmpegTaskOutputRef'
        mode:
          type: string
          enum: [ffmpeg, ffprobe]
          description: 'ffmpeg=转码/处理（output 必填），ffprobe=媒体信息查询（无 output）。'
        profile:
          type: string
          enum: [standard]
          description: '规格档位；当前仅 standard 已部署（2 vCPU / 3GB / 600s）。highmem/gpu 暂未上线。'
        callbackUrl:
          type: string
          format: uri
          maxLength: 2048
          pattern: '^https?:'
          description: 可选异步回调（任务进入终态时 Render POST 到该 URL）；必须为 http(s)。
    FfmpegTaskOutputRef:
      type: object
      required: [fileName]
      description: 输出文件名声明（mode=ffmpeg 必填）。服务端强制 key 为 ffmpeg-tasks/{taskId}/{fileName}。
      properties:
        fileName:
          type: string
          minLength: 1
          maxLength: 128
          pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.(mp4|mov|webm|mkv|m4a|aac|mp3|wav|flac|ogg|gif|jpg|jpeg|png)$'
          description: 输出文件名（1-128 字符，字母/数字/._-，以字母数字开头）。扩展名必须在白名单内：mp4/mov/webm/mkv/m4a/aac/mp3/wav/flac/ogg/gif/jpg/jpeg/png。
    FfmpegTask:
      type: object
      required: [taskId, status]
      description: FFmpeg 任务状态快照（GET 响应）。独立任务在网关结算后附带金额，prepare 子任务由父任务结算。
      properties:
        taskId: {$ref: '#/components/schemas/FfmpegTaskId'}
        mode: {type: string, enum: [ffmpeg, ffprobe]}
        tenantRef: {type: string}
        parentRenderId: {type: string, description: prepare 派生任务的父任务 ID。}
        usage:
          type: object
          required: [executeDurationMs, meters]
          description: 成功 FFmpeg 进程的实际执行用量；不含排队、下载、上传及探测。ffprobe、失败和旧任务可缺省。
          properties:
            executeDurationMs: {type: integer, minimum: 0}
            meters:
              type: object
              required: [ffmpeg.executeSeconds]
              properties:
                ffmpeg.executeSeconds: {type: number, minimum: 0.1, description: 执行秒数，每次向上取整至 100ms。}
        costFen: {type: integer, format: int64, minimum: 0, description: 独立任务已结算金额（分）；尚未结算时缺省。}
        costItems:
          type: array
          description: 独立任务的已结算计费明细。
          items: {$ref: '#/components/schemas/RenderCostItem'}
        status:
          type: string
          enum: [queued, running, completed, failed, unknown]
        finalUrl:
          type: [string, 'null']
          description: 内部 oss:// 引用（客户端应使用 finalHttpUrl）。
        finalHttpUrl:
          type: [string, 'null']
          format: uri
          description: 7 天有效的 OSS 签名下载 URL（completed 且 mode=ffmpeg 时存在）。
        output:
          $ref: '#/components/schemas/FfmpegTaskOutput'
        probeResult:
          type: [object, 'null']
          additionalProperties: true
          description: ffprobe JSON 结果（mode=ffprobe 且 completed 时存在）。
        error:
          type: [string, 'null']
        errorCode:
          type: [string, 'null']
          description: '任务级错误码：FFMPEG_TIMEOUT / FFMPEG_INPUT_FETCH_FAILED / FFMPEG_EXEC_FAILED / FFMPEG_OUTPUT_OVER_LIMIT 等。'
        createdAt: {type: string, format: date-time}
        updatedAt: {type: string, format: date-time}
    FfmpegTaskOutput:
      type: object
      description: 转码产物元数据（mode=ffmpeg 且 completed 时存在）。
      properties:
        objectKey: {type: string}
        sizeInBytes: {type: integer, format: int64}
        durationSeconds: {type: [number, 'null']}
        width: {type: [integer, 'null']}
        height: {type: [integer, 'null']}
        codec: {type: [string, 'null']}
````

