openapi: 3.0.3
info:
  title: Acosmi 开放 API
  description: >
    开放 API（sk- API Key）+ 按量付费（Credits），以及 2026-08-14 新增的 /v1 标准协议兼容层
    与会员委托 Key。与会员体系并行，身份互通、账本按凭证的 billing_mode 路由：
    /api/open/v1/* 边缘仅消费 API Credits 池③；/v1 兼容层按凭证分流（会员委托 Key → 会员权益池，
    按量 Key → 池③）。所有路径/方法/鉴权 scheme 均核对仓库真实代码
    （见 docs/api-open/开放API开发者文档-2026-05-29.md §8 来源核对清单）。
    本文描述整改候选，接口存在不等于生产已启用或业务验收。有效价约、持久计量和对应资金合同是执行前置；缺价或缺能力不是免费。
    /v1 兼容层受服务端开关 COMPAT_API_V1_ENABLED 控制，默认关闭（关闭时返回原生 404）。
  version: "1.1-candidate"

servers:
  - url: https://acosmi.com
    description: CN 生产（主机名以实际部署为准）

# 三套鉴权:
#   - apiKey (sk-)  : 对外开放 API /api/open/v1/*, 以及 /v1 兼容层 (Authorization: Bearer)
#   - xApiKey       : 仅 /v1 兼容层, Anthropic 客户端惯例 (x-api-key 头), 受服务端开关控制
#   - loginBearer   : 登录态 OAuth/JWT, 用于凭证控制面 /api/v4/open-api-keys 与 /api/v4/agent-access-keys
components:
  securitySchemes:
    nexusCookie:
      type: apiKey
      in: cookie
      name: acorei_token
      description: HttpOnly Nexus session, independently paired with the current Java session.
    playgroundKey:
      type: apiKey
      in: header
      name: X-Acosmi-Playground-Key
      description: Explicit own PAYG Key; browser memory only. Never stored or inserted into URLs/examples.
    apiKey:
      type: http
      scheme: bearer
      bearerFormat: sk-acm-...
      description: >
        开放 API Key。Authorization 头形如 "Bearer sk-acm-xxxxxxxx..."。
        /v1 兼容层同一位置还接受会员 OAuth access token（非 sk- 前缀时回退 OAuth/JWT 校验）。
    xApiKey:
      type: apiKey
      in: header
      name: x-api-key
      description: >
        仅 /v1 兼容层接受（Anthropic 客户端惯例），值为 sk-acm-...；
        由服务端开关 COMPAT_API_ANTHROPIC_XAPIKEY_ENABLED 控制，默认关闭。
    consoleBearer:
      type: http
      scheme: bearer
      bearerFormat: Java Web session
      description: Java控制台会话，用于本人订单、余额、账单与可信身份映射/退出；不是Nexus登录JWT，也不是开放执行凭证。
    loginBearer:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        Nexus 普通登录 JWT，供 Go PAYG Key 控制面。Java session 和会员 OAuth 不能替代。
        /api/v4/agent-access-keys 另接受桌面 OAuth（scope agent_access:manage）；
        web_oauth 签发被拒（403 issuer_not_consented）。

  schemas:
    PortalProfile:
      type: object
      required:
        - id
        - wire
        - protocol_supported
        - price_ack_ready
        - financial_ready
        - release_accepted
        - supported_parameters
      properties:
        id:
          type: string
          format: uuid
        wire:
          type: string
          enum:
            - openai
            - anthropic
        provider:
          type: string
        channel_id:
          type: string
        config_revision:
          type: string
        context_window:
          type: integer
        max_output_tokens:
          type: integer
        input_modalities:
          type: array
          items:
            type: string
        capabilities:
          type: object
          additionalProperties: true
        supported_parameters:
          type: array
          items:
            type: string
        protocol_supported:
          type: boolean
        price_ack_ready:
          type: boolean
        financial_ready:
          type: boolean
        release_accepted:
          type: boolean
        provider_health:
          type: string
          enum:
            - unknown
            - healthy
            - known_bad
        price_status:
          type: string
        free_reason:
          type: string
        pricing:
          type: object
          additionalProperties:
            type: string
            description: V1 Credits per total TOKEN / image / video second
        contract_versions:
          type: array
          items:
            type: string
        release_accepted_v2:
          type: boolean
        financial_ready_v2:
          type: boolean
        pricing_v2:
          $ref: '#/components/schemas/ComponentReferencePrice'
    ComponentReferencePrice:
      type: object
      properties:
        currency:
          type: string
          enum: [CNY]
        credits_per_cny:
          type: string
          enum: ['1000000']
        effective_price_version:
          type: integer
          minimum: 0
          description: Last acknowledged publication version. Execution revalidates this version; PRICE_CHANGED requires a fresh quote or price selection and never increases the customer cap.
        input_tiers:
          type: array
          items:
            type: object
            properties:
              max_input_tokens:
                type: integer
                minimum: 1
                description: Inclusive whole-request input bound; K means 1000, not 1024.
              rates:
                $ref: '#/components/schemas/ComponentRates'
        contract_version:
          type: string
          enum:
            - TEXT_COMPONENTS_V2
        price_scope:
          type: string
          enum:
            - UNIFIED
        measurement_schema:
          type: string
        rates:
          $ref: '#/components/schemas/ComponentRates'
        price_status:
          type: string
          enum:
            - ready
            - sync_pending
            - withdrawn
            - not_configured
        free_reason:
          type: string
      description: >-
        Reference desired source rates, Credits per million component TOKEN. Never treat historical ACK versions
        as a current frozen quote.
    ComponentRates:
      type: object
      additionalProperties: false
      properties:
        input_uncached:
          type: string
          pattern: ^\d+(\.\d+)?$
        output_total:
          type: string
          pattern: ^\d+(\.\d+)?$
        cache_read:
          type: string
          pattern: ^\d+(\.\d+)?$
        cache_write_total:
          type: string
          pattern: ^\d+(\.\d+)?$
    PortalEntry:
      type: object
      required:
        - public_key
        - model_id
        - name
        - profiles
      properties:
        public_key:
          type: string
          pattern: ^m-[A-Za-z0-9_-]+$
          description: m- plus canonical UTF-8 model_id base64url without padding
        model_id:
          type: string
        name:
          type: string
        profiles:
          type: array
          items:
            $ref: '#/components/schemas/PortalProfile'
    PortalCatalog:
      type: object
      required:
        - version
        - observed_at
        - data
      properties:
        version:
          type: string
        observed_at:
          type: string
          format: date-time
        data:
          type: array
          items:
            $ref: '#/components/schemas/PortalEntry'
    AcosmiOptions:
      type: object
      additionalProperties: false
      properties:
        contract_version:
          type: string
          enum:
            - TEXT_COMPONENTS_V2
        expected_price_version:
          type: integer
          minimum: 1
          description: Model-specific V2 effective revision; required together with contract_version and max_credits.
        max_credits:
          type: string
          pattern: ^(0|[1-9]\d{0,13})(\.\d{1,6})?$
          description: Explicit customer charge cap in public Credits (1,000,000 Credits = CNY 1; 1 Credit = 1,000 micro Credits). Never increased automatically. The domestic ledger settles in CNY; USD is display-only.
        routing:
          type: object
          additionalProperties: false
          properties:
            mode:
              type: string
              enum:
                - fixed
                - priority
            channel_id:
              type: string
              pattern: ^[a-z0-9_-]{1,64}$
          required:
            - mode
      oneOf:
        - type: object
          properties:
            routing:
              type: object
              additionalProperties: false
              properties:
                mode:
                  type: string
                  enum:
                    - fixed
                    - priority
                channel_id:
                  type: string
                  pattern: ^[a-z0-9_-]{1,64}$
              required:
                - mode
          additionalProperties: false
        - type: object
          required:
            - contract_version
            - expected_price_version
            - max_credits
    PlaygroundRequest:
      type: object
      additionalProperties: false
      required:
        - profile_id
        - wire
        - payload
      properties:
        profile_id:
          type: string
          format: uuid
        wire:
          type: string
          enum:
            - openai
            - anthropic
        payload:
          type: object
          description: >-
            Complete native text/tool payload for the selected wire. No client model/user/tenant/endpoint
            overrides. acosmi_options is stripped before provider dispatch.
          properties:
            messages:
              type: array
              minItems: 1
              items:
                type: object
            stream:
              type: boolean
            max_tokens:
              type: integer
              minimum: 1
            max_completion_tokens:
              type: integer
              minimum: 1
            acosmi_options:
              $ref: '#/components/schemas/AcosmiOptions'
          additionalProperties: true
    ConsumeRequestDetail:
      type: object
      properties:
        consume_request_id:
          type: string
          format: uuid
        transport_request_id:
          type: string
          format: uuid
        execution_status:
          type: string
        financial_status:
          type: string
          description: >-
            Independent from delivery/DONE; RESERVED, SETTLED, RELEASED, UNKNOWN_RESOLVED,
            FINANCE_CONFIRMATION_PENDING, NOT_STARTED or FINANCE_UNAVAILABLE.
        association_status:
          type: string
          enum:
            - RESOLVED
            - UNRESOLVED
        tuple:
          type: object
          properties:
            model_id:
              type: string
            profile_id:
              type: string
              format: uuid
            key_id:
              type: string
              format: uuid
        reserved_credits:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Exact decimal Credits; null is unconfirmed and must not be rendered as zero.
        customer_charged_credits:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Exact decimal Credits; null is unconfirmed and must not be rendered as zero.
        contractual_credits:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Exact decimal Credits; null is unconfirmed and must not be rendered as zero.
        platform_covered_credits:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Exact decimal Credits; null is unconfirmed and must not be rendered as zero.
        measurement_schema:
          type: string
          nullable: true
          description: Frozen original reservation schema; never inferred from current quote or catalog.
        effective_price_version:
          type: integer
          format: int64
          nullable: true
          description: Frozen original effective price revision.
        peak_multiplier:
          type: string
          nullable: true
          description: Original frozen peak multiplier; decimal string.
        rounding_difference:
          type: string
          nullable: true
          description: Signed contractual total minus the four displayed charge lines. Presentation only; never a cash adjustment. Null when not provable.
        reservation:
          type: object
          nullable: true
        finalization:
          type: object
          nullable: true
        usage:
          type: object
          nullable: true
        charge_lines:
          type: array
          items:
            type: object
            properties:
              item:
                type: string
              quantity:
                type: string
              unit:
                type: string
                enum: [TOKEN]
              rate_unit:
                type: string
                enum: [CREDITS_PER_MILLION_TOKENS]
              rate:
                type: string
              exactCredits:
                type: string
              displayCredits:
                type: string
        observed_at:
          type: string
          format: date-time
    KeyBudgetState:
      type: object
      properties:
        budgetScopeId:
          type: string
          format: uuid
        policyVersion:
          type: integer
        limitCredits:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Exact decimal Credits; null is unconfirmed and must not be rendered as zero.
        warningRatio:
          type: string
        monthUtc:
          type: string
          pattern: ^\d{4}-\d{2}$
        confirmedConsumption:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Exact decimal Credits; null is unconfirmed and must not be rendered as zero.
        unresolvedHolds:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Exact decimal Credits; null is unconfirmed and must not be rendered as zero.
        remainingCredits:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Exact decimal Credits; null is unconfirmed and must not be rendered as zero.
        pendingOperationId:
          type: string
          format: uuid
          nullable: true
        warningIssued:
          type: boolean
      description: >-
        Stable credential-family scope. Rotations preserve policy, consumption and unresolved holds. UTC month is
        frozen on first reserve, including late settlement.
    KeyBudgetMutation:
      type: object
      additionalProperties: false
      required:
        - limit_credits
        - warning_ratio
      properties:
        limit_credits:
          type: string
          nullable: true
          pattern: ^-?\d+(\.\d+)?$
          description: Public Credits at 1,000,000 Credits per CNY. null explicitly disables hard budget. 0 blocks positive holds. The console accepts CNY and converts it exactly before this request.
        warning_ratio:
          type: string
          pattern: '^0\.\d{1,6}$'
          description: 'Exact decimal warning ratio, strictly greater than 0 and less than 1.'
    KeyBudgetOperation:
      type: object
      properties:
        operationId:
          type: string
          format: uuid
        policyVersion:
          type: integer
        status:
          type: string
          enum:
            - APPLIED
            - REJECTED
            - PENDING
        error:
          type: string
          nullable: true
      additionalProperties: true
      description: After an unreadable ACK or lost response, GET the original operation. No blind new mutation.
    ComponentQuote:
      type: object
      properties:
        currency:
          type: string
          enum: [CNY]
        creditsPerCny:
          type: string
          enum: ['1000000']
        estimatedHoldCny:
          type: string
          description: Exact CNY equivalent of estimatedHoldCredits; not an actual charge.
        contractVersion:
          type: string
          enum:
            - TEXT_COMPONENTS_V2
        priceScope:
          type: string
          enum:
            - UNIFIED
        effectivePriceVersion:
          type: integer
          minimum: 1
        measurementSchema:
          type: string
        estimatedHoldCredits:
          type: string
          description: Prepaid hold in public Credits. Rounded upward to a whole micro Credit; input-tier models reserve using the estimated input tier and settle against the actual whole-request tier within the original prepaid contract.
        outputLimit:
          type: string
        observedAt:
          type: string
          format: date-time
        configRevision:
          type: string
      description: >-
        Reference quote, zero provider execution. Complete original payload is previewed server-side. A new user
        click is required to execute; PRICE_CHANGED always requires re-quote, even for a price decrease.
    PerformanceObservation:
      type: object
      properties:
        scope:
          type: string
          enum:
            - public
            - self
        sample_domain:
          type: string
          enum:
            - accepted_payg_text
        window:
          type: object
          properties:
            start:
              type: string
              format: date-time
            end:
              type: string
              format: date-time
        observed_at:
          type: string
          format: date-time
        groups:
          type: array
          items:
            type: object
            properties:
              profile_id:
                type: string
                format: uuid
              channel_id:
                type: string
              config_revision:
                type: string
              wire:
                type: string
              execution_success_rate:
                $ref: '#/components/schemas/RateObservation'
              provider_success_rate:
                $ref: '#/components/schemas/RateObservation'
              ttft_ms:
                $ref: '#/components/schemas/DistributionObservation'
              output_tps:
                $ref: '#/components/schemas/DistributionObservation'
              counts:
                type: object
                additionalProperties:
                  type: integer
      description: >-
        15-minute window, grouped by exact profile/channel/config revision/wire. Public metrics require 100 valid
        samples per metric and observation within 5 minutes. Private observations never enter public aggregates;
        insufficient/stale performance alone is not execution admission.
    RateObservation:
      type: object
      properties:
        value:
          type: number
          nullable: true
        count:
          type: integer
        status:
          type: string
          enum:
            - READY
            - INSUFFICIENT_SAMPLES
            - STALE
    DistributionObservation:
      type: object
      properties:
        p50:
          type: number
          nullable: true
        p95:
          type: number
          nullable: true
        valid_sample_count:
          type: integer
        status:
          type: string
          enum:
            - READY
            - INSUFFICIENT_SAMPLES
            - STALE
      description: >-
        TTFT is first visible text/tool content, not headers/heartbeat. TPS is null for hidden output or missing
        final counters.
    PaygKeyView:
      type: object
      properties:
        id:
          type: string
          format: uuid
        keyPrefix:
          type: string
        name:
          type: string
        scopes:
          type: string
        subjectType:
          type: string
        credentialKind:
          type: string
        billingMode:
          type: string
        budgetScopeId:
          type: string
          format: uuid
        expiresAt:
          type: string
          format: date-time
          nullable: true
        revokedAt:
          type: string
          format: date-time
          nullable: true
      additionalProperties: true
    TrustedConsoleIdentity:
      type: object
      required: [canonicalUserId, nexusTenantId]
      description: 仅从服务端已认证ADMIN影子用户和受控租户映射导出，Member数字身份不可替代。BFF仍须另查Nexus session核对主体。
      properties:
        canonicalUserId: { type: string, format: uuid }
        nexusTenantId: { type: string }
        expiresAt: { type: string, format: date-time, nullable: true }
    CommonResult:
      type: object
      properties:
        code: { type: integer, description: 0=成功, 非0=业务码 }
        message: { type: string }
        data: {}
    ErrorEnvelope:
      type: object
      description: >
        鉴权/凭证闸失败响应（error 风格）。error 取值见开发者文档 §4.1：
        invalid_api_key / credential_revoked / insufficient_scope / credential_rate_limited /
        credential_not_allowed_here / model_not_in_credential_allowlist / model_not_open /
        issuer_not_consented / invalid_credential_identity / member_agent_keys_disabled 等。
      properties:
        error: { type: string }
        message: { type: string }

    # ===== /v1 兼容层原生错误信封 (刻意不用平台 {code,message,data}) =====
    OpenAIErrorEnvelope:
      type: object
      description: >
        OpenAI 原生错误信封（/v1/models、/v1/chat/completions）。type 取值：
        authentication_error(401) / permission_error(403) / invalid_request_error(400,404) /
        not_found_error(404, /v1 未启用) / subscription_inactive(402, 仅会员委托 Key) /
        insufficient_quota(402) / rate_limit_error(429) / api_error(5xx)。
      properties:
        error:
          type: object
          properties:
            type: { type: string }
            message: { type: string }
            code: { type: string, description: 与 type 同值 }
            param: { type: string, nullable: true }
    AnthropicErrorEnvelope:
      type: object
      description: >
        Anthropic 原生错误信封（/v1/messages）。除标准 type/error 外还附加机器码字段
        errorCode（WINDOW_LIMIT_EXCEEDED / LIMIT_POLICY_DENIED / INSUFFICIENT_BALANCE 等），
        窗口限额另带 windowKind / windowResetAt / windowOverridable。标准客户端会忽略多余字段。
      properties:
        type: { type: string, enum: [error] }
        error:
          type: object
          properties:
            type: { type: string }
            message: { type: string }
        errorCode: { type: string, description: 平台机器码（非 Anthropic 标准字段） }

    # ===== 模型目录 =====
    OpenAIModelList:
      type: object
      description: OpenAI 目录格式（GET /v1/models）
      properties:
        object: { type: string, enum: [list] }
        data:
          type: array
          items: { $ref: '#/components/schemas/OpenAIModelEntry' }
    OpenAIModelEntry:
      type: object
      properties:
        id: { type: string, description: 模型业务标识（请求体 model 字段用它） }
        object: { type: string, enum: [model] }
        created: { type: integer, format: int64, description: "恒为 0（平台不维护模型创建时间）" }
        owned_by: { type: string, description: 模型 provider }
    OpenAPIModelList:
      type: object
      description: 开放模型目录（GET /api/open/v1/models 与 /api/open/v1/catalog/models 共用投影）
      properties:
        object: { type: string, enum: [list] }
        data:
          type: array
          items: { $ref: '#/components/schemas/OpenAPIModelView' }
    OpenAPIModelView:
      type: object
      description: >
        开放目录单条投影（白名单字段，绝不含 endpoint / 密钥 / 内部价）。
        同业务 model_id 可有多个物理 profile；按 UUID 或业务 ID + wire 选择。
        顶层 capabilities 只属于 capabilities_profile_id，不代表每个 wire 的能力相同。
        目录未给出有效价格及ready状态的组合不可据此当作免费或可执行。
      properties:
        id: { type: string, description: 模型行 UUID }
        model_id: { type: string, description: 模型业务标识（调用时的 :id） }
        name: { type: string }
        provider: { type: string }
        context_window: { type: integer }
        max_tokens: { type: integer, description: 首profile的模型输出上限；池③另受1048576硬上界约束 }
        input_modalities:
          type: array
          items: { type: string }
        capabilities: { type: object }
        capabilities_profile_id: { type: string, format: uuid, description: 顶层capabilities所描述的首profile物理UUID }
        profiles:
          type: array
          items:
            type: object
            properties:
              id: { type: string, format: uuid }
              compat_profile: { type: string }
              wire_format: { type: string, enum: [openai, anthropic] }
              provider: { type: string }
              capabilities: { type: object, description: 此profile的EffectiveClientCapabilities投影 }
              chat_runtime_supported: { type: boolean, description: 此profile是否具有对话执行链，不由wire_format推断 }
        supported_formats: { type: array, items: { type: string, enum: [openai, anthropic] } }
        price_status: { type: string, description: "首profile主要能力兼容状态；ready表示当前logical raw source已应用的ACK，实际effective rate/profile在Java预占冻结，非固定global profile UUID；逐模态以pricing_status为准" }
        pricing_status:
          type: object
          description: 逐能力价约状态；只有ready才准入，未知/缺失不得当作已就绪。
          properties:
            TEXT_OUTPUT: { type: string }
            IMAGE: { type: string }
            SECOND: { type: string }
        pricing:
          type: object
          description: >
            对外单价（Credits）：text_output_credits_per_token /
            image_credits_per_image / video_credits_per_second。可包含显式免费合同的0值，
            缺失不代表免费；须同时核对应pricing_status=ready与实际profile能力。
          additionalProperties: { type: number }
        marketing: { type: object }

    # ===== /v1 兼容层请求体 =====
    OpenAIChatCompletionRequest:
      type: object
      description: >
        OpenAI Chat Completions 请求体。模型来自 body 的 model 字段（不是 URL 路径段）；
        本候选池③输出上界1048576，模型更低上限优先，预占估算精确<=2^53-1。
        JSON体Go上限32MiB，实际取nginx/代理/上游与Go限制较低者；不表示当前生产已启用。
        会员权益预算保留自身合同；原生参数只按已支持profile转发，不保证任意额外字段。
      required: [model, messages]
      properties:
        model: { type: string, description: "模型标识；缺失返 400 invalid_request_error" }
        messages:
          type: array
          items: { type: object }
        max_tokens:
          type: integer
          minimum: 0
          description: 池③有效值为1..1048576且不超过模型上限；省略/0冻结模型默认预算（无配置回落1024）；会员原预算合同保留。
        n: { type: integer, description: 池③只支持1，其他值在付费执行前拒绝 }
        thinking:
          type: object
          properties:
            budget_tokens: { type: integer, minimum: 0, description: 池③须有限且不超过有效max_tokens，不接受字符串数字 }
        stream: { type: boolean, description: "true = SSE；池③流尾可含空choices的acosmi_billing_status扩展，最终data: [DONE]恰一次" }
      additionalProperties: true
    AnthropicMessagesRequest:
      type: object
      description: >
        Anthropic Messages 请求体。模型来自 body 的 model 字段；兼容层将其提升为路径参数后
        委托既有 Anthropic 线（裸原生 SSE / 上游 JSON 直通）。
        池③有效max_tokens<=1048576且不超过模型较低上限；thinking.budget_tokens为有限非负整数<=有效max_tokens。
        不支持max_completion_tokens，池③仅n=1；完整预占估算精确<=2^53-1。会员预算保留自身合同。
        Go候选JSON体上限32MiB，实际限制取nginx/代理/上游较低值；不代表当前生产已启用。
      required: [model, messages]
      properties:
        model: { type: string }
        max_tokens: { type: integer, minimum: 0, description: 池③有效值1..1048576且不超过模型上限，省略/0冻结模型默认；会员合同保留 }
        thinking:
          type: object
          properties:
            budget_tokens: { type: integer, minimum: 0, description: 池③须有限且不超过有效max_tokens }
        messages:
          type: array
          items: { type: object }
        stream: { type: boolean }
      additionalProperties: true

    # ===== 会员委托 Key 控制面 =====
    CreateAgentAccessKeyRequest:
      type: object
      description: >
        会员委托 Key 签发请求体。刻意没有 billingMode / credentialKind 字段——资金来源由端点决定
        （服务端固定写 MEMBER_ENTITLEMENT + MEMBER_KEY），客户端不可表达。
      required: [name]
      properties:
        name: { type: string, description: 凭证名称（必填） }
        targetAgent: { type: string, description: 目标智能体名（归因 / 批量吊销用） }
        purpose: { type: string, description: 用途标签（仅审计与控制台展示） }
        scopes: { type: string, description: "空格分隔；空 = models:chat；仅 BASIC 档 scope 合法" }
        expiresDays:
          type: integer
          enum: [30, 60, 90]
          default: 90
          description: "有效期天数；缺省或取值非法 → 90（硬上限，不允许永不过期）"
        models:
          type: array
          description: "模型 allowlist，最多 64 项；留空 = 不额外限制（仍受套餐白名单约束）"
          items: { type: string }
        rateLimitRpm: { type: integer, description: "per-Key RPM；默认 120，可下调不可上调" }
        concurrencyLimit: { type: integer, description: "per-Key 并发；默认 8，可下调不可上调" }
    AgentAccessKey:
      type: object
      description: 凭证行公共投影（不含 key_hash / 明文 / pepper_kid / policy_json）
      properties:
        id: { type: string }
        userId: { type: string }
        tenantId: { type: string }
        name: { type: string }
        keyPrefix: { type: string, description: "sk-acm- + 后 4 位，用于列表识别" }
        subjectType: { type: string, enum: [INDIVIDUAL, ENTERPRISE], description: "会员委托 Key 恒为 INDIVIDUAL" }
        scopes: { type: string }
        billingMode: { type: string, enum: [MEMBER_ENTITLEMENT, API_CREDITS] }
        credentialKind: { type: string, enum: [MEMBER_KEY, PAYG_KEY] }
        purpose: { type: string }
        clientId: { type: string, description: 签发该 Key 的 OAuth client }
        targetAgent: { type: string }
        allowedModelIds: { type: string, description: "模型 allowlist（JSON 数组字符串）；空 = 不额外限制" }
        rateLimitRpm: { type: integer }
        concurrencyLimit: { type: integer }
        lastUsedAt: { type: string, format: date-time }
        expiresAt: { type: string, format: date-time, description: "会员委托 Key 必有值（≤90 天）" }
        revokedAt: { type: string, format: date-time }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    AgentAccessKeyCreateResult:
      type: object
      description: 签发 / 轮换成功响应的 data（明文仅此一次）
      properties:
        key: { $ref: '#/components/schemas/AgentAccessKey' }
        plaintext: { type: string, description: "一次性明文 sk-acm-...，不可二次查看" }
    AgentAccessKeyUsage:
      type: object
      description: >
        单凭证用量聚合（数据源 managed_model_usage_logs 的 credential_id 归因列）——
        观测口径，不是账单；账单真相在营销系统 consume_records。
      properties:
        days: { type: integer }
        rows:
          type: array
          items:
            type: object
            properties:
              modelId: { type: string }
              calls: { type: integer, format: int64 }
              inputTokens: { type: integer, format: int64 }
              outputTokens: { type: integer, format: int64 }

    CreateAPIKeyRequest:
      type: object
      required: [name]
      properties:
        name: { type: string, description: Key 名称（必填） }
        scopes: { type: string, description: "空格分隔 scope；空=models:chat" }
        subjectType:
          type: string
          enum: [INDIVIDUAL, ENTERPRISE]
          description: "空=INDIVIDUAL；ENTERPRISE 需 enterpriseId、同租户可信OWNER与人工批准，未获批准返41002"
        enterpriseId: { type: integer, format: int64, minimum: 1, description: "subjectType=ENTERPRISE时必填，来自本人已批准的企业身份" }
        expiresAt: { type: string, format: date-time, description: "RFC3339；空=永不过期" }
    ComplianceBillingRequest:
      type: object
      description: 认证/法律询价请求；SKU 必须来自当前 active 目录，客户端不能指定资金归属。
      required: [skuCode]
      properties:
        skuCode: { type: string, description: 计费 SKU 码 }
        benefitType: { type: string }
        quantity: { type: integer, minimum: 1 }
        envelopeId: { type: string }
        regionScope: { type: string, enum: [CN, OS, GLOBAL] }
    ComplianceReserveRequest:
      type: object
      description: 预占绑定服务端身份、SKU、预算和不可变价约；客户端快照字段不是收费权威。
      required: [billingGroupId, skuCode]
      properties:
        billingGroupId: { type: string }
        idempotencyKey: { type: string }
        skuCode: { type: string }
        quantity: { type: integer, minimum: 1 }
        benefitType: { type: string }
        envelopeId: { type: string }
        priceSnapshotJson: { type: string, description: 从询价响应传回的合同关联，不得伪造或按当前套餐覆盖历史 }
        amountSnapshot: { type: number, description: 客户端值不替代服务端资金合同 }
    ComplianceCommitRequest:
      type: object
      description: 仅与本人预占和内部可信执行记录匹配的提交可结算；客户端自报 provider 成功不构成执行证明。
      required: [billingGroupId]
      properties:
        billingGroupId: { type: string }
        reservationId: { type: string }
        idempotencyKey: { type: string }
        executionProofId: { type: string, description: 受控内部执行凭据，不能由客户端编造 }
        providerRequestId: { type: string }
        providerStatusSnapshot: { type: string, description: 兼容字段，需与内部执行事实一致 }
        localVerificationStatus: { type: string, description: 兼容字段，需与内部执行事实一致 }
    ApiCreditSummary:
      type: object
      required: [actualCredits, reservedCredits, pendingCredits, refundedCredits, adjustmentCredits]
      properties:
        actualCredits: { type: string, description: 筛选期间实际结算 Credits }
        reservedCredits: { type: string, description: 筛选期间当前预占金额 }
        pendingCredits: { type: string, description: 待核对金额，可与预占重叠，不能视为免费 }
        refundedCredits: { type: string, description: 已退款或消费冲正金额 }
        adjustmentCredits: { type: string, description: 平台承担费用或其追加调整，不改变客户余额 }
    ConsoleOrder:
      type: object
      properties:
        id:
          type: string
        bizOrderId:
          type: string
        productName:
          type: string
        amountCent:
          type: integer
          format: int64
        productFamily:
          type: string
        purchaseKind:
          type: string
          description: 企业订阅使用 ENTERPRISE_SUBSCRIPTION，不能仅靠资金数值推断归属
        payStatus:
          type: string
        issueStatus:
          type: string
          description: ACTIVE 才是原有权益/额度已履约事实
        activationStatus:
          type: string
          description: 会员或团队订阅另有激活事实；不套用为池③订阅激活
        orderStatus:
          type: string
        refundStatus:
          type: string
        apiBaseCredits:
          type: string
          nullable: true
        apiBonusCredits:
          type: string
          nullable: true
        payPayload:
          type: object
          properties:
            qrCodeUrl:
              type: string
              description: 支付渠道二维码内容，不一定是图片 URL
            payUrl:
              type: string
              format: uri
            expiresAt:
              type: string
              format: date-time
            bankTransferInfo:
              type: object
        continuationPath:
          type: string
          nullable: true
          maxLength: 1024
          description: >-
            API_CREDITS owner-bound canonical /console/playground?model=m-key&profile=UUID&wire=openai|anthropic
            only. No secrets/prompt/identity/unknown query. Only FULFILLED exposes manual return; never
            auto-execute.
    ApiCreditPage:
      type: object
      required: [list, total, summary]
      properties:
        list: { type: array, items: { type: object }, description: 完整流水或持久计量事件；原金额精度为十进制字符串 }
        total: { type: integer, format: int64 }
        summary: { $ref: '#/components/schemas/ApiCreditSummary' }


    # ===== 电子认证执行端点请求体（核对真实 Java DTO） =====
    EvidenceAssetCreateReq:
      type: object
      description: 证据资产创建请求体（EvidenceAssetCreateReq.java）
      required: [assetType, hashAlgorithm]
      properties:
        assetType: { type: string, description: "AssetTypeEnum name()，如 OTHER / HASH_ONLY" }
        name: { type: string }
        mimeType: { type: string }
        hashAlgorithm: { type: string, enum: [sha256, sha512, sm3], description: hash 算法 wire 值 }
        declaredHash: { type: string, description: "客户端声明 hash(hex)；hash-only 资产必填" }
        digestSource: { type: string, enum: [CLIENT, COMPLIANCE_SERVICE, PROVIDER] }
        contentBase64: { type: string, description: "原文 base64；hash-only 时留空" }
        privacyLevel: { type: string, enum: [public, private], description: "默认 private；仅 public 可被公开 verify" }
        source: { type: string }
    TimestampIssueReq:
      type: object
      description: 通用时间戳签发请求体（TimestampController.TimestampIssueReq）
      required: [hashAlgorithm]
      properties:
        name: { type: string }
        mimeType: { type: string }
        hashAlgorithm: { type: string, enum: [sha256, sha512, sm3] }
        digest: { type: string, description: "客户端声明 digest(hex)；contentBase64 空时即以此签戳" }
        contentBase64: { type: string, description: "原文 base64；与 digest 二选一" }
    TimestampVerifyReq:
      type: object
      required: [tokenId]
      properties:
        tokenId: { type: integer, format: int64, description: 待验证的时间戳令牌 id }
    ContractTemplateCreateReq:
      type: object
      description: 合同模板创建请求体（ContractTemplateCreateReq.java，落 DRAFT）
      required: [name]
      properties:
        name: { type: string, description: 模板名称 }
        description: { type: string }
        fields:
          type: array
          description: 字段模型（ContractTemplateFieldVO 列表，可空）
          items: { type: object }
    ContractTemplateUpdateReq:
      type: object
      description: 合同模板更新请求体（仅 DRAFT；字段缺省=保持原值，name 空字符串非法）
      properties:
        name: { type: string }
        description: { type: string }
        fields:
          type: array
          items: { type: object }
    PdfUploadReq:
      type: object
      description: 模板 PDF 上传请求体（解码后 ≤12MiB，前 5 字节须为 %PDF-）
      required: [pdfBase64]
      properties:
        pdfBase64: { type: string, description: PDF 字节的 base64 编码 }
    ReportCreateReq:
      type: object
      description: 报告创建请求体（assetId / packageId 至少给其一）
      properties:
        assetId: { type: integer, format: int64 }
        packageId: { type: integer, format: int64 }
    CreateEnvelopeCommand:
      type: object
      description: >
        签署信封创建请求体（CreateEnvelopeCommand）。tenantId / applicantUserId 由服务端从 token 注入并覆盖；
        providerProduct 字段存在但创建路径不透传（设置无效）。
      properties:
        subjectSnapshotId: { type: integer, format: int64 }
        envelopeNo: { type: string, description: "信封业务编号，可空则服务端生成" }
        requestId: { type: string }
        idempotencyKey: { type: string, description: "body 幂等键（也可用 Idempotency-Key 头，头优先）" }
        billingGroupId: { type: string }
        chainId: { type: string }
    VoidEnvelopeCommand:
      type: object
      description: >
        信封作废请求体。仅 reason / requestId 为调用方可设，其余服务端注入。
        仅允许从 DRAFT / CONTRACT_READY / APPROVED 作废。
      properties:
        reason: { type: string, maxLength: 500, description: "作废原因，最大 500 字符" }
        requestId: { type: string }
    SealApprovalSubmitCommand:
      type: object
      description: >
        用印审批提交请求体。tenantId / applicantUserId 服务端注入；idempotencyKey 仅从
        Idempotency-Key 头注入（不接受 body）。
      properties:
        envelopeId: { type: integer, format: int64 }
        contractId: { type: integer, format: int64 }
        contractHash: { type: string }
        hashAlgorithm: { type: string }
        sealId: { type: integer, format: int64 }
        approverUserId: { type: string }
        transactorId: { type: integer, format: int64 }
        signLocationType: { type: string }
        signLocationPayload: { type: string }
        reason: { type: string }

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      schema: { type: string }
      description: "写端点可选幂等键；创建类真正消费去重，状态机类规整不消费。"
    PageNo:
      name: pageNo
      in: query
      required: false
      schema: { type: integer, default: 1, minimum: 1 }
      description: 页码，从 1 开始
    PageSize:
      name: pageSize
      in: query
      required: false
      schema: { type: integer, default: 10, minimum: 1, maximum: 200 }
      description: 每页条数，最大 200
    CreateTimeStart:
      name: createTimeStart
      in: query
      required: false
      schema: { type: string }
      description: "创建时间区间起（闭区间），格式 yyyy-MM-dd HH:mm:ss"
    CreateTimeEnd:
      name: createTimeEnd
      in: query
      required: false
      schema: { type: string }
      description: "创建时间区间止（闭区间），格式 yyyy-MM-dd HH:mm:ss"

  responses:
    Unauthorized:
      description: >
        401。error=invalid_api_key（凭证无效 / 反查失败 / 法律端点非 sk-）或
        credential_revoked（已吊销 / 已过期 / 属主用户已失效）或
        invalid_credential_identity（身份域不合规，不可用于计费）。
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorEnvelope' }
    Forbidden:
      description: >
        403。error=insufficient_scope / sku_scope_mismatch（越权 SKU）/
        credential_not_allowed_here（会员委托 Key 打到 /api/open/v1/*）/
        model_not_in_credential_allowlist / model_not_open / issuer_not_consented；
        或平台业务码 41001（未实名）/ 41002（企业 KYC 占位）。
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorEnvelope' }
    CredentialRateLimited:
      description: >
        429。用户级命名桶（chat/media/vector，跨 /api/v4、/api/open/v1、/v1 共用同一只桶，默认 500/min）
        或 per-Key 闸（error=credential_rate_limited，带 Retry-After：RPM 超限 60s / 并发超限 5s）。
      headers:
        Retry-After:
          schema: { type: string }
          description: 建议退避秒数
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorEnvelope' }
    OpenAINativeError:
      description: OpenAI 原生错误信封（详见开发者文档 §4.1）
      content:
        application/json:
          schema: { $ref: '#/components/schemas/OpenAIErrorEnvelope' }
    AnthropicNativeError:
      description: Anthropic 原生错误信封（详见开发者文档 §4.1）
      content:
        application/json:
          schema: { $ref: '#/components/schemas/AnthropicErrorEnvelope' }

paths:
  /api/open/v1/catalog/entries:
    get:
      summary: Public canonical model catalog
      security: []
      parameters: []
      responses:
        '200':
          description: Anonymous raw projection; fixed public tenant.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PortalCatalog'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      description: >-
        No provider or financial writes. Cache-Control public,max-age=30 and ETag; 304 on matching validator.
        Visibility does not imply admitted execution.
  /api/open/v1/catalog/entries/{publicKey}:
    get:
      summary: Public model detail
      security: []
      parameters:
        - name: publicKey
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Anonymous raw projection; fixed public tenant.
          content:
            application/json:
              schema:
                type: object
                properties:
                  version:
                    type: string
                  observed_at:
                    type: string
                    format: date-time
                  data:
                    $ref: '#/components/schemas/PortalEntry'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
  /api/open/v1/catalog/entries/{publicKey}/performance:
    get:
      summary: Public accepted PAYG text observations
      security: []
      parameters:
        - name: publicKey
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Anonymous raw projection; fixed public tenant.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PerformanceObservation'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
  /api/v4/open-api-playground/chat:
    post:
      summary: Composite session and own PAYG Key execution
      security:
        - loginBearer: []
          playgroundKey: []
      parameters:
        - name: X-Request-ID
          in: header
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Native selected-wire JSON or transparent SSE. Track both IDs independently.
          headers:
            X-Request-ID:
              schema:
                type: string
                format: uuid
            X-Acosmi-Request-Id:
              schema:
                type: string
                format: uuid
          content:
            application/json:
              schema:
                type: object
            text/event-stream:
              schema:
                type: string
        '401':
          description: Missing, revoked or expired session / Key
        '409':
          description: Principal mismatch, stale acceptance or PRICE_CHANGED; do not auto-resubmit
        '422':
          description: Output or charge cap rejected
        '503':
          description: Execution or finance outcome requires checking by original IDs
      description: >-
        Both canonical tenant/user principals are independently verified before Key billing context is set. One
        provider attempt. No automatic POST retry/refresh. X-Request-ID is transport tracking;
        X-Acosmi-Request-Id is consumption. Native JSON or SSE; terminal delivery is not a financial receipt.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PlaygroundRequest'
  /api/v4/open-api-requests/{consumeRequestId}:
    get:
      summary: Own immutable execution and financial association
      security:
        - loginBearer: []
      parameters:
        - name: consumeRequestId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/ConsumeRequestDetail'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
  /api/v4/open-api-requests:
    get:
      summary: Own records by original transport tracking UUID
      security:
        - loginBearer: []
      parameters:
        - name: transport_request_id
          in: query
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          data:
                            type: array
                            items:
                              $ref: '#/components/schemas/ConsumeRequestDetail'
                          observed_at:
                            type: string
                            format: date-time
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
  /api/v4/open-api-analytics/performance:
    get:
      summary: Private accepted PAYG text observations
      security:
        - loginBearer: []
      parameters: []
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/PerformanceObservation'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
  /api/v4/open-api-keys/{id}/rotate:
    post:
      summary: Rotate own PAYG Key while preserving budget scope
      security:
        - loginBearer: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          key:
                            $ref: '#/components/schemas/PaygKeyView'
                          plaintext:
                            type: string
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      description: >-
        Old credential stops admitting new calls. Original holds/history and shared UTC budget remain. New
        plaintext returned once; no model execution.
  /api/v4/open-api-keys/{id}/budget:
    get:
      summary: Own current monthly credential-family budget
      security:
        - loginBearer: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/KeyBudgetState'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
    put:
      summary: Explicit idempotent monthly policy mutation
      security:
        - loginBearer: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
        - name: Idempotency-Key
          in: header
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/KeyBudgetOperation'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/KeyBudgetMutation'
  /api/v4/open-api-keys/{id}/budget/operations/{operationId}:
    get:
      summary: Query original budget mutation without a new PUT
      security:
        - loginBearer: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
        - name: operationId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/KeyBudgetOperation'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
  /api/distribution/api-credit/quote:
    post:
      summary: Own complete payload reference quote; zero provider execution
      security:
        - consoleBearer: []
      parameters: []
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/ComponentQuote'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
                - executionProfileId
                - payload
              properties:
                executionProfileId:
                  type: string
                  format: uuid
                payload:
                  type: object
                  description: Complete native text parameters, not client-reported token estimates/schema/model identity.
  /api/distribution/api-credit/requests/{consumeRequestId}:
    get:
      summary: Own Java immutable financial association
      security:
        - consoleBearer: []
      parameters:
        - name: consumeRequestId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        type: object
                        description: >-
                          Camel-case
                          associationStatus/consumeRequestId/financialStatus/reservedCredits/customerChargedCredits/contractualCredits/platformCoveredCredits/observedAt/reservation/finalization/usage/chargeLines.
                          Unknown money is null; old unprovable associations are UNRESOLVED.
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
  /zhuanqian/api/console/playground/chat:
    post:
      summary: Same-origin browser execution bridge
      security:
        - consoleBearer: []
          nexusCookie: []
          playgroundKey: []
      parameters:
        - name: X-Request-ID
          in: header
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Native selected-wire JSON or transparent SSE. Track both IDs independently.
          headers:
            X-Request-ID:
              schema:
                type: string
                format: uuid
            X-Acosmi-Request-Id:
              schema:
                type: string
                format: uuid
          content:
            application/json:
              schema:
                type: object
            text/event-stream:
              schema:
                type: string
        '401':
          description: Missing, revoked or expired session / Key
        '409':
          description: Principal mismatch, stale acceptance or PRICE_CHANGED; do not auto-resubmit
        '422':
          description: Output or charge cap rejected
        '503':
          description: Execution or finance outcome requires checking by original IDs
      description: >-
        Physical default basePath. Browser sends current Java bearer, HttpOnly Nexus cookie and memory-only Key.
        Fixed Go destination and dedicated ReadableStream, no management JSON buffering/retry. Requires measured
        GO_MODEL_EXECUTION_TIMEOUT_MS <=3600000 and BFF deadline >=Go+30000. Only same-origin writes;
        reverse-proxy deployments can fix CONSOLE_PUBLIC_ORIGIN.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PlaygroundRequest'
  /zhuanqian/products:
    get:
      summary: Legacy shared model-store redirect for both consumer themes
      security: []
      responses:
        '307':
          description: Fixed relative Location /zh/models. Query discarded; no Referer-based theme selection.
          headers:
            Location:
              schema:
                type: string
                enum:
                  - /zh/models
    head:
      summary: HEAD for legacy fixed model-store redirect
      security: []
      responses:
        '307':
          description: Location /zh/models, no query.
  /zhuanqian/api/console/requests/{consumeRequestId}:
    get:
      summary: Own immutable execution and financial association
      security:
        - consoleBearer: []
          nexusCookie: []
      parameters:
        - name: consumeRequestId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/ConsumeRequestDetail'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      description: >-
        Same-principal Java session → verified Nexus bearer; fixed Go path, no-store. Historical queries require
        no Key plaintext.
  /zhuanqian/api/console/requests:
    get:
      summary: Own records by original transport tracking UUID
      security:
        - consoleBearer: []
          nexusCookie: []
      parameters:
        - name: transport_request_id
          in: query
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          data:
                            type: array
                            items:
                              $ref: '#/components/schemas/ConsumeRequestDetail'
                          observed_at:
                            type: string
                            format: date-time
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      description: >-
        Same-principal Java session → verified Nexus bearer; fixed Go path, no-store. Historical queries require
        no Key plaintext.
  /zhuanqian/api/console/analytics/performance:
    get:
      summary: Private accepted PAYG text observations
      security:
        - consoleBearer: []
          nexusCookie: []
      parameters: []
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/PerformanceObservation'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      description: >-
        Same-principal Java session → verified Nexus bearer; fixed Go path, no-store. Historical queries require
        no Key plaintext.
  /zhuanqian/api/console/keys/{id}/budget:
    get:
      summary: Own current monthly credential-family budget
      security:
        - consoleBearer: []
          nexusCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/KeyBudgetState'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      description: >-
        Same-principal Java session → verified Nexus bearer; fixed Go path, no-store. Historical queries require
        no Key plaintext.
    put:
      summary: Explicit idempotent monthly policy mutation
      security:
        - consoleBearer: []
          nexusCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
        - name: Idempotency-Key
          in: header
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/KeyBudgetOperation'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/KeyBudgetMutation'
      description: >-
        Same-principal Java session → verified Nexus bearer; fixed Go path, no-store. Historical queries require
        no Key plaintext.
  /zhuanqian/api/console/keys/{id}/budget/operations/{operationId}:
    get:
      summary: Query original budget mutation without a new PUT
      security:
        - consoleBearer: []
          nexusCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
        - name: operationId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/KeyBudgetOperation'
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      description: >-
        Same-principal Java session → verified Nexus bearer; fixed Go path, no-store. Historical queries require
        no Key plaintext.
  /zhuanqian/api/open-api-keys/{id}/rotate:
    post:
      summary: Rotate own PAYG Key while preserving budget scope
      security:
        - consoleBearer: []
          nexusCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          key:
                            $ref: '#/components/schemas/PaygKeyView'
                          plaintext:
                            type: string
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      description: >-
        Same-principal Java session → verified Nexus bearer; fixed Go path, no-store. Historical queries require
        no Key plaintext. Old credential stops admitting new calls. Original holds/history and shared UTC budget
        remain. New plaintext returned once; no model execution.
  /api/v4/managed-models/{id}/components-price:
    get:
      summary: ADMIN customer component desired source and ACK (no purchase prices)
      security:
        - loginBearer: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          source:
                            type: object
                            properties:
                              model_id:
                                type: string
                              contract_version:
                                type: string
                              price_scope:
                                type: string
                              measurement_schema:
                                type: string
                              rates:
                                $ref: '#/components/schemas/ComponentRates'
                              free_reason:
                                type: string
                              withdrawn:
                                type: boolean
                              source_version:
                                type: integer
                              source_digest:
                                type: string
                              ack_version:
                                type: integer
                              ack_digest:
                                type: string
                              effective_price_version:
                                type: integer
                              last_error:
                                type: string
                              updated_at:
                                type: string
                                format: date-time
                            nullable: true
                          ready:
                            type: boolean
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
    put:
      summary: ADMIN desired V2 source update; independent from V1
      security:
        - loginBearer: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Platform code:0/data envelope; no-store for personal data.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          source:
                            type: object
                            properties:
                              model_id:
                                type: string
                              contract_version:
                                type: string
                              price_scope:
                                type: string
                              measurement_schema:
                                type: string
                              rates:
                                $ref: '#/components/schemas/ComponentRates'
                              free_reason:
                                type: string
                              withdrawn:
                                type: boolean
                              source_version:
                                type: integer
                              source_digest:
                                type: string
                              ack_version:
                                type: integer
                              ack_digest:
                                type: string
                              effective_price_version:
                                type: integer
                              last_error:
                                type: string
                              updated_at:
                                type: string
                                format: date-time
                          ready:
                            type: boolean
        '503':
          description: Dependency / receipt unavailable; never infer free, zero balance or operation success.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
                - measurement_schema
                - rates
                - free_reason
                - withdrawn
              properties:
                measurement_schema:
                  type: string
                  enum:
                    - OPENAI_GROSS_READ_V1
                    - ANTHROPIC_NET_CACHE_V1
                rates:
                  type: object
                  additionalProperties:
                    type: string
                  description: All four rates for publication; exactly {} for withdrawal.
                free_reason:
                  type: string
                  description: Required if any rate is zero
                withdrawn:
                  type: boolean
      description: >-
        Source save is not release acceptance. ACK failure remains sync_pending. Shared ModelID / UNIFIED
        domain; no channel price differences or supplier purchase-price fields.
  /api/auth/identity:
    get:
      summary: 查询当前Java会话可信Nexus主体映射
      security: [{ consoleBearer: [] }]
      responses:
        '200':
          description: 本人受控映射，不能用客户端提供的user/tenant字段覆盖
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: '#/components/schemas/CommonResult' }
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/TrustedConsoleIdentity' }
        '401': { description: Java会话或影子身份已失效 }
        '403': { description: MEMBER或未关联Nexus的本地Admin身份不受支持 }
        '503': { description: 身份依赖暂不可用，不猜测身份 }
  /api/auth/logout:
    post:
      summary: 撤销本人提供的Java访问及关联刷新凭证
      description: 支持清理已过期但仍存储的access凭证。浏览器控制台经统一BFF同时退出Nexus cookie会话。
      security: [{ consoleBearer: [] }]
      responses:
        '200': { description: 本人所持凭证已撤销或已不存在 }
  /api/open/v1/capabilities:
    get:
      summary: 现有 scope 与能力的只读就绪投影
      security: []
      description: ready 仅表示对应执行链已启用，不替代具体 model/profile 价约或生产业务验收。
      responses:
        '200':
          description: 平台 CommonResult 信封
          content:
            application/json:
              schema:
                type: object
                properties:
                  code: { type: integer }
                  message: { type: string }
                  data:
                    type: object
                    properties:
                      scopes:
                        type: array
                        items:
                          type: object
                          properties:
                            scope: { type: string }
                            tier: { oneOf: [{ type: integer }, { type: string }] }
                            ready: { type: boolean }
                            reason: { type: string }
                      enterpriseKeyReady: { type: boolean }
                      compatV1Enabled: { type: boolean }
                      memberAgentKeysEnabled: { type: boolean }
                      memberAgentKeyIssuanceEnabled: { type: boolean, description: "新签发/轮换开关，与存量查询/吊销和调用开关分别约束" }
  /api/consumer/orders/{orderId}:
    get:
      summary: 查询本人订单的付款与实际履约
      security: [{ consoleBearer: [] }]
      parameters:
        - { name: orderId, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200':
          description: Java CommonResult，code=0 的 data 为 ConsoleOrder；同步回跳不代表到账
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CommonResult' }
        '404': { description: 不存在或不属于本人/租户 }
  /api/distribution/api-credit/bills/page:
    get:
      summary: 完整期间账单流水分页与期间汇总
      security:
        - consoleBearer: []
      parameters:
        - name: startTime
          in: query
          schema:
            type: string
            format: date-time
          description: UTC Instant，开始含
        - name: endTime
          in: query
          schema:
            type: string
            format: date-time
          description: UTC Instant，结束不含
        - name: apiKeyId
          in: query
          schema:
            type: string
        - name: modelId
          in: query
          schema:
            type: string
        - name: requestId
          in: query
          schema:
            type: string
        - name: source
          in: query
          schema:
            type: string
        - name: status
          in: query
          schema:
            type: string
        - name: pageNo
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: pageSize
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 50
        - name: consumeRequestId
          in: query
          required: false
          schema:
            type: string
            format: uuid
          description: Persistent consumption association; requestId remains the billing/usage event ID.
      responses:
        '200':
          description: Java CommonResult 的 data 为 ApiCreditPage；汇总不是本页累加
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CommonResult'
  /api/distribution/api-credit/bills/export:
    get:
      summary: 同筛选完整 CSV 导出（最多100000条）
      security:
        - consoleBearer: []
      parameters:
        - name: startTime
          in: query
          schema:
            type: string
            format: date-time
          description: UTC Instant，开始含
        - name: endTime
          in: query
          schema:
            type: string
            format: date-time
          description: UTC Instant，结束不含
        - name: apiKeyId
          in: query
          schema:
            type: string
        - name: modelId
          in: query
          schema:
            type: string
        - name: requestId
          in: query
          schema:
            type: string
        - name: source
          in: query
          schema:
            type: string
        - name: status
          in: query
          schema:
            type: string
        - name: consumeRequestId
          in: query
          required: false
          schema:
            type: string
            format: uuid
          description: Persistent consumption association; requestId remains the billing/usage event ID.
      responses:
        '200':
          description: 服务端同一 PostgreSQL 快照下完整筛选；防 CSV 公式注入
          content:
            text/csv:
              schema:
                type: string
        '409':
          description: 期间超出导出上限或合同冲突，请缩窄筛选
  /api/distribution/api-credit/usage/page:
    get:
      summary: 持久计量事件分页与期间汇总
      security:
        - consoleBearer: []
      parameters:
        - name: startTime
          in: query
          schema:
            type: string
            format: date-time
          description: UTC Instant，开始含
        - name: endTime
          in: query
          schema:
            type: string
            format: date-time
          description: UTC Instant，结束不含
        - name: apiKeyId
          in: query
          schema:
            type: string
        - name: modelId
          in: query
          schema:
            type: string
        - name: requestId
          in: query
          schema:
            type: string
        - name: source
          in: query
          schema:
            type: string
        - name: status
          in: query
          schema:
            type: string
        - name: pageNo
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: pageSize
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 50
        - name: consumeRequestId
          in: query
          required: false
          schema:
            type: string
            format: uuid
          description: Persistent consumption association; requestId remains the billing/usage event ID.
      responses:
        '200':
          description: Java CommonResult 的 data 为 ApiCreditPage；汇总不是本页累加
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CommonResult'
  /api/distribution/api-credit/usage/export:
    get:
      summary: 同筛选完整 CSV 导出（最多100000条）
      security:
        - consoleBearer: []
      parameters:
        - name: startTime
          in: query
          schema:
            type: string
            format: date-time
          description: UTC Instant，开始含
        - name: endTime
          in: query
          schema:
            type: string
            format: date-time
          description: UTC Instant，结束不含
        - name: apiKeyId
          in: query
          schema:
            type: string
        - name: modelId
          in: query
          schema:
            type: string
        - name: requestId
          in: query
          schema:
            type: string
        - name: source
          in: query
          schema:
            type: string
        - name: status
          in: query
          schema:
            type: string
        - name: consumeRequestId
          in: query
          required: false
          schema:
            type: string
            format: uuid
          description: Persistent consumption association; requestId remains the billing/usage event ID.
      responses:
        '200':
          description: 服务端同一 PostgreSQL 快照下完整筛选；防 CSV 公式注入
          content:
            text/csv:
              schema:
                type: string
        '409':
          description: 期间超出导出上限或合同冲突，请缩窄筛选
  /api/open/v1/ping:
    get:
      summary: 探活（验证 Key 链路）
      security: [{ apiKey: [] }]
      description: "需 scope models:chat。返回 { ok, userId, keyId }"
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/models:
    get:
      summary: 开放模型列表
      security: [{ apiKey: [] }]
      description: >
        需 scope models:chat。过滤条件仅 is_enabled && open_api_enabled（按租户），
        价格不参与过滤——未定价模型照样出现且 pricing 为空对象。
        会员委托 Key 打本组返 403 credential_not_allowed_here。
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OpenAPIModelList' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/catalog/models:
    get:
      summary: 匿名公开模型目录（无需鉴权）
      security: []
      description: >
        匿名公开端点（控制台「产品与定价」页 + 营销系统反代消费）。
        固定公开目录租户下 is_enabled && open_api_enabled，字段投影同 /api/open/v1/models。
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OpenAPIModelList' }

  /api/open/v1/models/{id}/chat:
    post:
      summary: 模型对话（OpenAI 兼容）
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string }, description: 模型 ID }
      requestBody:
        content: { application/json: { schema: { type: object } } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/CredentialRateLimited' }

  /api/open/v1/models/{id}/anthropic:
    post:
      summary: 模型对话（Anthropic Messages 协议）
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        content: { application/json: { schema: { type: object } } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/CredentialRateLimited' }

  /api/open/v1/models/{id}/images/generations:
    post:
      summary: 图片生成（仅 supports_image_generation 模型）
      description: >
        按目录 IMAGE 价约及服务端准入执行，每次生成 1 张。以真实执行 profile 冻结预占，
        必须提供规范 UUID Idempotency-Key。同键同参数恢复原任务，不重调 provider；
        同键不同参数返回 409。生成结果已收到但资金结算未确认时返回 503 和 taskId，
        不返回 url/b64_json；用原本人及原 API key 查询任务。
        UNKNOWN_IMAGE_V1冻结24h平台责任期限，Java按原预占时刻校验；仍无可信结果时退客户hold并保留UNKNOWN，
        无产物仍503 image_unknown_resolved，不造usage0或重调provider。真实产物迟到须先确认IMAGE=1真实计量，
        客户0扣费、原价约成本由平台承担，再200返回产物，原UNKNOWN保留。
        imageUnknownReady是财务准入前置，部署验收和灰度以运行回执为准。
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, format: uuid }
          description: 规范 UUID；必须在恢复时沿用原值，不能换键重试未知执行。
      requestBody:
        content: { application/json: { schema: { type: object } } }
      responses:
        '200': { description: 原图片结果已确认正常结算，或UNKNOWN后真实迟到量由平台承担并确认，可读取data中的url或b64_json }
        '400': { description: 幂等键/参数无效，或确定未交付且真实释放已确认（data.status=failed） }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '409': { description: 同幂等键参数冲突 }
        '429': { $ref: '#/components/responses/CredentialRateLimited' }
        '503':
          description: >
            image_settle_pending（原结果等待结算）或 image_reconcile_required（上游结果未知）。
            期限前保留预占和taskId，不能换键重调provider。
            24h责任终结后image_unknown_resolved表示客户预占已释放但无产物，不再扣客户费用。
          content:
            application/json:
              schema:
                type: object
                properties:
                  code: { type: integer }
                  message: { type: string }
                  data:
                    type: object
                    properties:
                      taskId: { type: string, format: uuid }
                      status:
                        type: string
                        enum: [image_reserve_intent, image_submitting, image_settle_pending, image_release_pending, image_reconcile_required, image_unknown_pending, image_late_usage_pending, image_unknown_resolved]
                      errorCode: { type: string }

  /api/open/v1/models/{id}/images/tasks/{taskId}:
    get:
      summary: 恢复本人原 API key 的图片任务
      description: >
        不重复执行 provider。原模型撤回、禁用或软删除后仍可按原本人、原API key、UUID及可信冻结origin查询原任务；这不开放新POST。
        完成返回原 ImageGenerationResponse；等待资金确认或上游结果未知返回 503 恢复状态，
        仍不披露未确认图片的url或b64_json。24h image_unknown_resolved但无产物仍503，客户hold已释放；
        真迟到产物先以客户0/全平台承担确认真实量，再200返回并保留原UNKNOWN。
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: taskId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200': { description: 返回已确认的原图片结果，含UNKNOWN后真实迟到且平台承担的产物 }
        '400': { description: 明确失败且真实释放已确认，data.status=failed }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { description: 本人原 key 下未找到匹配任务 }
        '503': { description: 原任务执行/结算待确认，或image_unknown_resolved无产物（客户预占已释放），继续查询原taskId，不重调provider }

  /api/open/v1/models/{id}/videos/generations:
    post:
      description: 新池③调用要求SECOND当前source ACK与财务结构readiness；缺价、未ACK或partial DDL在provider前503。冻结物理profile与服务端duration，幂等键为canonical UUID。
      summary: 视频生成（仅 supports_video_generation 模型）
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        content: { application/json: { schema: { type: object } } }
      responses:
        '200': { description: 任务已创建 }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/CredentialRateLimited' }
        '503': { description: 目录当前source未ACK、缺价、财务结构未就绪或执行依赖暂不可用；继续使用原canonical UUID核对，不重建另一请求 }

  /api/open/v1/models/{id}/videos/tasks/{taskId}:
    get:
      summary: 视频生成任务状态查询
      description: 按原owner、key、canonical UUID和可信冻结origin读取既有任务；目录停用、撤回或soft-delete后仍可核对原任务，不开放新POST、不重调provider。
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: taskId, in: path, required: true, schema: { type: string } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  # ===== /v1 标准协议兼容层 (2026-08-14) =====
  # 第三方智能体只配 base_url + api_key + model。模型来自 body 的 model 字段, 不是路径段。
  # 受服务端开关 COMPAT_API_V1_ENABLED 控制 (默认关闭 → 原生 404 not_found_error)。
  # 鉴权接受: Authorization: Bearer sk-acm-... / Authorization: Bearer <oauth access token> /
  #          x-api-key: sk-acm-... (受 COMPAT_API_ANTHROPIC_XAPIKEY_ENABLED 控制)。
  # 错误一律原生协议信封, 不是平台 {code,message,data}。
  # 限流两层: 用户级命名桶 (与 /api/v4、/api/open/v1 共用同一只桶) + per-Key RPM/并发闸。
  /v1/models:
    get:
      summary: 模型目录（OpenAI 格式）
      security: [{ apiKey: [] }, { xApiKey: [] }]
      description: >
        需 scope models:chat。集合按资金来源分流：会员委托 Key / 会员登录态 → 会员 exposure
        （租户启用 ∩ 用户权益桶，不受 open_api_enabled 约束，权益查询失败时 fail-open 退回租户目录）；
        按量 Key → open_api_enabled 白名单。两者再 ∩ 该凭证自设的模型 allowlist。
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OpenAIModelList' }
        '401': { $ref: '#/components/responses/OpenAINativeError' }
        '403': { $ref: '#/components/responses/OpenAINativeError' }
        '404': { $ref: '#/components/responses/OpenAINativeError' }
        '500': { $ref: '#/components/responses/OpenAINativeError' }

  /v1/chat/completions:
    post:
      summary: OpenAI Chat Completions（同步 + SSE）
      security: [{ apiKey: [] }, { xApiKey: [] }]
      description: >
        需 scope models:chat。stream=true 时返回上游原生 OpenAI SSE（含 SSE 注释保活帧
        ": keep-alive"，以上游自带的 data: [DONE] 结束，平台不重复补发终止标记）；
        流已开头后无法改状态码，错误以流内一帧 data: {"error":{...}} 送出。
        视频类模型不可走本端点。本层只做协议转换，资金编排复用会员 Hold/Settle/Release 或池③ 预占。
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/OpenAIChatCompletionRequest' }
      responses:
        '200':
          description: OK（上游原生 OpenAI JSON 直通；stream=true 时为 text/event-stream）
          content:
            application/json:
              schema: { type: object }
            text/event-stream:
              schema: { type: string }
        '400':
          description: "invalid_request_error：body 非法 JSON / 缺 model / 视频模型走 chat 线"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OpenAIErrorEnvelope' }
        '401':
          description: "authentication_error：invalid_api_key / credential_revoked / 缺凭证"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OpenAIErrorEnvelope' }
        '402':
          description: >
            subscription_inactive（会员订阅失效，仅会员委托 Key）/
            insufficient_quota（entitlement_exhausted 会员权益不足，或池③ Credits 余额不足）
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OpenAIErrorEnvelope' }
        '403':
          description: "permission_error：insufficient_scope / model_not_in_plan（套餐白名单或档位拒绝）"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OpenAIErrorEnvelope' }
        '404':
          description: "模型不存在 / 已禁用（invalid_request_error）；/v1 未启用时 not_found_error"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OpenAIErrorEnvelope' }
        '429':
          description: >
            rate_limit_error：window_limit_exceeded（会员窗口额度，带 Retry-After 指向窗口恢复点）
            或同用户/模型并发过密；per-Key 限流命中时 type=credential_rate_limited，
            同为本层的原生信封。
          headers:
            Retry-After:
              schema: { type: string }
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/OpenAIErrorEnvelope'
                  - $ref: '#/components/schemas/ErrorEnvelope'
        '500': { $ref: '#/components/responses/OpenAINativeError' }
        '503':
          description: "member_agent_keys_disabled（会员委托 Key 调用开关未开）/ 池③ 预占失败"
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/OpenAIErrorEnvelope'
                  - $ref: '#/components/schemas/ErrorEnvelope'

  /v1/messages:
    post:
      summary: Anthropic Messages（同步 + SSE）
      security: [{ apiKey: [] }, { xApiKey: [] }]
      description: >
        需 scope models:chat。兼容层把 body 的 model 提升为路径参数后委托既有 Anthropic 线：
        流式为裸原生 Anthropic SSE 直通（同样有首字节保活），同步为上游 JSON 原样返回。
        Anthropic 客户端可继续发送 anthropic-version 头（平台透传，不参与鉴权）。
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/AnthropicMessagesRequest' }
      responses:
        '200':
          description: OK（上游原生 Anthropic JSON；stream=true 时为 text/event-stream）
          content:
            application/json:
              schema: { type: object }
            text/event-stream:
              schema: { type: string }
        '400':
          description: "invalid_request_error：body 非法 JSON / 缺 model"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AnthropicErrorEnvelope' }
        '401':
          description: "authentication_error：invalid_api_key / credential_revoked / 缺凭证"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AnthropicErrorEnvelope' }
        '402':
          description: >
            subscription_inactive（仅会员委托 Key）/
            invalid_request_error + errorCode=INSUFFICIENT_BALANCE（entitlement_exhausted 权益不足）
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AnthropicErrorEnvelope' }
        '403':
          description: "permission_error：insufficient_scope / model_not_in_plan（+errorCode=LIMIT_POLICY_DENIED）"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AnthropicErrorEnvelope' }
        '404': { $ref: '#/components/responses/AnthropicNativeError' }
        '429':
          description: >
            rate_limit_error + errorCode=WINDOW_LIMIT_EXCEEDED（会员窗口额度，带 Retry-After
            与 windowKind / windowResetAt / windowOverridable）或并发过密；
            per-Key 限流命中时 type=credential_rate_limited（同为原生信封）。
          headers:
            Retry-After:
              schema: { type: string }
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/AnthropicErrorEnvelope'
                  - $ref: '#/components/schemas/ErrorEnvelope'
        '500': { $ref: '#/components/responses/AnthropicNativeError' }
        '503':
          description: "member_agent_keys_disabled（会员委托 Key 调用开关未开）"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ErrorEnvelope' }

  # ===== 电子认证 (按件计费, scope compliance:contract_signing:write) =====
  /api/open/v1/compliance/quote:
    post:
      summary: 认证询价
      security: [{ apiKey: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ComplianceBillingRequest' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '501': { description: "SEAL_USAGE 暂不可用 (CFCA gate3)" }

  /api/open/v1/compliance/reserve:
    post:
      summary: 认证预占
      security: [{ apiKey: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ComplianceReserveRequest' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '501': { description: "SEAL_USAGE 暂不可用" }

  /api/open/v1/compliance/commit:
    post:
      summary: 认证提交结算（验证内部执行凭据）
      security: [{ apiKey: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ComplianceCommitRequest' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '501': { description: "SEAL_USAGE 暂不可用" }

  # ===== 法律按量付费 (按件计费, scope legal:consultation|service|advisor 任一) =====
  /api/open/v1/legal/quote:
    post:
      summary: 法律询价
      security: [{ apiKey: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ComplianceBillingRequest' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/legal/reserve:
    post:
      summary: 法律预占
      security: [{ apiKey: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ComplianceReserveRequest' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/legal/commit:
    post:
      summary: 法律提交结算（验证内部执行凭据）
      security: [{ apiKey: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ComplianceCommitRequest' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  # ===== 电子认证执行端点 (Phase H, sk- Key, 细分 scope) =====
  # 完整端点清单 / 不开放能力见 docs/api-open/开放API开发者文档-2026-05-29.md §3A-§3D。
  # 真签署/发布/审批通过(sign/h5-url/reports publish/seal-approvals approve)因 step-up 未接入返 501，
  # 此处刻意不列；印章 CRUD 与 send/remind/PAdES 等 ABSENT 能力亦不列（避免误导）。

  # ---- 存证 evidence ----
  /api/open/v1/compliance/evidence/assets:
    post:
      summary: 创建证据资产
      description: "scope compliance:evidence:write"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/EvidenceAssetCreateReq' }
      responses:
        '200': { description: OK（CommonResult，data=资产公共投影） }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/evidence/assets/{id}:
    get:
      summary: 查证据资产详情
      description: "scope compliance:evidence:read"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/evidence/assets/page:
    get:
      summary: 证据资产分页
      description: "scope compliance:evidence:read"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/PageNo' }
        - { $ref: '#/components/parameters/PageSize' }
        - { name: assetType, in: query, required: false, schema: { type: string } }
        - { name: status, in: query, required: false, schema: { type: string } }
        - { $ref: '#/components/parameters/CreateTimeStart' }
        - { $ref: '#/components/parameters/CreateTimeEnd' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/evidence/assets/{id}/timestamp:
    post:
      summary: 给资产签时间戳
      description: "scope compliance:timestamp:issue。无请求体字段（provider 服务端选择）"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
        - { $ref: '#/components/parameters/IdempotencyKey' }
      responses:
        '200': { description: OK（data=时间戳令牌公共投影） }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/evidence/assets/{id}/packages:
    post:
      summary: 由资产构建证据包
      description: "scope compliance:evidence:write"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
        - { name: timestampTokenId, in: query, required: false, schema: { type: integer, format: int64 } }
        - { $ref: '#/components/parameters/IdempotencyKey' }
      responses:
        '200': { description: OK（data=证据包公共投影） }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/evidence/packages/page:
    get:
      summary: 证据包分页
      description: "scope compliance:evidence:read"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/PageNo' }
        - { $ref: '#/components/parameters/PageSize' }
        - { name: status, in: query, required: false, schema: { type: string } }
        - { $ref: '#/components/parameters/CreateTimeStart' }
        - { $ref: '#/components/parameters/CreateTimeEnd' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/evidence/verify:
    get:
      summary: 公开验真（匿名，无需鉴权）
      description: "PermitAll + 跨租户；仅 privacyLevel=public 的资产可验真"
      parameters:
        - { name: evidenceNo, in: query, required: false, schema: { type: string } }
        - { name: publicVerifyCode, in: query, required: false, schema: { type: string } }
      responses:
        '200': { description: OK（data=验真结果 Map） }

  # ---- 时间戳 timestamps ----
  /api/open/v1/compliance/timestamps:
    post:
      summary: 通用时间戳签发
      description: "scope compliance:timestamp:issue"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TimestampIssueReq' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/timestamps/verify:
    post:
      summary: 时间戳离线验证
      description: "scope compliance:timestamp:verify。data={ passed, reason }"
      security: [{ apiKey: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TimestampVerifyReq' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/timestamps/{id}:
    get:
      summary: 查时间戳详情
      description: "scope compliance:timestamp:verify"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/timestamps/page:
    get:
      summary: 时间戳分页
      description: "scope compliance:timestamp:verify"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/PageNo' }
        - { $ref: '#/components/parameters/PageSize' }
        - { name: provider, in: query, required: false, schema: { type: string } }
        - { name: verificationStatus, in: query, required: false, schema: { type: string } }
        - { $ref: '#/components/parameters/CreateTimeStart' }
        - { $ref: '#/components/parameters/CreateTimeEnd' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  # ---- 合同模板 contract-templates ----
  /api/open/v1/compliance/contract-templates:
    post:
      summary: 创建模板（落 DRAFT）
      description: "scope compliance:contract_template:write"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContractTemplateCreateReq' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/contract-templates/{id}:
    get:
      summary: 模板详情
      description: "scope compliance:contract_template:read"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
    put:
      summary: 更新模板（仅 DRAFT；字段缺省=保持原值）
      description: "scope compliance:contract_template:write（服务端注册为 POST /{id}，对外语义为更新）"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContractTemplateUpdateReq' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/contract-templates/{id}/delete:
    post:
      summary: 删除模板
      description: "scope compliance:contract_template:write"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/contract-templates/{id}/pdf:
    post:
      summary: 上传模板 PDF（仅 DRAFT，≤12MiB，须 %PDF- magic）
      description: "scope compliance:contract_template:write"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PdfUploadReq' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/contract-templates/{id}/publish:
    post:
      summary: 发布模板（DRAFT → PUBLISHED）
      description: "scope compliance:contract_template:write"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/contract-templates/{id}/archive:
    post:
      summary: 归档模板
      description: "scope compliance:contract_template:write"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/contract-templates/page:
    get:
      summary: 模板分页
      description: "scope compliance:contract_template:read"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/PageNo' }
        - { $ref: '#/components/parameters/PageSize' }
        - { name: status, in: query, required: false, schema: { type: string, enum: [DRAFT, PUBLISHED, ARCHIVED] } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/contract-templates/{id}/versions:
    get:
      summary: 模板版本列表（版本号降序）
      description: "scope compliance:contract_template:read"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  # ---- 报告 reports ----
  /api/open/v1/compliance/reports:
    post:
      summary: 创建报告（assetId / packageId 至少其一）
      description: "scope compliance:reports:write"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ReportCreateReq' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/reports/{id}:
    get:
      summary: 报告详情
      description: "scope compliance:reports:read"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/reports/page:
    get:
      summary: 报告分页
      description: "scope compliance:reports:read"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/PageNo' }
        - { $ref: '#/components/parameters/PageSize' }
        - { name: status, in: query, required: false, schema: { type: string, enum: [DRAFT, PUBLISHED] } }
        - { $ref: '#/components/parameters/CreateTimeStart' }
        - { $ref: '#/components/parameters/CreateTimeEnd' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/reports/{id}/download:
    get:
      summary: 离线复核材料下载（ReportDownloadVO）
      description: "scope compliance:reports:read。不返回 bodyCanonicalJson / storage key"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  # ---- 签署信封 signing-envelopes ----
  /api/open/v1/compliance/signing-envelopes:
    post:
      summary: 创建签署信封
      description: "scope compliance:contract_signing:write。data=新建 envelope Long id"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateEnvelopeCommand' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/signing-envelopes/{id}/void:
    post:
      summary: 作废信封（纯本地状态转移）
      description: "scope compliance:contract_signing:write。仅 DRAFT/CONTRACT_READY/APPROVED 可作废"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/VoidEnvelopeCommand' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/signing-envelopes/{id}/sync-provider-status:
    post:
      summary: 对账 provider 状态（只读对账）
      description: "scope compliance:contract_signing:write。无请求体"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
        - { $ref: '#/components/parameters/IdempotencyKey' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/signing-envelopes/{id}:
    get:
      summary: 信封详情（SigningEnvelopePublicVO）
      description: "scope compliance:contract_signing:read"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/signing-envelopes/page:
    get:
      summary: 信封分页
      description: "scope compliance:contract_signing:read"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/PageNo' }
        - { $ref: '#/components/parameters/PageSize' }
        - { name: status, in: query, required: false, schema: { type: string } }
        - { $ref: '#/components/parameters/CreateTimeStart' }
        - { $ref: '#/components/parameters/CreateTimeEnd' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/signing-envelopes/{id}/contracts:
    get:
      summary: 信封下合同附件列表（EnvelopeContractItemVO）
      description: "scope compliance:contract_signing:read"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/signing-envelopes/{id}/provider-requests:
    get:
      summary: 信封下 provider 请求 ledger（OperationPageItemVO 投影）
      description: "scope compliance:contract_signing:read"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  # ---- 用印审批 seal-approvals ----
  /api/open/v1/compliance/seal-approvals:
    post:
      summary: 提交用印审批申请
      description: "scope compliance:seal_approval:request。data=新建审批单 Long id"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/IdempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SealApprovalSubmitCommand' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/seal-approvals/{id}/reject:
    post:
      summary: 驳回审批
      description: "scope compliance:seal_approval:approve"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
        - { name: reason, in: query, required: false, schema: { type: string } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/seal-approvals/{id}/cancel:
    post:
      summary: 取消审批
      description: "scope compliance:seal_approval:request"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
        - { name: reason, in: query, required: false, schema: { type: string } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/seal-approvals/pending:
    get:
      summary: 当前审批人待办（SUBMITTED 列表）
      description: "scope compliance:seal_approval:approve"
      security: [{ apiKey: [] }]
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/seal-approvals/page:
    get:
      summary: 审批单分页
      description: "scope compliance:seal_approval:approve"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/PageNo' }
        - { $ref: '#/components/parameters/PageSize' }
        - { name: status, in: query, required: false, schema: { type: string, enum: [DRAFT, SUBMITTED, APPROVED, REJECTED, CANCELED, USED, EXPIRED] } }
        - { $ref: '#/components/parameters/CreateTimeStart' }
        - { $ref: '#/components/parameters/CreateTimeEnd' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  /api/open/v1/compliance/seal-approvals/{id}:
    get:
      summary: 审批单详情
      description: "scope compliance:contract_signing:read（详情复用 signing read，服务端现状）"
      security: [{ apiKey: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  # ---- 用印记录 seal-uses ----
  /api/open/v1/compliance/seal-uses/page:
    get:
      summary: 用印日志分页（只读）
      description: "scope compliance:contract_signing:read"
      security: [{ apiKey: [] }]
      parameters:
        - { $ref: '#/components/parameters/PageNo' }
        - { $ref: '#/components/parameters/PageSize' }
        - { name: sealId, in: query, required: false, schema: { type: integer, format: int64 } }
        - { name: envelopeId, in: query, required: false, schema: { type: integer, format: int64 } }
        - { name: usageStatus, in: query, required: false, schema: { type: string, enum: [RESERVED, INVOKED, CONSUMED, FAILED, CANCELED] } }
        - { $ref: '#/components/parameters/CreateTimeStart' }
        - { $ref: '#/components/parameters/CreateTimeEnd' }
      responses:
        '200': { description: OK }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

  # ===== 自助 Key 管理 (登录态, 非 sk-) =====
  /api/v4/open-api-keys:
    get:
      summary: 列出当前用户未吊销的 Key
      security: [{ loginBearer: [] }]
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CommonResult' }
    post:
      summary: 签发新 Key（内置实名前置闸 R11，返回一次性明文）
      security: [{ loginBearer: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateAPIKeyRequest' }
      responses:
        '200':
          description: "创建成功，data.plaintext 仅此一次"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CommonResult' }
        '400': { description: 参数错误 / 非法 scope / expiresAt 格式错 }
        '403':
          description: "未绑手机(41001) 或 企业准入未批准(41002)"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CommonResult' }

  /api/v4/open-api-keys/{id}:
    delete:
      summary: 吊销 Key（置 revoked_at，owner 校验）
      security: [{ loginBearer: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        '200': { description: OK }
        '404': { description: API Key 不存在或已吊销 }

  # ===== 会员委托 Key 控制面 (登录态 / 桌面 OAuth scope agent_access:manage) =====
  # 与 /api/v4/open-api-keys 刻意分面: 资金来源由**端点**决定, 请求体没有表达它的语法。
  # 服务端固定写 billing_mode=MEMBER_ENTITLEMENT + credential_kind=MEMBER_KEY。
  # 三道闸: 开关闸 (MEMBER_AGENT_KEY_ISSUANCE_ENABLED) + 签发者同意闸 (拒 web_oauth) + 提权闸 (scope ⊆ 签发者授权 ∩ BASIC 档)。
  /api/v4/agent-access-keys:
    get:
      summary: 列出本人的会员委托 Key
      security: [{ loginBearer: [] }]
      description: 不含 key_hash / 明文。仅返回 credential_kind=MEMBER_KEY 的行。
      responses:
        '200':
          description: OK（CommonResult，data = AgentAccessKey 数组）
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/AgentAccessKey' }
        '403': { description: "issuer_not_consented（web_oauth 签发者被拒）" }
    post:
      summary: 签发会员委托 Key（返回一次性明文）
      security: [{ loginBearer: [] }]
      description: >
        实名前置闸（未绑定手机 → 403 / 41001）+ 签发者同意闸 + 提权闸。
        有效期 30/60/90 天，默认与上限均 90 天，不允许永不过期；单用户有效上限 5 把。
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateAgentAccessKeyRequest' }
      responses:
        '200':
          description: "创建成功，data.plaintext 仅此一次"
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/AgentAccessKeyCreateResult' }
        '400': { description: "参数错误 / 非法 scope / 模型 allowlist 超 64 项 / 有效凭证数已达上限（5 把）" }
        '401': { description: 用户不存在 }
        '403': { description: "未实名(41001) / issuer_not_consented / scope 超出签发者可授予集" }
        '503': { description: "MEMBER_AGENT_KEY_ISSUANCE_ENABLED 未开启" }

  /api/v4/agent-access-keys/{id}:
    delete:
      summary: 吊销会员委托 Key
      security: [{ loginBearer: [] }]
      description: 不受签发开关约束（关停能力永远比开启容易），仅保留签发者同意闸。
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: "OK（data = { revoked: true }）"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CommonResult' }
        '400': { description: 缺少凭证 ID }
        '403': { description: issuer_not_consented }
        '404': { description: 凭证不存在或已吊销 }

  /api/v4/agent-access-keys/{id}/rotate:
    post:
      summary: 轮换会员委托 Key（旧明文立即失效）
      security: [{ loginBearer: [] }]
      description: 仅作用于 credential_kind=MEMBER_KEY 的凭证；新有效期重置为 90 天。
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: "OK（data.plaintext 为新明文，仅此一次）"
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/AgentAccessKeyCreateResult' }
        '400': { description: 缺少凭证 ID }
        '403': { description: "该凭证不属于会员智能体凭证 / issuer_not_consented" }
        '404': { description: 凭证不存在 }
        '503': { description: "MEMBER_AGENT_KEY_ISSUANCE_ENABLED 未开启" }

  /api/v4/agent-access-keys/{id}/usage:
    get:
      summary: 查该凭证近 N 天用量（观测口径，不是账单）
      security: [{ loginBearer: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - name: days
          in: query
          required: false
          schema: { type: integer, default: 7, minimum: 1, maximum: 90 }
          description: "统计天数；非法或越界回落 7"
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CommonResult'
                  - type: object
                    properties:
                      data: { $ref: '#/components/schemas/AgentAccessKeyUsage' }
        '403': { description: issuer_not_consented }
        '404': { description: 凭证不存在（含非本人凭证） }

  # ===== API Credits 账户 (登录态 C 端, Java tk-dist) =====
  /api/distribution/api-credit/balance:
    get:
      summary: 查我的 API Credits 余额
      security: [{ consoleBearer: [] }]
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CommonResult' }

  /api/distribution/api-credit/ledger:
    get:
      summary: 查我的 API Credits 流水
      security: [{ consoleBearer: [] }]
      parameters:
        - { name: limit, in: query, required: false, schema: { type: integer, default: 100 } }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CommonResult' }

  /api/distribution/api-credit/packages:
    get:
      summary: 可购买的充值套餐包列表
      security: [{ consoleBearer: [] }]
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CommonResult' }
