openapi: 3.1.0

# Tare —— 对外接口描述文件
#
# ⚠️ 这份是**手工维护**的，覆盖范围严格限定为对客户开放的那几组接口。
#    服务自身用 springdoc 生成的那一份（/v3/api-docs）**不对外提供**：它会把控制台、
#    运营、健康检查等内部接口一并暴露，而那些不是对外契约，也不在网关上开放。
#    改了对外接口就要改这里，判据很简单：**docs/tare 那份文档里出现的接口，这里必须有。**
#
# ⚠️ **控制台接口不在这份文件里**（渠道、路由、进价、告警那些走登录态）。
#    进价上的 `recorded_at`（「这个价什么时候录的」）属于控制台那一片，说明在
#    https://www.jamerly.ai/docs/tare 的「进价」一节。要用 key 认证读它，需要先把它加进
#    /v1/integration 的白名单，再补进这份文件。
#
# ⚠️ 两种响应形状：
#    · 模型端点与 key/models/generation 这几组是 **OpenAI/OpenRouter 形状**，
#      错误体是 {"error":{...}}；
#    · /v1/integration/* 是 **ApiResponse 形状** {"code","message","data","success"}，
#      因为它的调用方是 ERP 和财务系统，那套形状是当初就定下的对外契约。
#    合并成一种会破坏其中一边已经写死的客户端。

info:
  title: Tare API
  version: '2026-11-26.1'
  summary: 一个 OpenAI 兼容的模型网关，外加子钥签发与对账接口
  # ⚠️ 上面那个链接要写成 markdown 形式，不能用裸 URL：裸 URL 后面紧跟中文括号时，
  #    渲染器的自动链接会把后面的中文一起吃进地址里，点出去是 404。
  description: |
    完整的说明性文档在 [www.jamerly.ai/docs/tare](https://www.jamerly.ai/docs/tare)（中英双语）。
    ⚠️ `2026-11-26.1`：新增决策接口 `POST /v1/decisions`（同一个接口也挂在 Jev 的路径名
    `POST /v1/systemone` 上）：一段文本 + 若干个问题，回每个答案的概率（是非 / 单选 / 打分）。
    线格式与 TypeSafe Jev、OpenRouter Decisions 相同。都是新增，已有接口不变。
    ⚠️ `2026-11-23.1`：子钥按天的用量。`Key` 新增 `usage_daily`（今天）、`usage_weekly`（本周，
    周一起）、`usage_monthly`（本月，1 号起）三个字段，与 OpenRouter `GET /api/v1/key` 同名；
    按账期时区切天，清零不影响。新增 `GET /v1/keys/usage/daily`（账号下全部子钥）、
    `GET /v1/keys/{hash}/usage/daily`、`GET /v1/keys/external/{externalId}/usage/daily`，
    每行是一把 key 一天（可再按模型拆）的花费、请求数和 token 数。都是新增，已有字段不变。
    ⚠️ `2026-11-20.1`：新增**管理钥**（`keyType: management`，在控制台创建）与 `/v1/manage/*`：
    用一把 key 配渠道（`/v1/manage/providers`）、路由（`/v1/manage/routers`）和 DLP
    （`/v1/manage/dlp`），处理器与控制台同一份，响应是 ApiResponse 形状。管理钥只能调这一组，
    别的 key 和控制台会话都调不了这一组；渠道试聊（`/providers/{id}/chat`）对管理钥关闭。
    DLP 新增客户自定义规则（`/v1/manage/dlp/rules*`）与能力目录（`/v1/manage/dlp/capabilities`），
    以及 10 种台湾 / 菲律宾证件号内置类型。已有接口行为不变。
    ⚠️ `2026-11-10.1`：子钥额度可以清零。新增 `POST /v1/keys/{hash}/reset` 与
    `POST /v1/keys/external/{externalId}/reset`（立刻清零），创建和修改子钥时新增
    `limit_reset`（`daily` / `weekly` / `monthly`，按 UTC 自动清零，与 OpenRouter 同名同义）。
    `Key` 新增 `limit_reset`、`limit_usage`、`limit_reset_at` 三个字段，`limit_remaining`
    改为按 `limit_usage` 计算。从没清零过的 key，`limit_usage` 等于 `usage`，返回值和以前一样。
    ⚠️ `2026-09-28.1`：又是补文档不是补功能——`/v1/images`、`/v1/images/generations`
    这两个路径此前完全没在这份契约文件里出现过（服务端早就有）；顺带把 `/v1/embeddings`
    的请求体补上 `models`/`provider` 两个字段（早已生效，只是没写）。**接口行为本身
    没有任何变化。**
    ⚠️ `2026-09-27.2`：补文档，不是补功能——`/v1/videos/generations`（异步视频生成）
    和 `/v1/mocks/*`（演习失败场景）在服务端已经上线一段时间，这次才第一次写进这份
    契约文件。**接口行为本身没有任何变化。** 顺手修正了下方「两种响应形状」表格里的一处
    不准确：`/v1/mocks/*` 走的是 ApiResponse 信封，不是只有 `/v1/integration/*` 才用它。
    ⚠️ `2026-09-27.1`：`/v1/chat/completions` 新增 `models`（备用模型链）与 `provider`
    （按次路由偏好）两个请求字段，`GET /v1/generation` 新增 `latency`/`generation_time`/
    `routing_overhead_ms`/`time_to_first_token_ms` 四个耗时字段。**都是新增字段，
    不改任何已有形状**——不传就是今天的行为。

    ⚠️ `2026-09-01.1`：新增「来源 IP 白名单」（见下方鉴权一节与 `refusal_reason`
    的 `source_ip_not_allowed`）。**这是账号侧的开关，不改任何接口形状** —— 没开的
    key 行为一个字节都没变。

    ⚠️ `2026-08-22.4`：`.3` 曾以**缺两段**的形式发布过（chat 端点与
    `Generation.upstream_inference_cost` 关于「转售不返回上游成本」的说明在发布流程中
    丢失）。行为本身从 0.1.13 起就是这样，丢的只是文字。拿过 `.3` 的话请重新拉一份。

    这份文件只描述
    接口形状，**不重复文档里的那些判断依据**（为什么额度用尽是 403、为什么流式末帧
    两种方言不一致等等）——接入前请两份一起读。

    ## 鉴权

    全部接口都用 `Authorization: Bearer <key>`。三类 key 权限互不重叠，用错类型返回明确的
    拒绝，而不是含糊的 401：

    | key | 能做什么 |
    |---|---|
    | 推理 key | 调模型（`/v1/chat/completions`、`/v1/embeddings`、`/v1/models`、`/v1/generation`） |
    | 母钥 | 管子钥（`/v1/keys/*`），**不能调模型** |
    | 对账 key | 读账（`/v1/integration/*`），**不能调模型** |

    ### 来源 IP 白名单（可选）

    每一把 key 都可以限定「只许从这些地址调用」（控制台 → API Keys → 编辑那把 key）。
    名单外的调用返回 `403` + `metadata.refusal_reason = source_ip_not_allowed`，
    **key 本身仍然有效** —— 这不是吊销，换一台在名单上的机器就能用。

    ⚠️ 要填的是**你的服务器出网的那个地址**，不是内网地址，也不是你打开控制台那台
    电脑的地址（两者通常不同）。控制台上会显示「我们看到这台浏览器是 X」，那只是一个
    参照，不要直接把它填进去。

    ⚠️ 名单区分 IPv4 和 IPv6：填了 `203.0.113.7` 而你的机器某天走 IPv6 出网，同样会被
    拒。两种都可能用到的话，两个段都加。

    ⚠️ 关掉这道闸和清空名单是两件事。**开着而名单为空 = 全部拒绝**，不是全部放行。

    ## 请求头

    除了 `Authorization`（和流式的 `Accept: text/event-stream`），**不要求任何请求头**。

    ⚠️ **未识别的请求头一律忽略，不会因此拒绝请求，也不会转发给上游。** 发往上游的请求头
    由我们重建（凭据、`Content-Type`、方言要求的那几个），**你带的头不会出现在上游那一侧**。
    OpenRouter 的归因头 `HTTP-Referer` / `X-Title` 属于这一类：带上无害，但不会到达任何
    地方，也不影响路由、计费和限流。

    归因请改用 `usage_label`（请求体内，原样落进用量记录）和子钥本身。

    ## 时间与时区

    所有时间戳都是 ISO 8601。⚠️ **不带偏移量的那些（`2026-08-21T17:30:00`）按
    `Asia/Shanghai`（UTC+8）解释** —— 它们是服务端本地时间。账期也按这个时区切，
    `/v1/integration/whoami` 会返回当时使用的时区，**以该字段为准，不要硬编码**。

    ## 两种响应形状

    | 接口 | 形状 | 失败时 |
    |---|---|---|
    | `/v1/chat/completions`、`/v1/embeddings`、`/v1/images*`、`/v1/keys/*`、`/v1/models`、`/v1/generation`、`/v1/videos/generations*` | OpenAI：`{"error":{...}}` | **HTTP 非 2xx** |
    | `/v1/integration/*`、`/v1/mocks/*` | ApiResponse：`{"code","message","data","success"}` | **HTTP 非 2xx，body 仍是 ApiResponse**（不是 200 + success:false） |
  contact:
    name: Jamerly
    url: https://www.jamerly.ai/docs/tare
  license:
    # ⚠️ 这不是开源产物，别为了消掉 linter 的警告硬套一个 MIT 之类的许可 ——
    # 那会让拿到文件的人以为接口实现也是开源的。
    name: Proprietary — provided to Jamerly customers under contract
    url: https://www.jamerly.ai/docs/tare

servers:
  - url: https://tare.jamerly.ai/v1
    description: 生产

security:
  - bearerAuth: []

tags:
  - name: Chat
    description: OpenAI 兼容的模型端点
  - name: Video
    description: 异步视频生成——提交任务、轮询状态
  - name: Keys
    description: 母钥签发与管理子钥
  - name: Catalog
    description: 模型目录与单次调用回查
  - name: Content
    description: 调用内容的留存开关与查看授权（ApiResponse 形状）
  - name: Mock
    description: 演习失败场景——不打上游，直接按剧本返回（ApiResponse 形状）
  - name: Reconciliation
    description: 给机器用的账务接口（ApiResponse 形状）
  - name: Manage
    description: 管理钥配置渠道、路由与 DLP（ApiResponse 形状）

paths:

  /chat/completions:
    post:
      tags: [Chat]
      operationId: createChatCompletion
      summary: 发起一次模型调用（OpenAI 兼容）
      description: |
        请求体**原样透传**：未识别的字段照发给上游，这是 `cache_control`、`reasoning`、
        `plugins` 这类字段能工作的原因。我们只改动四处：模型名换成上游认的、`stream`
        固定为本次尝试的模式、流式强制 `stream_options.include_usage=true`、剥除归因字段。

        ⚠️ **`models`、`provider` 是例外——它们被我们消费掉，不转发给上游。**
        原样转发的话，OpenRouter 自己也认识这两个字段名，会拿我们内部的模型名/渠道名
        去做**它自己的**一轮转移/过滤（2026-09-27 实测过这个事故），所以这两个和
        `cache_control` 那类「未识别就透传」的字段不是一回事。

        - **`models`**（字符串数组）：备用模型链。`model` 全不可用（没配路由，或配了但
          候选全部熔断/耗尽）时依次退到这里的第一个，那个也不行再往下一个。`model`
          仍然必填、永远第一优先级，这个数组只在它失败之后才生效。
        - **`provider`**（对象）：按次路由偏好，只影响「这次能打哪几家」，不改
          「打不通了怎么办」。字段：`order`（string[]，按这个顺序优先尝试的渠道名）、
          `only`（string[]，白名单）、`ignore`（string[]，黑名单）、`allow_fallbacks`
          （boolean，默认 true；false 时只用 `order`/`only` 点到的渠道，一个都打不通
          就失败）、`sort`（目前只认 `"latency"`，按实测平均延迟从快到慢重排；
          `"price"`/`"throughput"` 会被当成没传，不报错）。`only`/`ignore`/`order`
          过滤完一条候选都不剩时是 `400`，不是 `404`——那是你的偏好写错了，不是模型
          没配置。

        ⚠️ **`usage.cost` 是「花了你多少」。** 走平台渠道（token 的钱由我们垫）时，回包中
        **不含 `usage.cost_details`** —— 那一格是上游向我们收取的金额。BYOK 下保留：
        那是你自己上游账单上的钱，也正是成本归因需要的数据。
        （2026-08-22 之前两种模式都返回了；已修。）
        算不出来时 `cost` 整格不出现，而不是 0 —— 「该模型尚未定价」也算算不出来。

        ⚠️ **两种上游方言的流式末帧形状不一致**（OpenAI 兼容是 `choices: []`，Anthropic 是
        `choices` 有一项而 `delta` 为空）。按帧渲染时判据写成「`choices` 为空 **或** delta
        无内容 → 跳过渲染，只取 `usage`」。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model, messages]
              additionalProperties: true
              properties:
                model:
                  type: string
                  description: 平台侧模型名，取自 `GET /models` 的 `id`
                  examples: ['GLM 5.1']
                models:
                  type: array
                  items: { type: string }
                  description: |
                    备用模型链，按顺序尝试。`model` 全不可用时才用得上第一个，
                    详见上方说明。最多 5 个，超过的部分会被丢弃，不报错。
                  examples: [['GLM 5.1', 'GPT-5.6 Sol']]
                provider:
                  type: object
                  description: 按次路由偏好，详见上方说明
                  properties:
                    order:
                      type: array
                      items: { type: string }
                      description: 按这个顺序优先尝试的渠道名（大小写不敏感）
                    allow_fallbacks:
                      type: boolean
                      default: true
                      description: false 时只用 `order`/`only` 点到的渠道
                    only:
                      type: array
                      items: { type: string }
                      description: 白名单：只用这些渠道
                    ignore:
                      type: array
                      items: { type: string }
                      description: 黑名单：不用这些渠道
                    sort:
                      type: string
                      description: 目前只认 `latency`；`price`/`throughput` 当没传，不报错
                      examples: ['latency']
                messages:
                  type: array
                  items:
                    type: object
                    required: [role]
                    properties:
                      role: { type: string, enum: [system, user, assistant, tool] }
                      content: {}
                stream: { type: boolean, default: false }
                max_tokens: { type: integer }
                temperature: { type: number }
                usage_label:
                  type: string
                  description: 你自己的归因标签，会原样落进用量记录，基数不设上限
      responses:
        '200':
          description: |
            成功。非流式返回一个 completion 对象；`stream: true` 时是 SSE
            （`text/event-stream`），以 `data: [DONE]` 结束。
          headers:
            X-Generation-Id:
              description: 本次调用的对外编号，`gen-` 开头；用它回查成本
              schema: { type: string }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ChatCompletion' }
            text/event-stream:
              schema:
                type: string
                description: "每行一个 `data: {chunk}`，末帧带 `usage`"
        '400':
          description: |
            请求本身有问题——包括 `provider` 里的 `only`/`ignore`/`order` 把候选过滤到
            一条都不剩（错误信息里会列出这个模型实际配置了哪些渠道）。和「模型没配置」
            （`404`）是两回事：改偏好就行，不用去查路由配置。
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/OpenAIError' }
        '402':
          description: |
            **账号欠费，且只有这一种含义。** 额度用尽是 403，不在这里。
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: |
            凭据有效，但这次不许过。三类：key 的累计额度用尽、账号月度预算到顶、
            **调用来源不在这把 key 的 IP 白名单上**。
            按 `metadata.refusal_reason` 区分，见该字段的说明。
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: |
            **这个模型没有配置路由**（不是余额问题）。改模型名、加一条路由，或配一条兜底。
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429':
          description: 超过每分钟请求数
          headers:
            Retry-After:
              description: 建议等待的秒数
              schema: { type: integer }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: 有路由，但候选渠道全在失败。**重试即可，这不是配置问题。**
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /embeddings:
    post:
      tags: [Chat]
      operationId: createEmbedding
      summary: 把文本转成向量（OpenAI 兼容）
      description: |
        请求体**原样透传**（`models`、`provider` 除外，见下），回包是**上游原文**加一格
        `usage.cost`。

        ⚠️ **模型名不做映射。** chat 那边写的是我们这边的模型名（取自 `GET /models`），
        这里写的是**上游自己的名字**（`text-embedding-3-small` 这一类）——
        embeddings 不走模型路由表，所以没有那层映射，回包里的模型名同样不改写。

        ⚠️ **打到哪条渠道：你自己的渠道优先（显式配的 > 按方言推出来的），
        都没有才走平台那条被指定的渠道。**
        两者的计费不同（自己的渠道只记账，平台渠道按售价扣余额），所以**不会**在两者
        之间自动故障转移 —— 一次静默的回退等于在你没同意的情况下开始花钱。
        **自己的渠道之间会**互相故障转移（计费模式一样，换一条不改变你付多少）。

        ⚠️ **`models`、`provider` 也在这里生效，但 `models` 的含义和 chat 不完全一样。**
        embeddings 没有路由表可以映射，所以 `models` 里的名字是**另一个上游原始模型名**，
        不是平台名字——外层按这条链换名字，每换一个都要把你全部自有渠道重新试一轮，
        等这一个模型名在所有渠道上都失败了才换下一个。`provider` 的行为和 chat 完全一样：
        只调整/过滤**你自己**渠道的顺序，不会把平台渠道拉进来。两者都会在转发前被剥掉，
        原因见 `/chat/completions` 上的同一条说明。

        没有流式。`gen-` 编号走响应头，用法和 chat 一致。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model, input]
              additionalProperties: true
              properties:
                model:
                  type: string
                  description: |
                    **上游的模型名**（不是 `GET /models` 里的 `id`）。
                    ⚠️ embedding 模型**不会出现在 `GET /models`** —— 那份目录来自上游的
                    模型目录，而上游的目录里没有 embedding 模型。请按上游文档写。
                  examples: ['text-embedding-3-small']
                models:
                  type: array
                  items: { type: string }
                  description: |
                    备用**上游模型名**链（不是平台名字，见上方说明）。最多 5 个。
                  examples: [['text-embedding-3-small', 'text-embedding-3-large']]
                provider:
                  type: object
                  description: 按次路由偏好，字段和语义与 `/chat/completions` 的 `provider` 相同
                  properties:
                    order: { type: array, items: { type: string } }
                    allow_fallbacks: { type: boolean, default: true }
                    only: { type: array, items: { type: string } }
                    ignore: { type: array, items: { type: string } }
                    sort: { type: string, examples: ['latency'] }
                input:
                  description: 字符串或字符串数组
                  oneOf:
                    - { type: string }
                    - { type: array, items: { type: string } }
                dimensions: { type: integer }
                encoding_format: { type: string, enum: [float, base64] }
                usage_label:
                  type: string
                  description: 你自己的归因标签，会原样落进用量记录
      responses:
        '200':
          description: OK
          headers:
            X-Generation-Id:
              description: 本次调用的对外编号，`gen-` 开头
              schema: { type: string }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmbeddingList' }
        '400': { $ref: '#/components/responses/OpenAIError' }
        '401': { $ref: '#/components/responses/OpenAIError' }
        '402': { $ref: '#/components/responses/OpenAIError' }
        '403': { $ref: '#/components/responses/OpenAIError' }
        '404':
          description: |
            **一条能做 embeddings 的渠道都没有。** 这是配置问题，改模型名没有用 ——
            配一条 OpenAI 兼容的渠道，或者让我方给你的账号打开平台渠道。
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '502': { $ref: '#/components/responses/OpenAIError' }

  /images:
    post:
      tags: [Chat]
      operationId: createImage
      summary: 图片生成（OpenAI 兼容）
      description: |
        `POST /images/generations` 是同一个接口——请求和回包完全一样，两个路径都通。

        路由按模型名，和 `/chat/completions` 同一套：故障转移、`models` 备用链、`provider`
        按次路由偏好都一样生效（三个字段的语义见 `/chat/completions` 上的说明，`models`/
        `provider` 同样会被剥掉、不转发给上游）。余额/预算/key 额度三道门禁在**每一个候选**
        上都会查一遍，不只是第一个——两条候选可能计费方式不同（自己的渠道 vs 平台渠道），
        静默换到第二条又不重新检查等于在客户没同意的情况下开始花钱。

        除具名字段外，其余字段（`size`、`aspect_ratio`、`n`、`input_references`、供应商私有
        参数）原样转发给上游；上游不认的字段会返回**上游自己的**报错，不是这边的。

        ⚠️ **`data` 可以是空数组，这不是错误。** 模型可能只回文字、或者被上游自己的内容
        策略拦下——两种都是 `200`，原因写在 `finish_reason`/`text` 里，不会被重新分类成失败。

        ⚠️ **不要把 `url` 存进你自己的数据库。** 它 24 小时后失效，在失效之前和永久链接
        没有区别。要长期保存请存 `b64_json`，或者把字节复制到你自己的存储。

        无流式。
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ImageGenerationRequest' }
      responses:
        '200':
          description: OK
          headers:
            X-Generation-Id:
              description: 本次调用的对外编号，`gen-` 开头
              schema: { type: string }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ImageGeneration' }
        '400':
          description: 请求本身有问题，含 `provider` 把候选过滤到一条都不剩
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/OpenAIError' }
        '402': { $ref: '#/components/responses/OpenAIError' }
        '403': { $ref: '#/components/responses/OpenAIError' }
        '404':
          description: 这个模型没有配置路由
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: 有路由，但候选渠道全在失败
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /images/generations:
    post:
      tags: [Chat]
      operationId: createImageAlias
      summary: 与 `POST /images` 完全相同的接口，另一个常见名字
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ImageGenerationRequest' }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ImageGeneration' }
        '400': { $ref: '#/components/responses/OpenAIError' }
        '401': { $ref: '#/components/responses/OpenAIError' }
        '404': { $ref: '#/components/responses/OpenAIError' }

  /models:
    get:
      tags: [Catalog]
      operationId: listModels
      summary: 这个账号能用的模型和价格
      description: |
        **带上推理 key，目录里就包含你自己配的模型**：你在自己渠道上配的那些 ∪ 平台的那些，
        同名时以你自己那条为准 —— 和真正调用时的路由口径完全一致。

        **凭据是可选的**：不带任何请求头时返回平台目录（客户端确实这么用，这条路一直保留）。
        但带了就必须是真的 —— 无效或过期的 key 返回 `401`，不会静默给你一份
        「少了你自己模型」的目录。

        **推理 key 和母钥都可以**。母钥没有绑 Router，它拿到的是**账号默认那套路由**的目录；
        要看某一把绑了别的 Router 的子钥能用什么，就拿那把子钥来调。
        对账 key 返回 `403`（它碰不到模型这一片）。

        ⚠️ 你自己渠道上的模型，`pricing.prompt` / `completion` 是 `0`：那些 token 你直接付给
        上游，不经我们的价目表。真实成本读回包的 `usage.cost`。
      security:
        - bearerAuth: []
        - {}
      responses:
        '401': { $ref: '#/components/responses/OpenAIError' }
        '403': { $ref: '#/components/responses/OpenAIError' }
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Model' }

  /generation:
    get:
      tags: [Catalog]
      operationId: getGeneration
      summary: 按编号回查一次调用的真实成本
      description: |
        ⚠️ **404 是正常路径**，不是错误：用量记录在响应之后才写入。非流式通常 1 秒内可查，
        流式以流结束为准；中途断开的流需事后向上游回查，可能到分钟级。
        请把 404 当作「稍后再试」，退避几秒后重试。
      parameters:
        - name: id
          in: query
          required: true
          schema: { type: string }
          description: 响应头 `X-Generation-Id` 或回包 `id` 里的 `gen-…`
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: '#/components/schemas/Generation' }
        '404':
          description: 尚不可查（或不属于你的调用）。按「稍后再试」处理
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /videos/generations:
    post:
      tags: [Video]
      operationId: submitVideoGeneration
      summary: 提交一个异步视频生成任务
      description: |
        异步：这一步只把任务提交上去，立刻返回 `status: pending`，真正的生成是分钟级的。
        用返回的 `id` 轮询 `GET /v1/videos/generations/{id}`。

        ⚠️ **轮询不会打到上游去。** 生成进度由服务端后台统一拉取，客户端查多勤都不影响
        对上游的调用频率——这和 chat/embeddings 那种「一次请求就是一次上游调用」不一样，
        轮询本身的成本和节奏由我们控制，不是把这个决定权交给调用方的查询习惯。

        ⚠️ **`callback_url` 目前只接收、不投递。** 字段会被原样存下来，但**没有任何 webhook
        会被真正发出**——现在唯一能知道任务完成的办法是轮询。传了它不会报错，也不会在某天
        突然开始收到回调；如果你现在的代码是「传了 callback_url 就不轮询」，请改成轮询。

        `models`（备用模型链）和 `provider`（按次路由偏好，`order`/`only`/`ignore`/
        `allow_fallbacks`/`sort`）两个字段和 `/v1/chat/completions` 是同一套解析逻辑，
        语义完全一致，见该接口的说明；这里同样不会转发给上游。

        不认识的顶层字段原样收进供应商特定参数（比如某些模型要的分辨率、种子数），
        原样透传给上游，不做校验。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model, prompt]
              additionalProperties: true
              properties:
                model: { type: string, description: 取自 `GET /models` 的 `id` }
                models:
                  type: array
                  items: { type: string }
                  description: 备用模型链，语义同 `/v1/chat/completions`
                provider:
                  type: object
                  description: 按次路由偏好，语义同 `/v1/chat/completions`
                prompt: { type: string }
                duration_seconds: { type: integer }
                aspect_ratio: { type: string, examples: ['16:9'] }
                reference_image_url: { type: string }
                reference_video_url: { type: string }
                callback_url:
                  type: string
                  description: '⚠️ 目前只存不投递，见上方说明'
      responses:
        '200':
          description: 提交成功，`status` 通常是 `pending`
          content:
            application/json:
              schema: { $ref: '#/components/schemas/VideoGeneration' }
        '400': { $ref: '#/components/responses/OpenAIError' }
        '401': { $ref: '#/components/responses/OpenAIError' }
        '402': { $ref: '#/components/responses/OpenAIError' }
        '403': { $ref: '#/components/responses/OpenAIError' }
        '404':
          description: 这个模型没配路由，或者配了但这条渠道不支持视频
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: 上游暂时不可用（含上游因内容审核等原因拒绝的情况，见 `error.metadata.provider_code`）
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /videos/generations/{id}:
    get:
      tags: [Video]
      operationId: getVideoGeneration
      summary: 查询一个视频生成任务的状态
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/VideoGeneration' }
        '404':
          description: 不存在，或者不属于你（两者用同一个 404，不区分）
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /decisions:
    post:
      tags: [Chat]
      operationId: createDecision
      summary: 决策（TypeSafe Jev / OpenRouter Decisions 线格式）
      description: |
        给一段文本（或任意 JSON）和若干个按名字列出的问题，返回每个问题各个答案的**概率**，不生成文字。
        三种题型：`noul`（是非题，回 P(yes)）、`choice`（单选，回最可能的选项、每个选项的概率和 `confidence`）、
        `score`（打分，回期望档位、每档概率和 `confidence`）。同一段文本问多个问题只读一遍。

        `POST /systemone` 是同一个接口（TypeSafe Jev / Microsoft Foundry 的叫法）：用 Jev SDK 的代码改一下
        base URL 就能用。

        路由按模型名，和 `/chat/completions` 同一套客户路由 → 平台兜底与故障转移；DLP 扫 `state` 和
        每个问题的文本。按 token 计费，价目是这个模型单独的一行（只收输入，输出免费），回包
        `usage.cost` 就是这次的扣费。

        不支持 `models` 备用链和 `provider` 路由偏好，也不流式（带 `stream: true` 返回 400）。

        ⚠️ `confidence` 低的结果请交给人工，或者换更强的模型复核；概率不是规则引擎的结论——日期比较、
        金额相加这类计算请在你自己的代码里做，把结论写进问题里再问。
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/DecisionRequest' }
      responses:
        '200':
          description: OK
          headers:
            X-Generation-Id:
              description: 本次调用的对外编号，`gen-` 开头（与回包 `id` 相同）
              schema: { type: string }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Decision' }
        '400':
          description: 请求本身有问题（缺 `model` / `state` / `questions`，题型不认识，选项少于两个），或被 DLP 拦下
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/OpenAIError' }
        '403': { $ref: '#/components/responses/OpenAIError' }
        '404':
          description: 这个模型没有配置路由
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: 有路由，但没有候选渠道提供决策接口，或候选全在失败
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /systemone:
    post:
      tags: [Chat]
      operationId: createDecisionJevAlias
      summary: 与 `POST /decisions` 完全相同的接口（Jev / Foundry 的路径名）
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/DecisionRequest' }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Decision' }
        '400': { $ref: '#/components/responses/OpenAIError' }
        '401': { $ref: '#/components/responses/OpenAIError' }
        '404': { $ref: '#/components/responses/OpenAIError' }

  /keys:
    post:
      tags: [Keys]
      operationId: createKey
      summary: 开一把子钥（母钥调用）
      description: |
        **完整明文只在创建时返回一次。**带 `external_id` 时同一个编号重复创建是**幂等**的：
        返回已存在的那把，HTTP 状态码是 `200` 而不是 `201`。

        ⚠️ 幂等重放只在**创建后 5 分钟内**能拿回明文。超过窗口 `key` 是 `null`，
        并附 `key_unavailable_reason`（**枚举值**）和 `key_unavailable_message`（文案会变）。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name:
                  type: string
                  description: 用途说明，由你填写；原样进入账单归因
                limit:
                  type: [number, 'null']
                  description: '消费上限（美元）。不传 = 不限额。设了 `limit_reset` 时是每个周期的上限，否则是累计上限'
                limit_reset:
                  type: [string, 'null']
                  enum: [daily, weekly, monthly, null]
                  description: |
                    额度多久自动清零一次。不传 = 不自动清零（花完为止）。
                    边界按 UTC：每天 00:00、每周一 00:00、每月 1 日 00:00，过了边界一分钟内生效。
                external_id:
                  type: string
                  description: 你自己的编号，用来做创建幂等；唯一性是 (账号, external_id)
                include_byok_in_limit:
                  type: boolean
                  default: true
                  description: BYOK 渠道的消耗算不算进这把 key 的上限
                expires_at:
                  type: string
                  description: 形如 `2027-01-01T00:00:00`
      responses:
        '201':
          description: 新建成功
          content:
            application/json:
              schema: { $ref: '#/components/schemas/KeyCreated' }
        '200':
          description: 幂等命中，返回已存在的那把（**没有新建任何东西**）
          content:
            application/json:
              schema: { $ref: '#/components/schemas/KeyReplay' }
        '400': { $ref: '#/components/responses/OpenAIError' }
        '401': { $ref: '#/components/responses/OpenAIError' }
    get:
      tags: [Keys]
      operationId: listKeys
      summary: 列出这个账号下的子钥
      description: |
        游标翻页。⚠️ 游标是 id 不是 offset：翻页途中若有新 key 创建，offset 会让某一把被
        跳过或重复出现。**账号下的子钥总数不设上限**，单次返回的行数有上限。
      parameters:
        - name: limit
          in: query
          schema: { type: integer, default: 100, maximum: 200 }
          description: 单页行数。**超过 200 不报错，会被压到 200**
        - name: after
          in: query
          schema: { type: integer, format: int64 }
          description: 上一页返回的 `next_cursor`，首页不传
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Key' }
                  next_cursor:
                    type: [integer, 'null']
                    description: '**在顶层**，与 `data` 平级。`null` = 没有下一页'
        '401': { $ref: '#/components/responses/OpenAIError' }

  /keys/{hash}:
    parameters:
      - name: hash
        in: path
        required: true
        schema: { type: string }
        description: 创建时返回的 `data.hash`，这把 key 的稳定标识
    get:
      tags: [Keys]
      operationId: getKey
      summary: 查一把子钥的剩余额度与用量
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: '#/components/schemas/Key' }
        '404': { $ref: '#/components/responses/OpenAIError' }
    patch:
      tags: [Keys]
      operationId: updateKey
      summary: 改额度 / 停用 / 恢复
      description: |
        ⚠️ **解封用 `{"disabled": false}`，不要用同一个 `external_id` 再开一把**：
        `external_id` 的唯一性**包含已停用的 key**，一个编号永久对应一把 key。
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/KeyPatch' }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: '#/components/schemas/Key' }
        '404': { $ref: '#/components/responses/OpenAIError' }

  /keys/external/{externalId}:
    parameters:
      - name: externalId
        in: path
        required: true
        schema: { type: string }
        description: 你自己的编号
    get:
      tags: [Keys]
      operationId: getKeyByExternalId
      summary: 按你自己的编号查子钥
      description: 有了它就不必在你那边维护一张 `external_id → hash` 的映射表。
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: '#/components/schemas/Key' }
        '404': { $ref: '#/components/responses/OpenAIError' }
    patch:
      tags: [Keys]
      operationId: updateKeyByExternalId
      summary: 按你自己的编号改额度 / 停用 / 恢复
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/KeyPatch' }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: '#/components/schemas/Key' }
        '404': { $ref: '#/components/responses/OpenAIError' }

  /keys/{hash}/reset:
    parameters:
      - name: hash
        in: path
        required: true
        schema: { type: string }
        description: 创建时返回的 `data.hash`
    post:
      tags: [Keys]
      operationId: resetKeyLimit
      summary: 把子钥额度清零
      description: |
        `limit_usage` 回到 0，`limit_remaining` 回到 `limit`，`limit_reset_at` 记成这一刻。
        累计的 `usage` 不变。没有请求体。

        用在你自己的积分节奏和周期对不上的时候，比如用户续费、活动补发额度。
        不需要先查用量再把 `limit` 改成「已用 + 新额度」，那样查和改之间花掉的钱会算错。
        设了 `limit_reset` 的 key 也可以手动清零，不影响下一次自动清零的时间。
      responses:
        '200':
          description: OK，返回清零之后的 key
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: '#/components/schemas/Key' }
        '404': { $ref: '#/components/responses/OpenAIError' }

  /keys/external/{externalId}/reset:
    parameters:
      - name: externalId
        in: path
        required: true
        schema: { type: string }
        description: 你自己的编号
    post:
      tags: [Keys]
      operationId: resetKeyLimitByExternalId
      summary: 按你自己的编号把子钥额度清零
      description: 和 `POST /v1/keys/{hash}/reset` 完全一致。
      responses:
        '200':
          description: OK，返回清零之后的 key
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: '#/components/schemas/Key' }
        '404': { $ref: '#/components/responses/OpenAIError' }

  /keys/usage/daily:
    get:
      tags: [Keys]
      operationId: listKeysUsageDaily
      summary: 账号下全部子钥按天的用量
      description: |
        一行是一把 key 一天，带 `hash` 和 `external_id`，一次请求拿到所有子钥的数。
        那一天没有用量的 key 不出现。单次窗口上限 **100 天**。

        今天那一行是实时计算的，还会变；响应里的 `includes_open_day` 为 `true` 时说明结果包含今天。
        增量同步时，`includes_open_day` 为 `false` 的结果可以直接入库，之后不会再变。
      parameters:
        - name: from
          in: query
          schema: { type: string, format: date }
          description: '含，`YYYY-MM-DD`，默认本月 1 号'
        - name: to
          in: query
          schema: { type: string, format: date }
          description: '含，`YYYY-MM-DD`，默认今天'
        - name: group_by
          in: query
          schema: { type: string, enum: [model] }
          description: '传 `model` 时每行再按模型拆，行里多一个 `model` 字段'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/KeyDailyUsage' }
        '400':
          description: '日期格式不对、`to` 早于 `from`、窗口超过 100 天，或 `group_by` 不是 `model`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: 用量暂时查不到，稍后重试
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /keys/{hash}/usage/daily:
    parameters:
      - name: hash
        in: path
        required: true
        schema: { type: string }
        description: 创建时返回的 `data.hash`
    get:
      tags: [Keys]
      operationId: getKeyUsageDaily
      summary: 一把子钥按天的用量
      description: 和 `GET /v1/keys/usage/daily` 同一个形状，只含这一把 key。
      parameters:
        - name: from
          in: query
          schema: { type: string, format: date }
          description: '含，`YYYY-MM-DD`，默认本月 1 号'
        - name: to
          in: query
          schema: { type: string, format: date }
          description: '含，`YYYY-MM-DD`，默认今天'
        - name: group_by
          in: query
          schema: { type: string, enum: [model] }
          description: '传 `model` 时每行再按模型拆，行里多一个 `model` 字段'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/KeyDailyUsage' }
        '400':
          description: '日期格式不对、`to` 早于 `from`、窗口超过 100 天，或 `group_by` 不是 `model`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: 不存在，或者不属于你（两者用同一个 404，不区分）
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: 用量暂时查不到，稍后重试
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /keys/external/{externalId}/usage/daily:
    parameters:
      - name: externalId
        in: path
        required: true
        schema: { type: string }
        description: 你自己的编号
    get:
      tags: [Keys]
      operationId: getKeyUsageDailyByExternalId
      summary: 按你自己的编号查一把子钥按天的用量
      description: 和 `GET /v1/keys/{hash}/usage/daily` 完全一致。
      parameters:
        - name: from
          in: query
          schema: { type: string, format: date }
          description: '含，`YYYY-MM-DD`，默认本月 1 号'
        - name: to
          in: query
          schema: { type: string, format: date }
          description: '含，`YYYY-MM-DD`，默认今天'
        - name: group_by
          in: query
          schema: { type: string, enum: [model] }
          description: '传 `model` 时每行再按模型拆，行里多一个 `model` 字段'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/KeyDailyUsage' }
        '400':
          description: '日期格式不对、`to` 早于 `from`、窗口超过 100 天，或 `group_by` 不是 `model`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: 不存在，或者不属于你（两者用同一个 404，不区分）
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: 用量暂时查不到，稍后重试
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /content-settings:
    get:
      tags: [Content]
      operationId: getContentSettings
      summary: 调用内容存不存、留多久、我们能不能看
      description: |
        这一组是**留存开关本身**（控制台上叫 Call Traces）。默认**不存**：关闭时
        `request_content` / `response_content` 两列为空 —— 是没有存，不是存了不给看。
      parameters:
        - name: productLine
          in: query
          schema: { type: string }
          description: |
            指定产品线；不传即账号级。
            ⚠️ **只能放在 GET 的 query 上**，写操作一律放在 body：前置网关会丢弃 POST/PUT 的
            query string，写在 query 上不报错也不生效。
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/ContentSettings' }
        '401': { $ref: '#/components/responses/ApiResponseError' }
    put:
      tags: [Content]
      operationId: updateContentSettings
      summary: 开关保存、改留存期
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                enabled: { type: boolean }
                retentionDays:
                  type: integer
                  minimum: 1
                  maximum: 365
                  description: 默认 30；超出 1–365 返回 400
                productLine: { type: string }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/ContentSettings' }
        '400': { $ref: '#/components/responses/ApiResponseError' }
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /content-settings/grants:
    post:
      tags: [Content]
      operationId: grantContentAccess
      summary: 授权我们查看一段时间
      description: |
        ⚠️ **没有「永久授权」这个选项**，时长 1 小时 – 30 天：无时限的授权会在排查结束后
        一直留存。授权期内每次读取都会记录审计。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                hours:
                  type: integer
                  minimum: 1
                  maximum: 720
                  default: 24
                reason: { type: string, description: 给审计看的理由 }
                productLine: { type: string }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/OperatorAccess' }
        '400': { $ref: '#/components/responses/ApiResponseError' }
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /content-settings/grants/revoke:
    post:
      tags: [Content]
      operationId: revokeContentAccess
      summary: 提前收回授权
      description: 到期的授权自动失效，无需处理。
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                productLine: { type: string }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/OperatorAccess' }
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /mocks:
    get:
      tags: [Mock]
      operationId: listMocks
      summary: 列出配置过演习的 key
      description: |
        ⚠️ **拿 API key 调的，只看得到自己这一把**；控制台登录会话能看到账号下所有配过的 key。
        这不是分页限制，是有意的隔离——一把泄露的 key 不该能看到别的 key 是不是也在演习、
        演的是哪种失败。
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /mocks/scenarios:
    get:
      tags: [Mock]
      operationId: listMockScenarios
      summary: 能演的失败场景目录
      description: 从服务端枚举取，不要在你这边另外硬编码一份——会漂。
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: array
                        items:
                          type: object
                          properties:
                            value:
                              type: string
                              enum: [KEY_CREDIT_EXHAUSTED, BUDGET_EXHAUSTED,
                                     ACCOUNT_BALANCE_INSUFFICIENT, RATE_LIMITED, UPSTREAM_TIMEOUT,
                                     UPSTREAM_ERROR, INVALID_KEY, MODEL_NOT_FOUND, BAD_REQUEST,
                                     CONTENT_FILTERED, SUCCESS]
                            failure:
                              type: boolean
                              description: 'false 的目前只有 `SUCCESS`——按剧本返回一个正常响应，不是失败'
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /mocks/{apiKeyId}:
    parameters:
      - name: apiKeyId
        in: path
        required: true
        schema: { type: integer, format: int64 }
    put:
      tags: [Mock]
      operationId: setMock
      summary: 给一把 key 挂上（或改）演习
      description: |
        ⚠️ **只能挂在你自己的 key 上**——拿 API key 调时挂在别的 key 上返回 `404`
        （不是 `403`，不向调用方确认「那把 key 存在，只是不是你的」）。

        挂上之后，**这把 key 接下来的调用**（`/v1/chat/completions`、`/v1/embeddings`、
        视频生成……）不再打上游，直接按这里配的场景返回，**立即生效，不需要重启或等待**。
        **只影响这一把 key**，账号下别的 key 照常打真实上游。**不计费**——演习的调用不产生
        任何用量记录。

        ⚠️ **不给 `expiresAt` 会补一个默认的（4 小时后）**，不存在「永久演习」这个选项，
        避免演习模式在测试结束后被忘记开着，某天突然发现生产 key 一直在返回假数据。
        时间戳建议带偏移量（`2026-09-27T18:00:00+08:00`）——不带的按服务端本地时区
        （`Asia/Shanghai`）解释，和别处的时间戳约定一致，但调用方通常猜不到这一点。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [scenario]
              properties:
                scenario:
                  type: string
                  description: 取自 `GET /v1/mocks/scenarios` 的 `value`
                enabled: { type: boolean }
                responseBody:
                  type: string
                  description: '只在 `scenario: SUCCESS` 时有意义：原样作为响应体返回'
                delayMs:
                  type: integer
                  description: 人为加的延迟，用来测超时处理逻辑
                expiresAt:
                  type: string
                  description: 不传则默认 4 小时后过期，见上方说明
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }
        '401': { $ref: '#/components/responses/ApiResponseError' }
        '404':
          description: 这把 key 不存在，或者不是你的
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ApiResponse' }
    delete:
      tags: [Mock]
      operationId: deleteMock
      summary: 撤掉一把 key 上的演习，恢复正常调用
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '401': { $ref: '#/components/responses/ApiResponseError' }
        '404':
          description: 这把 key 不存在，或者不是你的
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ApiResponse' }

  /integration/whoami:
    get:
      tags: [Reconciliation]
      operationId: integrationWhoami
      summary: 这把对账 key 是谁的、当前账期、能访问哪些资源
      description: 接入时从这里开始，否则「空数组」与「鉴权失败」无法区分。
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          userId: { type: integer, format: int64 }
                          timezone:
                            type: string
                            description: '**账期是按这个时区切的**，两边不一致会永远对不平'
                          currentPeriod: { type: string, examples: ['2026-08'] }
                          resources:
                            type: array
                            items: { type: string }
        '401':
          description: |
            key 无效，或**用的不是对账 key**。三类 key 权限互不重叠，这是刻意的：对账 key 会
            流转到财务系统和工单里，不能同时具备消费能力。
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ApiResponse' }

  /integration/reconciliation:
    get:
      tags: [Reconciliation]
      operationId: integrationReconciliation
      summary: 一期的勾稽：期初 + 本期变动 = 期末
      parameters:
        - name: period
          in: query
          schema: { type: string, examples: ['2026-07'] }
          description: '`YYYY-MM`，默认**上一期**（当月还在累加）'
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /integration/usage/daily:
    get:
      tags: [Reconciliation]
      operationId: integrationUsageDaily
      summary: 按天的用量汇总
      description: |
        读取夜间汇总表，**当天部分为实时计算**。⚠️ 单次查询窗口上限 **100 天**，超出返回
        明确的错误，不做静默截断。
      parameters:
        - name: from
          in: query
          schema: { type: string, format: date }
          description: 含，默认本期第一天
        - name: to
          in: query
          schema: { type: string, format: date }
          description: 含，默认今天
        - name: apiKeyId
          in: query
          schema: { type: integer, format: int64 }
          description: 只看某一把 key
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /integration/balance:
    get:
      tags: [Reconciliation]
      operationId: integrationBalance
      summary: 余额、授信、可用额度
      description: |
        ⚠️ **账号级**：同一账号下所有 key 共享一个钱包。要限制单把 key 的消费用母钥的
        `limit`，那是另一套机制。
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/Balance' }
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /integration/transactions:
    get:
      tags: [Reconciliation]
      operationId: integrationTransactions
      summary: 余额流水，分页
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/Movements' }
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /integration/statements:
    get:
      tags: [Reconciliation]
      operationId: integrationStatements
      summary: 已锁定的账单列表，最近的在前
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/Statement' }
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /integration/attribution:
    get:
      tags: [Reconciliation]
      operationId: integrationAttribution
      summary: 成本归因：按模型、渠道、标签拆开
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/Attribution' }
        '401': { $ref: '#/components/responses/ApiResponseError' }

  /integration/statements/{period}:
    get:
      tags: [Reconciliation]
      operationId: integrationStatementDetail
      summary: 某一期的账单详情
      description: |
        ⚠️ **已锁定的账单不会被改写。** 迟到的更正计入**下一期**，该行会注明来自哪个月。
        如果你的 ERP 预期「更正到达后上个月的数字会变」，那不会发生。
      parameters:
        - name: period
          in: path
          required: true
          schema: { type: string, examples: ['2026-07'] }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '404': { $ref: '#/components/responses/ApiResponseError' }


  # ── 管理钥（keyType=management）：/v1/manage/* ──────────────────────────────────────────
  # 处理器与控制台的 /v1/providers、/v1/routers、/v1/dlp 同一份；这里只列合作方会用到的那些。

  /manage/providers:
    get:
      tags: [Manage]
      operationId: manageListProviders
      summary: 列出自己的渠道（凭据只回掩码）
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '403': { $ref: '#/components/responses/ApiResponseError' }
    post:
      tags: [Manage]
      operationId: manageCreateProvider
      summary: 新建一条渠道（自带上游 key）
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ManageProvider' }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /manage/providers/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
    put:
      tags: [Manage]
      operationId: manageUpdateProvider
      summary: 修改渠道；没给的字段不改，`apiKey` 留空或回传掩码 = 保持原凭据
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ManageProvider' }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }
    delete:
      tags: [Manage]
      operationId: manageDeleteProvider
      summary: 删除渠道
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /manage/providers/{id}/test:
    parameters:
      - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
    post:
      tags: [Manage]
      operationId: manageTestProvider
      summary: 测一下渠道（地址、凭据、方言），不花 token
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }

  /manage/providers/{id}/costs:
    parameters:
      - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
    get:
      tags: [Manage]
      operationId: manageListProviderCosts
      summary: 这条渠道上录的进价
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
    put:
      tags: [Manage]
      operationId: manageUpsertProviderCost
      summary: 录 / 改一个模型的进价
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /manage/routers:
    get:
      tags: [Manage]
      operationId: manageListRouters
      summary: 列出自己的路由
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
    post:
      tags: [Manage]
      operationId: manageCreateRouter
      summary: 新建路由
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                makeDefault: { type: boolean }
                enablePlatformModels: { type: boolean }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /manage/routers/{id}/routes:
    parameters:
      - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
    get:
      tags: [Manage]
      operationId: manageListRoutes
      summary: 这个路由下的模型 → 渠道
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
    post:
      tags: [Manage]
      operationId: manageAddRoute
      summary: 把一个模型接到一条渠道上（渠道要有路由才承接流量）
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ManageRoute' }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /manage/routers/{id}/capabilities:
    parameters:
      - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
    get:
      tags: [Manage]
      operationId: manageGetCapabilities
      summary: 一个模型在这个路由下的能力（设过的 + 上游推导的）
      parameters:
        - { name: modelName, in: query, required: true, schema: { type: string } }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '404': { $ref: '#/components/responses/ApiResponseError' }
    put:
      tags: [Manage]
      operationId: manageSetCapabilities
      summary: 设一个模型的能力（这个模型在这个路由下的每一条路由一起改）
      description: |
        决定 `GET /v1/models` 里这个模型的 `architecture`，压过上游目录。两边都传空数组 = 清掉，回到跟上游。
        输入能力同时参与路由：没勾 `image` 的模型，带图的调用不会发给它。
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ModelCapabilities' }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /manage/routers/{id}/routes/{routeId}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      - { name: routeId, in: path, required: true, schema: { type: integer, format: int64 } }
    put:
      tags: [Manage]
      operationId: manageUpdateRoute
      summary: 改一条路由（优先级、权重、启停）
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ManageRoute' }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
    delete:
      tags: [Manage]
      operationId: manageDeleteRoute
      summary: 删一条路由
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }

  /manage/dlp/policy:
    get:
      tags: [Manage]
      operationId: manageGetDlpPolicy
      summary: 账户的 DLP 设置（开关、每种内置类型的动作、推荐包采纳）
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
    put:
      tags: [Manage]
      operationId: managePutDlpPolicy
      summary: 改账户的 DLP 设置；没给的字段不改
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                enabled: { type: [boolean, 'null'], description: '`null` = 跟随平台默认' }
                types:
                  type: object
                  additionalProperties: { type: [string, 'null'], enum: [BLOCK, MASK, IGNORE, ALERT, null] }
                  examples: [{ TW_NATIONAL_ID: MASK, EMAIL: null }]
                packMode: { type: string }
                autoCeiling: { type: string }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

  /manage/dlp/capabilities:
    get:
      tags: [Manage]
      operationId: manageDlpCapabilities
      summary: 写自定义规则能用的全部能力与上限
      description: 规则类型、字符集、校验算法、语境词上限、可选动作、每个作用域的条数上限、内置类型清单。
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }

  /manage/dlp/rules:
    get:
      tags: [Manage]
      operationId: manageListDlpRules
      summary: 列出自定义规则
      parameters:
        - { name: scope, in: query, schema: { type: string, enum: [TENANT, KEY, ALL], default: TENANT } }
        - { name: keyId, in: query, schema: { type: integer, format: int64 }, description: '`scope=KEY` 时必填' }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '404': { $ref: '#/components/responses/ApiResponseError' }
    post:
      tags: [Manage]
      operationId: manageCreateDlpRule
      summary: 新建一条自定义规则
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/DlpCustomRule' }
            examples:
              keywords:
                value: { scope: TENANT, name: project-codes, kind: KEYWORDS, keywords: { words: [Project Falcon, 猎鹰计划], wholeWord: true }, action: BLOCK }
              format:
                value: { scope: KEY, keyId: 1024, name: employee-id, kind: FORMAT, format: { prefix: EMP-, charset: DIGITS, length: { min: 6, max: 6 } }, action: MASK }
              regexWithChecksum:
                value: { name: card-in-ticket, kind: REGEX, regex: '\b\d{16}\b', checksum: LUHN, context: { words: [card, 卡号], window: 40 }, action: MASK }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }
        '404': { $ref: '#/components/responses/ApiResponseError' }

  /manage/dlp/rules/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
    put:
      tags: [Manage]
      operationId: manageUpdateDlpRule
      summary: 部分更新：给了的字段替换，作用域不可改
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/DlpCustomRule' }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }
        '404': { $ref: '#/components/responses/ApiResponseError' }
    delete:
      tags: [Manage]
      operationId: manageDeleteDlpRule
      summary: 删除
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '404': { $ref: '#/components/responses/ApiResponseError' }

  /manage/dlp/rules/test:
    post:
      tags: [Manage]
      operationId: manageTestDlpRules
      summary: 试扫（只读）
      description: 带 `rule` 只跑这条草稿；不带则跑账户（或 `keyId` 那把 key）当前生效的整份策略。
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [text]
              properties:
                text: { type: string, maxLength: 20000 }
                rule: { $ref: '#/components/schemas/DlpCustomRule' }
                keyId: { type: integer, format: int64 }
      responses:
        '200': { $ref: '#/components/responses/ApiResponseOk' }
        '400': { $ref: '#/components/responses/ApiResponseError' }

components:

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: "`Authorization: Bearer <key>`"

  responses:
    OpenAIError:
      description: OpenAI 形状的错误体
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    ApiResponseOk:
      description: OK（ApiResponse 形状）
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ApiResponse' }
    ApiResponseError:
      description: "失败（ApiResponse 形状，`success: false`）"
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ApiResponse' }

  schemas:

    ManageProvider:
      type: object
      description: 渠道。完整字段说明见文档「管理钥」一节。
      properties:
        name: { type: string }
        baseUrl: { type: string, description: 上游根地址 }
        apiStyle: { type: string, examples: [OPENAI, ANTHROPIC] }
        apiKey: { type: string, description: 上游凭据；更新时留空或回传掩码 = 保持原样 }
        paused: { type: boolean }
      additionalProperties: true

    ManageRoute:
      type: object
      properties:
        modelName: { type: string, description: 客户调用时写的模型名 }
        providerModelName: { type: string, description: 上游那边的模型名 }
        providerId: { type: integer, format: int64 }
        priority: { type: integer }
        weight: { type: integer }
        enabled: { type: boolean }
        inputModalities:
          type: array
          readOnly: true
          items: { type: string }
          description: 这个模型设的输入能力；空 = 跟上游。用 `PUT /manage/routers/{id}/capabilities` 改
        outputModalities:
          type: array
          readOnly: true
          items: { type: string }
          description: 这个模型设的输出能力；空 = 跟上游

    ModelCapabilities:
      type: object
      required: [modelName, inputModalities, outputModalities]
      properties:
        modelName: { type: string }
        inputModalities:
          type: array
          items: { type: string, enum: [text, image, file, audio, video] }
        outputModalities:
          type: array
          items: { type: string, enum: [text, image, audio, video, embeddings] }
        inferred:
          type: object
          readOnly: true
          description: 只在 GET 的回包里：不看设置时上游目录 / 模型资料给的能力
          properties:
            inputModalities: { type: array, items: { type: string } }
            outputModalities: { type: array, items: { type: string } }
            source: { type: [string, 'null'], enum: [upstream, baseline, null], description: 'upstream = 渠道的模型列表，baseline = Tare 的模型资料，null = 两边都没有' }

    DlpCustomRule:
      type: object
      description: |
        客户自定义 DLP 规则。`kind` 决定读哪一格定义：`REGEX` 读 `regex`，`KEYWORDS` 读 `keywords`，
        `FORMAT` 读 `format`。`checksum` 与 `context` 对三种都可选。上限以 `GET /manage/dlp/capabilities` 为准。
      properties:
        scope: { type: string, enum: [TENANT, KEY], default: TENANT }
        keyId: { type: integer, format: int64, description: '`scope=KEY` 时必填，必须是自己的推理 key' }
        name: { type: string, maxLength: 64 }
        kind: { type: string, enum: [REGEX, KEYWORDS, FORMAT] }
        regex: { type: string, maxLength: 500 }
        keywords:
          type: object
          properties:
            words: { type: array, maxItems: 100, items: { type: string, maxLength: 64 } }
            wholeWord: { type: boolean, default: true }
        format:
          type: object
          properties:
            prefix: { type: string, maxLength: 32 }
            charset: { type: string, enum: [ALNUM, UPPER_DIGIT, LOWER_DIGIT, HEX, DIGITS, B64URL, B64] }
            length:
              type: object
              properties:
                min: { type: integer, minimum: 1 }
                max: { type: integer, maximum: 512 }
            boundary: { type: string, enum: [WORD, NONE], default: WORD }
            suffix: { type: [string, 'null'], maxLength: 32 }
        checksum: { type: [string, 'null'], enum: [LUHN, IBAN_MOD97, CN_RESIDENT_ID, TW_NATIONAL_ID, TW_RESIDENT_CERT, TW_UBN, null] }
        context:
          type: [object, 'null']
          properties:
            words: { type: array, maxItems: 20, items: { type: string, maxLength: 32 } }
            window: { type: integer, minimum: 1, maximum: 200, default: 40 }
        action: { type: string, enum: [BLOCK, MASK, ALERT] }
        enabled: { type: boolean, default: true }
        description: { type: [string, 'null'], maxLength: 255 }

    DecisionRequest:
      type: object
      required: [model, state, questions]
      properties:
        model:
          type: string
          examples: ['microsoft/microsoft-decision-1']
        state:
          description: 问题针对的文本；也可以是任意 JSON（对象或数组），里面的字符串都会被读到
          oneOf:
            - type: string
            - type: object
            - type: array
        questions:
          type: object
          description: 按名字列的问题，最多 64 个；回包 `answers` 用同样的名字
          additionalProperties: { $ref: '#/components/schemas/DecisionQuestion' }
      examples:
        - model: microsoft/microsoft-decision-1
          state: 我上周买的芒果酸奶送到的时候盒子是空的，这已经是第二次了！
          questions:
            complaint: { type: noul, instructions: 顾客是否在投诉？ }
            team:
              type: choice
              instructions: 这条消息应该交给哪个组处理？
              criteria: { billing: 付款、扣费、退款, shipping: 配送、缺件、送错, product: 商品质量、口味 }
            anger: { type: score, instructions: 顾客有多生气？, criteria: [平静, 不满, 生气, 非常愤怒] }
    DecisionQuestion:
      type: object
      required: [type, instructions]
      properties:
        type: { type: string, enum: [noul, choice, score] }
        instructions:
          type: string
          description: 问题本身。规则请直接写进来（「我们的政策是…，这位顾客该不该退款？」）
        criteria:
          description: |
            `choice`：选项名 → 说明（说明可为空串），至少两个；`score`：从低到高的档位列表，至少两个；
            `noul`：可选，上游可能不读，判断标准请写进 `instructions`
          oneOf:
            - type: object
              additionalProperties: { type: string }
            - type: array
              items: { type: string }
    Decision:
      type: object
      properties:
        id: { type: string, description: 本次调用的编号，`gen-` 开头 }
        model: { type: string, description: 请求里的模型名 }
        answers:
          type: object
          description: 按问题名字给出答案
          additionalProperties:
            type: object
            properties:
              type: { type: string, enum: [noul, choice, score] }
              noul: { type: number, description: '`noul`：P(yes)，0 到 1' }
              choice: { type: string, description: '`choice`：概率最高的选项' }
              score: { type: number, description: '`score`：期望档位（0 起）' }
              legend: { type: object, description: '`score`：档位下标 → 档位名', additionalProperties: { type: string } }
              probabilities: { type: object, description: '`choice` / `score`：每个选项（档位）的概率，合计为 1', additionalProperties: { type: number } }
              confidence: { type: number, description: '`choice` / `score`：0（和均匀分布一样）到 1（完全确定）' }
        usage:
          type: object
          properties:
            input_tokens: { type: integer }
            output_tokens: { type: integer }
            cost: { type: number, description: 这次的扣费（美元）；BYOK 时为上游费用 + 路由费 }
    Error:
      type: object
      description: |
        ⚠️ **`type` 与 `metadata.error_type` 同值、刻意重复**：OpenAI SDK 读前者，
        OpenRouter 一系读后者。只给一个时，另一边的客户端拿到 `undefined` —— 不报错，
        只是把一个明确的拒绝显示成「未知错误」。
      properties:
        error:
          type: object
          required: [code, message, type]
          properties:
            code:
              type: integer
              description: '**始终等于 HTTP 状态码。**按它分支是安全的'
            message: { type: string }
            type:
              type: string
              description: OpenAI SDK 读该字段
              examples: [token_limit_exceeded]
            metadata:
              type: object
              properties:
                error_type:
                  type: string
                  description: 与 `type` 同值
                refusal_reason:
                  type: string
                  enum: [key_credit_exhausted, budget_exhausted, account_balance_insufficient,
                         source_ip_not_allowed]
                  description: |
                    出现在被「挡下」而不是「出错」的那些响应上，**用它决定向终端用户展示什么**：
                    · `key_credit_exhausted` —— 这把 key 的额度用尽（403），充值可解决；
                    · `budget_exhausted` —— 账号月度预算到顶（403），**与终端用户无关**；
                    · `account_balance_insufficient` —— 账号欠费（402），**同样与终端用户无关**；
                    · `source_ip_not_allowed` —— 调用来源不在这把 key 的 IP 白名单上（403）。
                      **和钱无关**：把它说成「额度不足」会让用户去充一笔没用的钱，
                      而要做的是换一台在名单上的机器、或者把这台的出网地址加进名单。
                    中间两种若说成「你的额度用完了」，用户会为与自己无关的事付费。
                provider_code:
                  type: string
                  description: 上游给的原始码，透传，可能没有

    ApiResponse:
      type: object
      required: [code, message, success]
      description: |
        对账那一组的信封。⚠️ 经由网关访问时，网关**不拆上游信封**，业务数据会嵌两层
        （`data.data`）；直连 `tare.jamerly.ai` 时是一层。
      properties:
        code: { type: integer }
        message: { type: string }
        success: { type: boolean }
        data: {}

    ChatCompletion:
      type: object
      description: OpenAI 形状，外加 `usage.cost`。
      required: [id, object, created, model, choices]
      properties:
        id: { type: string, description: '`gen-` 开头的对外编号' }
        object: { type: string, examples: [chat.completion] }
        created: { type: integer }
        model:
          type: string
          description: '**始终是你请求的那个名字**，故障转移对调用方不可见'
        provider: { type: string }
        choices:
          type: array
          items: {}
        usage:
          type: object
          properties:
            prompt_tokens: { type: integer }
            completion_tokens: { type: integer }
            total_tokens: { type: integer }
            cost:
              type: number
              description: |
                这次调用的**成本**（归因口径），单位美元。
                · 平台模型：等于我们的售价；
                · **BYOK：上游进价 + 服务费**（BYOK 的 token 你直接付给供应商，
                  给你一个 0 会让你的成本报表显示这个月免费用了几百万 token）。
                ⚠️ **无法计算时该字段不出现**，而不是 0：假的 0 会被当真。
                ⚠️ **流式的末帧同样带 cost**（末帧才有 usage）。
            is_byok: { type: boolean }

    Model:
      type: object
      # context_length 与 architecture 拿不到上游目录时会缺 —— 刻意不进 required。
      required: [id, name, pricing]
      properties:
        id:
          type: string
          description: '**平台侧模型名**，用它发起调用'
        name: { type: string }
        description:
          type: string
          description: 来自上游目录的模型说明；**不可用时该字段不出现**
        context_length:
          type: integer
          description: 来自上游目录；**不可用时该字段不出现**（不要当成 0）
        architecture:
          type: object
          description: |
            按这个顺序取：控制台 Routing 页给这个模型设的能力 → 上游目录 → Tare 的模型资料。
            三处都没有时这个字段不出现。自建、本地模型和只回 id 的中转站通常不在上游目录里，
            在 Routing 页给它设上能力，按 `input_modalities` 过滤模型的客户端才看得到它。
          properties:
            modality: { type: string }
            input_modalities: { type: array, items: { type: string } }
            output_modalities: { type: array, items: { type: string } }
        reasoning:
          type: object
          description: |
            这个模型的思考能力，来自上游目录，客户端据此决定是否展示「思考强度」选择器、
            展示哪几档。

            ⚠️ **不可用时整个字段不出现，且不给默认值**（与 `architecture` 相反）。
            编造默认值等于代替上游做出未经确认的承诺：用户选了上游不认的强度，换回一个 400，
            看起来却像模型故障。
          properties:
            mandatory:
              type: boolean
              description: 强制思考，无法关闭
            default_enabled: { type: boolean }
            supported_efforts:
              type: array
              items: { type: string }
              description: '⚠️ 取值**由上游决定**，不限于这三档；按字段渲染，不要写死'
            default_effort: { type: string }
        pricing:
          type: object
          description: '**每 token** 的字符串（不是每百万），**币种为美元**'
          properties:
            prompt: { type: string }
            completion: { type: string }
            input_cache_read:
              type: string
              description: '缓存读，同样每 token'
            input_cache_write:
              type: string
              description: '缓存写，同样每 token'
            request:
              type: string
              description: '**恒为 `0`**：我们不按次收费，只按 token'
            image:
              type: string
              description: |
                ⚠️ **恒为 `0`，但图片不是免费的。** 价目表只有 token 四档
                （输入 / 输出 / 缓存读 / 缓存写），没有「每张图」这一档；带图的调用
                按上游报的 token 与成本计价。**不要用该字段估算图片成本**。

    EmbeddingList:
      type: object
      required: [object, data, model, usage]
      properties:
        object: { type: string, examples: [list] }
        model:
          type: string
          description: '**上游原样返回的名字**，我们不改写'
        data:
          type: array
          items:
            type: object
            required: [object, index, embedding]
            properties:
              object: { type: string, examples: [embedding] }
              index: { type: integer }
              embedding:
                type: array
                items: { type: number }
                description: '`encoding_format: base64` 时这一格是字符串，由上游决定'
        usage:
          type: object
          properties:
            prompt_tokens: { type: integer }
            total_tokens: { type: integer }
            cost:
              type: number
              description: |
                这次**花了你多少**，口径和 chat 完全一致。
                ⚠️ **算不出来时这一格不出现，而不是 0** —— 「这个模型还没定价」也算
                算不出来（判据是上游确实收了我们钱而我们算出 0）。
                出现的 `0` 因此是**真的 0**，不是「不知道」。
                ⚠️ 走平台渠道时回包里**不会**有 `usage.cost_details` —— 那一格是上游
                向我们收的钱。BYOK 下它保留：那是你自己上游账单上的钱。
                embeddings 没有输出 token，所以只有输入这一档参与计价。

    Generation:
      type: object
      required: [id, model, created_at, tokens_prompt, tokens_completion, total_cost, usage, is_byok]
      properties:
        id: { type: string }
        model: { type: string }
        provider_name: { type: string }
        created_at:
          type: string
          format: date-time
          description: '⚠️ 不带偏移量，按 `Asia/Shanghai`（UTC+8）解释'
        tokens_prompt: { type: integer }
        tokens_completion: { type: integer }
        native_tokens_prompt: { type: integer }
        native_tokens_completion: { type: integer }
        total_cost:
          type: number
          description: 向你收取的金额
        usage:
          type: number
          description: 与 `total_cost` 同值（OpenRouter 兼容）
        upstream_inference_cost:
          type: number
          description: |
            上游向我们收取的金额；**仅 BYOK 调用有** —— 走平台渠道（转售）时这一格
            不出现，那是我们的进价。
            ⚠️ 2026-08-22 之前实现漏判了这一条，转售调用上也返回了；已修。
        is_byok: { type: boolean }
        cancelled: { type: boolean }
        generation_time:
          type: integer
          description: |
            真正服务了这次请求那条渠道自己的耗时（毫秒）。没转移过的调用等于 `latency`。
            没记过耗时的老记录不出现这一格，不给 0。
        latency:
          type: integer
          description: |
            这次调用的总延迟（毫秒）= `generation_time` 加上转移之前每一条失败尝试
            各自的耗时。字段名和语义照抄 OpenRouter；和它不同的是我们还给
            `routing_overhead_ms` 这一层拆分——它不把自己的重试暴露给客户，我们可以，
            因为我们按每次尝试单独记账。
        routing_overhead_ms:
          type: integer
          description: |
            `latency` 减去 `generation_time`。只在这次调用真的转移过渠道时才出现，
            没转移过就不给这一格（不是 0）。区分「模型本来就慢」和「前面几条渠道
            先超时了一轮」。
        time_to_first_token_ms:
          type: integer
          description: |
            首字节到达耗时（毫秒）。**只有流式调用才有**——OpenRouter 的 generation
            stats 接口没有这一格，我们记了就给。

    ImageGenerationRequest:
      type: object
      required: [model, prompt]
      additionalProperties: true
      properties:
        model:
          type: string
          description: 平台侧模型名，或你在 Routing 页配过的一条
          examples: ['google/gemini-3-pro-image']
        prompt: { type: string }
        models:
          type: array
          items: { type: string }
          description: 备用模型链，语义与 `/chat/completions` 的 `models` 相同
        provider:
          type: object
          description: 按次路由偏好，语义与 `/chat/completions` 的 `provider` 相同
          properties:
            order: { type: array, items: { type: string } }
            allow_fallbacks: { type: boolean, default: true }
            only: { type: array, items: { type: string } }
            ignore: { type: array, items: { type: string } }
            sort: { type: string, examples: ['latency'] }
        size: { type: string }
        aspect_ratio: { type: string, examples: ['16:9'] }
        n: { type: integer }
        input_references:
          type: array
          items: { type: string }
          description: 参考图的公网 HTTPS 地址（图生图/图片编辑）

    ImageGeneration:
      type: object
      properties:
        id: { type: string }
        created: { type: integer }
        model: { type: string, description: 你请求的那个名字，不是上游的 }
        data:
          type: array
          items:
            type: object
            properties:
              b64_json: { type: string, description: '**长期保存用这个**' }
              media_type: { type: string, examples: [image/png] }
              url: { type: string, description: '⚠️ 24 小时后失效' }
              expires_at: { type: integer, description: Unix 秒，`url` 失效时刻 }
        text: { type: string, description: 模型随图片一起返回的文字，**空则不出现** }
        finish_reason:
          type: string
          description: '`data` 为空时先看这个——`content_filter` 表示生成后被上游拦下'
        usage:
          type: object
          properties:
            prompt_tokens: { type: integer }
            completion_tokens: { type: integer }
            total_tokens: { type: integer }
            cost: { type: number, description: 这次调用的真实成本 }

    VideoGeneration:
      type: object
      required: [id, status, model, created]
      properties:
        id: { type: string, description: '`gen-` 开头的对外编号' }
        status:
          type: string
          enum: [pending, running, succeeded, failed, expired]
        model: { type: string }
        created: { type: integer, description: Unix 时间戳（秒），提交时刻 }
        completed: { type: integer, description: 'Unix 时间戳（秒），只在 `succeeded` 时出现' }
        result:
          type: object
          description: '只在 `status: succeeded` 时出现'
          properties:
            video_url: { type: string }
            video_urls:
              type: array
              items: { type: string }
              description: 只在这次生成产出不止一个视频时才出现
        usage:
          type: object
          description: '只在 `status: succeeded` 时出现'
          properties:
            video_tokens: { type: integer }
        error:
          type: object
          description: '只在 `status: failed` 或 `expired` 时出现'
          properties:
            message: { type: string }

    Key:
      type: object
      # ⚠️ 只有**确定存在**的字段进 required。`external_id` 刻意不在里面 ——
      # 从没设过时整格不出现，这正是需要客户端处理的那种情况。
      required: [hash, name, label, usage, disabled, include_byok_in_limit, created_at, updated_at]
      properties:
        hash:
          type: string
          description: '**稳定标识**，之后所有针对这把 key 的操作都用它'
        name: { type: string }
        label: { type: string, description: 前缀 + 省略号，给人看的 }
        limit:
          type: [number, 'null']
          description: '上限；**`null` = 不限额，不是 0**'
        limit_remaining:
          type: [number, 'null']
          description: '还能花多少 = `limit - limit_usage`，不会小于 0。不限额时为 `null`'
        limit_reset:
          type: [string, 'null']
          enum: [daily, weekly, monthly, null]
          description: '自动清零周期；`null` = 不自动清零'
        limit_usage:
          type: number
          description: '上次清零以来花了多少（美元），额度按它判断。从没清零过时等于 `usage`'
        limit_reset_at:
          type: [string, 'null']
          format: date-time
          description: '上次清零（手动或自动）的时刻，**UTC**，不带偏移量。打开 `limit_reset` 时也会写成那一刻'
        usage:
          type: number
          description: '累计花了多少（美元）。清零不影响它'
        usage_daily:
          type: [number, 'null']
          description: |
            今天花了多少（美元）。天按账期时区切（见 `GET /v1/keys/usage/daily` 返回的 `timezone`），
            与 `limit_reset` 用的 UTC 边界不是同一个。清零不影响它。
            `null` = 用量暂时查不到，不是 0。
            关了 `include_byok_in_limit` 的 key，`usage` 不含 BYOK 渠道的消耗，这三个时间段字段含。
        usage_weekly:
          type: [number, 'null']
          description: '本周（周一起，账期时区）花了多少（美元）。其余同 `usage_daily`'
        usage_monthly:
          type: [number, 'null']
          description: '本月（1 号起，账期时区）花了多少（美元）。其余同 `usage_daily`'
        disabled: { type: boolean }
        include_byok_in_limit: { type: boolean }
        external_id:
          type: string
          description: 你自己的编号；**从未设置时该字段整个不出现**
        byok_usage: { type: number, description: 目前恒为 0，保留 }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        expires_at:
          type: [string, 'null']
          format: date-time
          description: '⚠️ 不带偏移量，按 `Asia/Shanghai`（UTC+8）解释'

    KeyDailyUsage:
      type: object
      required: [data, from, to, timezone, includes_open_day]
      properties:
        data:
          type: array
          description: 按日期、key、模型排序
          items:
            type: object
            required: [date, hash, external_id, usage, requests, prompt_tokens, completion_tokens, reasoning_tokens, cached_tokens]
            properties:
              date: { type: string, format: date, description: '账期时区的日期' }
              hash: { type: string }
              external_id:
                type: [string, 'null']
                description: '这把 key 的 `external_id`；没设过时为 `null`'
              model:
                type: [string, 'null']
                description: '只在 `group_by=model` 时出现'
              usage:
                type: number
                description: '这一天花了多少（美元），与 `Key.usage_daily` 同一口径'
              requests: { type: integer, format: int64 }
              prompt_tokens: { type: integer, format: int64 }
              completion_tokens: { type: integer, format: int64 }
              reasoning_tokens:
                type: integer
                format: int64
                description: |
                  `completion_tokens` 中的推理部分。从 2026-11-23 起统计，更早的日期为 0。
                  Anthropic 系上游不单独报推理 token，这类调用恒为 0。
              cached_tokens:
                type: integer
                format: int64
                description: '`prompt_tokens` 中命中缓存的部分'
        from: { type: string, format: date, description: '实际使用的起始日期（含）' }
        to: { type: string, format: date, description: '实际使用的结束日期（含）' }
        timezone:
          type: string
          examples: [Asia/Shanghai]
          description: '切天用的时区'
        includes_open_day:
          type: boolean
          description: '`[from, to]` 包含今天。今天的数还会变'

    Balance:
      type: object
      required: [currency, balance, available]
      properties:
        currency: { type: string, examples: [USD] }
        balance: { type: number, description: 当前余额 }
        creditLimit: { type: number, description: 授信额度 }
        available: { type: number, description: 可用 = 余额 + 授信 }
        lifetimeCharged: { type: number, description: 累计消费 }
        lifetimeCredited: { type: number, description: 累计充值 }
        periods:
          type: array
          description: 按期的小计
          items:
            type: object
            required: [period]
            properties:
              period: { type: string, examples: ['2026-07'] }
              charged: { type: number }
              credited: { type: number }

    Movements:
      type: object
      required: [content, total, page, size]
      properties:
        content:
          type: array
          items: { $ref: '#/components/schemas/Movement' }
        total: { type: integer, format: int64 }
        page: { type: integer }
        size: { type: integer }

    Movement:
      type: object
      required: [id, at, amount, direction]
      properties:
        id: { type: integer, format: int64 }
        at:
          type: string
          format: date-time
          description: '⚠️ 不带偏移量时按 `Asia/Shanghai`（UTC+8）解释'
        category: { type: string }
        type: { type: string }
        direction: { type: string, enum: [IN, OUT] }
        amount: { type: number }

    Statement:
      type: object
      required: [period]
      properties:
        period: { type: string, examples: ['2026-07'] }
        closed:
          type: boolean
          description: '**已锁定的账单不会被改写**，迟到的更正进下一期'
        charged: { type: number }
        lines:
          type: array
          description: 每个模型一行；补差行会写明自己来自哪个月
          items: { type: object, additionalProperties: true }

    Attribution:
      type: object
      description: |
        按模型 / 渠道 / 自定义标签拆分的花费。⚠️ **覆盖率与金额一并给出**：
        「本月成本 X（覆盖 62%）」中的 62% 表示还有 38% 的调用没有成本数据——不是它们
        不花钱，而是我们不知道花了多少。用未覆盖全的数字算毛利会偏乐观。
      additionalProperties: true

    ContentSettings:
      type: object
      required: [enabled, retentionDays]
      properties:
        enabled: { type: boolean, description: '**默认 false** —— 默认不存' }
        retentionDays: { type: integer, description: 默认 30，可配 1–365 }
        productLine: { type: string }
        operatorAccess: { $ref: '#/components/schemas/OperatorAccess' }

    OperatorAccess:
      type: object
      description: 我们当前是否可以查看这个账号的调用内容。
      properties:
        granted: { type: boolean }
        expiresAt:
          type: [string, 'null']
          format: date-time
          description: 授权到什么时候；没有授权时为 null
        reason: { type: string }

    KeyPatch:
      type: object
      properties:
        limit:
          type: [number, 'null']
          description: 改上限；`null` = 改成不限额
        limit_reset:
          type: [string, 'null']
          enum: [daily, weekly, monthly, null]
          description: |
            改自动清零周期；**显式 `null` = 不再自动清零**。
            从不清零改成按周期清零时，周期从这一刻起算，已经花掉的量**不会**被立刻清掉；
            要现在就清，调 `POST /v1/keys/{hash}/reset`。
        name: { type: string }
        disabled:
          type: boolean
          description: '`true` 停用、`false` 恢复'
        include_byok_in_limit: { type: boolean }
        expires_at:
          type: [string, 'null']
          format: date-time
          description: |
            改到期时间；**显式 `null` = 取消到期**（与 `limit` 字段语义一致）。
            ⚠️ 到期的 key 调模型返回 **401**，与被吊销的表现完全一致：区分二者等于向持有无效
            凭据的人确认「这把 key 曾经存在」。
            ⚠️ 到期**不会**把 `disabled` 置为 `true`，该字段只表示「被停用」，判断到期请读
            `expires_at`。

    KeyCreated:
      type: object
      required: [key, data]
      properties:
        key:
          type: string
          description: '**完整明文，只在这一次出现。**'
        data: { $ref: '#/components/schemas/Key' }

    KeyReplay:
      type: object
      description: 幂等命中的返回。窗口内带明文，窗口外 `key` 为 `null`。
      # key 一定出现（可能是 null）；那两个 unavailable 字段只在窗口外出现。
      required: [key, data]
      properties:
        key:
          type: [string, 'null']
          description: 创建后 5 分钟内才有
        key_unavailable_reason:
          type: string
          enum: [plaintext_window_expired]
          description: |
            **可编程的取值**，目前只有这一个；新增会提前通知。**按它分支。**
        key_unavailable_message:
          type: string
          description: '面向人的文案。**措辞会变，不要用于判断。**'
        data: { $ref: '#/components/schemas/Key' }
