openapi: 3.1.0
info:
  title: Rapir Relay API
  version: "0.1.0"
  description: |
    Rapir Relay developer inference API (plan rapir-developers-gateway).
    Served by relay-api at `GET /v1/openapi.yml`.

    Conventions:
    - Auth: `Authorization: Bearer rapir_…` or `x-api-key: rapir_…`.
    - Errors: `{"error":{"code","message","status","metadata":{"request_id"}}}`
      (OpenAI-native fields `type`/`param` are also present on inference
      surfaces). Codes: `invalid_request`, `invalid_api_key`,
      `insufficient_balance`, `telegram_link_required`, `permission_denied`,
      `model_not_found`, `request_too_large`, `rate_limited`,
      `no_available_provider`, `service_unavailable`, `internal_error`.
    - Response headers are an allow-list: `content-type`, `cache-control`,
      `x-request-id` / `request-id` (the same Rapir `req_<ulid>`),
      `retry-after` (gateway-generated 429/503 only), `x-ratelimit-*`.
      Nothing upstream sends is forwarded.
    - Prices are USD per 1M tokens as decimal strings.

servers:
  - url: http://localhost:4100
    description: local
  - url: https://apinew.rapir.ai
    description: closed beta and production (once the Relay server exists)

paths:
  /health:
    get:
      operationId: gatewayHealth
      summary: Liveness probe.
      security: []
      responses:
        "200":
          description: Process is up.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status: { type: string, enum: [ok] }
                required: [status]
                additionalProperties: false

  /v1/models:
    get:
      operationId: listDevModels
      summary: Developer model catalog.
      description: |
        OpenAI list shape plus additive OpenRouter-style fields. Public
        without a key (cached); with a key the result is filtered by the
        key's allow-list and the account's risk tier. Prices are the cheapest
        Auto-eligible route's customer prices ("from" prices).

        Reasoning-level variants (2026-10-07): every alias that carries
        default request params (`g6astra-xhigh`, `op55-max`, `dsv4p-think`)
        is ALSO published as its own first-class entry, directly after its
        base model, with `variant_of` naming the base. Fetch-driven clients
        that never read `aliases` still see them. The `aliases` arrays are
        unchanged.

        ANTHROPIC SHAPE (dev.2.B): when the request carries an
        `anthropic-version` or `x-api-key` header (Claude Code discovery
        sends both), the response is the Anthropic list shape
        `{data:[{type:"model", id, display_name, created_at}], has_more,
        first_id, last_id}` honouring `limit` (≤1000), `after_id` and
        `before_id`.
      parameters:
        - in: query
          name: limit
          schema: { type: integer, minimum: 1, maximum: 1000 }
          description: Anthropic shape only; default 20.
        - in: query
          name: after_id
          schema: { type: string }
          description: Anthropic shape only; page after this model id.
        - in: query
          name: before_id
          schema: { type: string }
          description: Anthropic shape only; page before this model id.
      security: []
      responses:
        "200":
          description: Catalog page.
          content:
            application/json:
              schema:
                type: object
                properties:
                  object: { type: string, enum: [list] }
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/DevModel"
                required: [object, data]
                additionalProperties: false

  /v1/models/count:
    get:
      operationId: countDevModels
      summary: Visible model count.
      description: |
        Count of models the caller can see (public catalog, or the key's
        allow-list ∩ risk tier when authenticated). Package `dev.4.B`.
      security: []
      responses:
        "200":
          description: Count.
          content:
            application/json:
              schema:
                type: object
                properties:
                  count: { type: integer, minimum: 0 }
                required: [count]
                additionalProperties: false

  /v1/models/developers:
    get:
      operationId: listDevModelDevelopers
      summary: Compact developer list with visible model counts.
      description: |
        Distinct `owned_by` values from the visible catalog, each with a
        model count. Package `dev.4.B`.
      security: []
      responses:
        "200":
          description: Developer list.
          content:
            application/json:
              schema:
                type: object
                properties:
                  object: { type: string, enum: [list] }
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        count: { type: integer, minimum: 0 }
                      required: [id, count]
                      additionalProperties: false
                required: [object, data]
                additionalProperties: false

  /v1/models/{modelId}:
    get:
      operationId: getDevModel
      summary: One catalog model.
      description: |
        Same wire shape as a `/v1/models` list item. Model ids containing `/`
        are accepted URL-encoded (`anthropic%2Fclaude-sonnet-5`) or as a raw
        multi-segment path. A reasoning-level variant entry id
        (`g6astra-xhigh`) serves the variant's own row (`variant_of` set);
        `/{variant}/providers` serves the base model's providers. Package
        `dev.4.B`.
      parameters:
        - in: path
          name: modelId
          required: true
          schema: { type: string }
          description: Public model id, alias, or variant entry id (may contain `/`).
      security: []
      responses:
        "200":
          description: Model.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DevModel"
        "404":
          description: Unknown or not-visible model (`model_not_found`).

  /v1/models/{modelId}/providers:
    get:
      operationId: listDevModelProviders
      summary: Providers for one model (read-only).
      description: |
        Opaque `provider-N` rows with customer prices and capabilities.
        `stats` come from the metrics pipeline (`dev.6.A`) and stay `null`
        below the §10 sample threshold or inside the publication delay.
        Per-account routing preferences and live health are NOT here —
        they live behind `GET /v1/account/routing` (`dev.7`); this public
        read always reports Auto defaults.
      parameters:
        - in: path
          name: modelId
          required: true
          schema: { type: string }
      security: []
      responses:
        "200":
          description: Provider options.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DevModelProviders"
        "404":
          description: Unknown or not-visible model (`model_not_found`).

  /v1/providers:
    get:
      operationId: listDevProviders
      summary: Providers for a model (query form).
      description: |
        Same body as `GET /v1/models/{modelId}/providers`. `model` is
        required. Per-account routing preferences live behind
        `PUT /v1/account/routing` (`dev.7`). Package `dev.4.B`.
      parameters:
        - in: query
          name: model
          required: true
          schema: { type: string }
          description: Public model id or alias.
      security: []
      responses:
        "200":
          description: Provider options.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DevModelProviders"
        "400":
          description: Missing `model` query (`invalid_request`).
        "404":
          description: Unknown or not-visible model (`model_not_found`).

  /v1/account/credits:
    get:
      operationId: getAccountCredits
      summary: Account wallet balances.
      description: |
        Package `dev.4.C`. Any authenticated developer key. Balances are
        customer-facing USD decimal strings derived from integer micro-USD.
        Vendor COGS is never exposed.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      responses:
        "200":
          description: Wallet snapshot.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AccountCredits"
        "401":
          $ref: "#/components/responses/GatewayError"

  /v1/account/routing:
    get:
      operationId: getAccountRouting
      summary: Per-model routing preferences + provider availability.
      description: |
        Package `dev.7`. The account's stored per-model routing
        preferences plus, for every catalog model the account may use, the
        serving providers as OPAQUE entries: health
        (`available` / `paused` / `circuit_open`) and RELATIVE speed and
        cost ranks (1 = fastest / cheapest among this model's available
        providers; null when there is not enough data). No provider names,
        endpoint slugs, base URLs or absolute supplier rates ever appear.
        `?model=` restricts the availability view to one model.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      parameters:
        - in: query
          name: model
          required: false
          schema: { type: string }
          description: Public model id — restrict the availability view.
      responses:
        "200":
          description: Preferences + availability overview.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AccountRoutingOverview"
        "401":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"
    put:
      operationId: putAccountRouting
      summary: Replace the account's per-model routing preferences.
      description: |
        Package `dev.7`. PUT replaces the whole map — an omitted model is
        cleared. Preferences steer every later request for that model
        unless the request itself carries a routing suffix
        (`:fast`/`:nitro`, `:cheap`/`:floor`), which wins for that one
        request. For single-price models, the customer price does not depend on the route.
        Models using per-route pricing may charge different amounts based on the serving provider.
        A pinned provider that is unhealthy simply falls over to the remaining healthy providers.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AccountRoutingPutBody"
      responses:
        "200":
          description: Stored preferences + refreshed availability view.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AccountRoutingOverview"
        "400":
          $ref: "#/components/responses/GatewayError"
        "401":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"

  /v1/requests:
    get:
      operationId: listAccountRequests
      summary: Request log (metadata only).
      description: |
        Package `dev.4.C`. An inference key sees only its own requests; a
        `management` key sees the account's. No prompt or response bodies.
        Providers are opaque `provider-N` ids only.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      parameters:
        - in: query
          name: model
          schema: { type: string }
        - in: query
          name: provider
          schema: { type: string }
          description: Opaque `provider-N` id.
        - in: query
          name: key
          schema: { type: string, format: uuid }
        - in: query
          name: status
          schema: { type: string }
        - in: query
          name: from
          schema: { type: string, format: date-time }
        - in: query
          name: to
          schema: { type: string, format: date-time }
        - in: query
          name: limit
          schema: { type: integer, minimum: 1, maximum: 100 }
        - in: query
          name: cursor
          schema: { type: string }
      responses:
        "200":
          description: Page of request metadata.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/RequestListItem"
                  next_cursor: { type: ["string", "null"] }
                required: [data, next_cursor]
                additionalProperties: false
        "401":
          $ref: "#/components/responses/GatewayError"

  /v1/requests/{id}/cost:
    get:
      operationId: getRequestCost
      summary: Per-request customer cost breakdown.
      description: |
        Package `dev.4.C`. Same visibility rules as `GET /v1/requests`.
        `cost_usd` and `breakdown` are customer prices only — never vendor
        COGS. Bodies are never returned.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Cost detail.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RequestCost"
        "401":
          $ref: "#/components/responses/GatewayError"
        "400":
          $ref: "#/components/responses/GatewayError"

  /v1/usage/stats:
    get:
      operationId: getUsageStats
      summary: Aggregated usage statistics.
      description: |
        Package `dev.4.C`. Built from `dev_usage_daily` plus today's live
        request rows. Group by `day`, `model`, `provider` or `key`. Customer
        cost only; no live availability/latency stats (`dev.6.A`).
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      parameters:
        - in: query
          name: period
          schema: { type: string, example: "7d" }
        - in: query
          name: group_by
          schema:
            type: string
            enum: [day, model, provider, key]
      responses:
        "200":
          description: Aggregated stats.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/UsageStats"
        "401":
          $ref: "#/components/responses/GatewayError"

  /v1/keys:
    get:
      operationId: listApiKeys
      summary: List API keys for the account.
      description: |
        Package `dev.4.C`. Requires the `management` scope. Secrets are never
        re-emitted.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      responses:
        "200":
          description: Key list.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/ApiKey"
                required: [data]
                additionalProperties: false
        "401":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"
    post:
      operationId: createApiKey
      summary: Create an inference key.
      description: |
        Package `dev.4.C`. Requires `management`. API-created keys are
        `inference`-only and inherit ≤ the parent's limits. Portal creates
        may request scopes; `scopes: [inference]` never gains `management`.
        The one-time secret is returned in `secret` (`api_key` is a deprecated alias).
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateApiKeyRequest"
      responses:
        "201":
          description: Created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  key:
                    $ref: "#/components/schemas/ApiKey"
                  secret:
                    type: string
                    description: Raw `rapir_…` secret; shown once.
                  api_key:
                    type: string
                    description: Deprecated alias of `secret` (backward compatible).
                    deprecated: true
                required: [key, secret, api_key]
                additionalProperties: false
        "401":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"

  /v1/keys/{id}:
    patch:
      operationId: patchApiKey
      summary: Update an API key.
      description: Package `dev.4.C`. Requires `management`. Limits cannot exceed the parent key.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PatchApiKeyRequest"
      responses:
        "200":
          description: Updated key.
          content:
            application/json:
              schema:
                type: object
                properties:
                  key:
                    $ref: "#/components/schemas/ApiKey"
                required: [key]
                additionalProperties: false
        "401":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"
    delete:
      operationId: revokeApiKey
      summary: Revoke an API key.
      description: Package `dev.4.C`. Requires `management`. A key cannot revoke itself.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "204":
          description: Revoked.
        "401":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"

  /v1/keys/{id}/limit:
    patch:
      operationId: patchApiKeyLimit
      summary: Update a key's spend caps.
      description: |
        Package `dev.4.C`. Requires `management`. Caps are USD decimal
        strings and cannot exceed the parent key's caps.
      security:
        - bearerAuth: []
        - apiKeyAuth: []
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PatchApiKeyLimitRequest"
      responses:
        "200":
          description: Updated key.
          content:
            application/json:
              schema:
                type: object
                properties:
                  key:
                    $ref: "#/components/schemas/ApiKey"
                required: [key]
                additionalProperties: false
        "401":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"

  /v1/messages:
    post:
      operationId: createDevMessage
      summary: Anthropic Messages passthrough (Claude Code).
      description: |
        Raw passthrough (R2): the request body is forwarded byte-identical
        except the top-level `model` (replaced by the route's upstream id)
        and the Rapir-only `provider` routing field (removed). `system`,
        `messages`, `tools`, `thinking` blocks and signatures are never
        re-serialised. `anthropic-version` and `anthropic-beta` pass
        verbatim; `?beta=true` is accepted and forwarded.

        Streaming: the SSE tap rewrites only `message_start` (`model` echo,
        minted `msg_<24 base62>` id, envelope filter); every other event —
        content blocks, `signature_delta`, `message_delta`, `ping` — passes
        byte-for-byte. The gateway injects `event: ping` after 15 s of
        upstream silence. Mid-stream failures arrive as `event: error` in the
        Anthropic-native shape.

        Billing: a reservation is taken before the first token (402
        `insufficient_balance` with `metadata.required_reservation_usd` when
        it fails) and settled at stream end from tapped usage: input, cache
        read, cache write 5m/1h and output are priced separately (§8.3).
        Failover to the next route happens only before the first byte.

        Sticky sessions: `x-claude-code-session-id` (then `metadata.user_id`)
        pins the serving route for 60 minutes sliding, so thinking
        signatures and prompt caches stay valid across turns.
      parameters:
        - in: query
          name: beta
          schema: { type: string, enum: ["true"] }
          description: Forwarded verbatim to the route.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model, messages, max_tokens]
              properties:
                model:
                  type: string
                  description: |
                    Public model id or alias (e.g. `anthropic/claude-sonnet-5`,
                    `claude-sonnet-5-5`, `son55`). Optionally append one
                    routing suffix: `:fast`/`:nitro` picks the lowest-latency
                    provider, `:cheap`/`:floor` the cheapest. A suffix wins
                    over the account's saved per-model routing preference
                    (PUT /v1/account/routing) for this one request and never
                    reaches the upstream provider.
                messages:
                  type: array
                  items: { type: object }
                max_tokens: { type: integer }
                stream: { type: boolean }
                system: {}
                tools:
                  type: array
                  items: { type: object }
                thinking:
                  type: object
                  description: |
                    Anthropic thinking control (`{type: "enabled"|"disabled",
                    budget_tokens}`). Forwarded verbatim on Claude and
                    DeepSeek routes; Qwen/MiniMax routes map it to their
                    native `enable_thinking` switch; on other routes the
                    budget maps to the nearest `reasoning_effort` level
                    (≤2048 low, ≤8192 medium, above high; disabled → low —
                    which also disables thinking on GLM routes).
                reasoning_effort:
                  type: string
                  description: |
                    OpenAI-style effort (low/medium/high/xhigh/max). Forwards
                    as-is on routes that honour it.
                metadata: { type: object }
              additionalProperties: true
      responses:
        "200":
          description: |
            Anthropic message (JSON) or SSE stream (`text/event-stream`):
            `message_start`, `content_block_*`, `message_delta`,
            `message_stop`, `ping` events. `model` echoes the exact string
            the client sent; `id` is minted by Rapir.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AnthropicMessage"
            text/event-stream:
              schema:
                type: string
                description: Anthropic-native SSE event sequence.
        "400":
          $ref: "#/components/responses/GatewayError"
        "401":
          $ref: "#/components/responses/GatewayError"
        "402":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"
        "404":
          $ref: "#/components/responses/GatewayError"
        "413":
          $ref: "#/components/responses/GatewayError"
        "429":
          $ref: "#/components/responses/GatewayError"
        "503":
          $ref: "#/components/responses/GatewayError"

  /v1/messages/count_tokens:
    post:
      operationId: createDevMessageTokenCount
      summary: Anthropic count_tokens (proxy-or-404).
      description: |
        Proxied to the route's upstream when the route declares
        `count_tokens`; otherwise returns an Anthropic-shaped 404
        (`not_found_error`) and Claude Code falls back to its own estimate.
        Never billed; rate-limited to 120/min per key
        (`metadata.limit_type: count_tokens`).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model, messages]
              properties:
                model: { type: string }
                messages:
                  type: array
                  items: { type: object }
              additionalProperties: true
      responses:
        "200":
          description: Token count, proxied from the route.
          content:
            application/json:
              schema:
                type: object
                properties:
                  input_tokens: { type: integer }
                required: [input_tokens]
                additionalProperties: true
        "400":
          $ref: "#/components/responses/GatewayError"
        "401":
          $ref: "#/components/responses/GatewayError"
        "404":
          $ref: "#/components/responses/GatewayError"
        "429":
          $ref: "#/components/responses/GatewayError"

  /v1/responses:
    post:
      operationId: createDevResponse
      summary: OpenAI Responses passthrough (Codex, `wire_api = "responses"`).
      description: |
        Raw passthrough (R2): the request body is forwarded byte-identical
        except the top-level `model` (replaced by the route's upstream id),
        the Rapir-only `provider` routing field (removed), and a no-op
        `service_tier` (`auto`/`default`, stripped). `input` items, `tools`
        (custom tools included), reasoning items and
        `include: ["reasoning.encrypted_content"]`, `store`,
        `previous_response_id` and `prompt_cache_key` are never
        re-serialised. `service_tier: "flex"|"priority"` is rejected 400
        (service tiers arrive with a later package). `openai-beta` passes
        verbatim when present.

        Streaming: the SSE tap rewrites only the lifecycle events
        (`response.created` / `in_progress` / `completed` / `failed` /
        `incomplete`): `model` echoes the exact string the client sent,
        unknown `response` envelope keys are dropped, `service_tier` echoes
        the requested tier or is deleted, and a failed/incomplete
        `response.error` is normalized. Every other event —
        `response.output_item.*`, `content_part.*`, `output_text.*`,
        `reasoning_*`, `function_call_arguments.*`,
        `custom_tool_call_input.*`, `web_search_call.*` — passes
        byte-for-byte, including `sequence_number`; `resp_`/`rs_` ids
        round-trip unchanged. The gateway injects an SSE comment
        `: keepalive` after 15 s of upstream silence. Mid-stream failures
        arrive as a `response.failed` event (or a normalized `error` event
        when the upstream used one).

        Billing: a reservation is taken before the first token (402
        `insufficient_balance` with `metadata.required_reservation_usd` when
        it fails) and settled at stream end from tapped usage: uncached
        input, cached input and output are priced separately (§8.3);
        `web_search_call` items bill as server-tool calls. Failover to the
        next route happens only before the first byte.

        Sticky routing: `previous_response_id` is a hard pin to the issuing
        endpoint (recorded only for `store:true` responses);
        `prompt_cache_key` pins the serving route for 30 minutes sliding, so
        prompt caches stay warm across turns.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model]
              properties:
                model:
                  type: string
                  description: |
                    Public model id or alias (e.g. `openai/gpt-5-mini`). A
                    trailing routing suffix is allowed: `:fast`/`:nitro` for
                    the lowest-latency provider, `:cheap`/`:floor` for the
                    cheapest. A suffix overrides the account's saved
                    per-model preference (PUT /v1/account/routing) for this
                    one request.
                input: {}
                instructions: { type: string }
                stream: { type: boolean }
                store: { type: boolean }
                previous_response_id: { type: string }
                prompt_cache_key: { type: string }
                include:
                  type: array
                  items: { type: string }
                reasoning:
                  type: object
                  description: |
                    Responses reasoning control. On native responses routes
                    the body forwards byte-identical. On chat-adapted routes
                    `reasoning.effort` maps to the chat-wire
                    `reasoning_effort` verbatim (model-specific level sets
                    pass through — e.g. medium/high/xhigh-only models reject
                    lower values upstream, surfaced as-is); `summary` and
                    `none` have no chat-wire equivalent and are dropped.
                tools:
                  type: array
                  items: { type: object }
                tool_choice: {}
                max_output_tokens: { type: integer }
                service_tier:
                  type: string
                  enum: [auto, default]
                  description: "`auto`/`default` are stripped upstream-bound; `flex`/`priority` are rejected 400."
                metadata: { type: object }
              additionalProperties: true
      responses:
        "200":
          description: |
            Response object (JSON) or SSE stream (`text/event-stream`):
            `response.created`, `response.output_item.*`, `content_part.*`,
            `output_text.*`, `reasoning_*`, `function_call_arguments.*`,
            `response.completed` events. `model` echoes the exact string the
            client sent; `resp_`/`rs_` ids round-trip unchanged.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ResponsesResponse"
            text/event-stream:
              schema:
                type: string
                description: Responses-native SSE event sequence.
        "400":
          $ref: "#/components/responses/GatewayError"
        "401":
          $ref: "#/components/responses/GatewayError"
        "402":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"
        "404":
          $ref: "#/components/responses/GatewayError"
        "413":
          $ref: "#/components/responses/GatewayError"
        "429":
          $ref: "#/components/responses/GatewayError"
        "503":
          $ref: "#/components/responses/GatewayError"

  /v1/responses/compact:
    post:
      operationId: createDevResponseCompaction
      summary: Responses compact (proxy-or-404).
      description: |
        Proxied (non-stream) to the route's upstream when the route declares
        `compact`; otherwise returns an OpenAI-shaped 404
        (`invalid_request_error`, code `model_not_found`) and Codex falls
        back to client-side compaction. Billed like any inference call from
        reported usage. Sticky routing follows `previous_response_id`, then
        `prompt_cache_key`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model]
              properties:
                model: { type: string }
                input: {}
                previous_response_id: { type: string }
                prompt_cache_key: { type: string }
              additionalProperties: true
      responses:
        "200":
          description: Compaction response, proxied from the route.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ResponsesResponse"
        "400":
          $ref: "#/components/responses/GatewayError"
        "401":
          $ref: "#/components/responses/GatewayError"
        "402":
          $ref: "#/components/responses/GatewayError"
        "404":
          $ref: "#/components/responses/GatewayError"
        "429":
          $ref: "#/components/responses/GatewayError"
        "503":
          $ref: "#/components/responses/GatewayError"

  /v1/chat/completions:
    post:
      operationId: createDevChatCompletion
      summary: Chat Completions passthrough.
      description: |
        Raw passthrough (R2): the request body is forwarded byte-identical
        except the top-level `model` (replaced by the route's upstream id),
        the Rapir-only `provider` routing field (removed), and
        `stream_options.include_usage` (forced on for streams; the usage
        chunk is stripped again downstream when the client did not ask).
        `system`, `messages`, `tools` are never re-serialised.

        Billing: a reservation is taken before the first token (402
        `insufficient_balance` with `metadata.required_reservation_usd` when
        it fails) and settled at stream end from reported usage. Failover to
        the next route happens only before the first byte.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model, messages]
              properties:
                model:
                  type: string
                  description: Public model id or alias (`developer/name`).
                messages:
                  type: array
                  items: { type: object }
                stream: { type: boolean }
                max_tokens: { type: integer }
                max_completion_tokens:
                  type: integer
                  description: |
                    Completion-token cap (gpt-5/6-class models). Forwarded
                    verbatim; clamped to the serving route's max output.
                n: { type: integer }
                reasoning_effort:
                  type: string
                  enum: [low, medium, high, xhigh, max]
                  description: |
                    Reasoning effort. Forwarded verbatim on chat-native
                    routes; on adapted routes it maps from Anthropic
                    `thinking` budgets (see `/v1/messages`). Supplier-side
                    mapping (verified 2026-10-01): honoured for OpenAI,
                    Gemini, Claude, GLM and Kimi routes; on GLM routes any
                    explicit effort disables thinking (default is on).
                thinking:
                  type: object
                  description: |
                    Claude/DeepSeek-style thinking control
                    (`{type: "enabled"|"disabled", budget_tokens}`).
                    Forwarded verbatim on Claude and DeepSeek routes.
                enable_thinking:
                  type: boolean
                  description: Qwen/MiniMax-style thinking switch. Forwarded verbatim.
                stream_options:
                  type: object
                  properties:
                    include_usage: { type: boolean }
              additionalProperties: true
      responses:
        "200":
          description: |
            Chat completion (JSON) or SSE stream (`text/event-stream`).
            `model` echoes the exact string the client sent; `id`/`created`
            are minted by Rapir; `system_fingerprint` is never present.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ChatCompletionResponse"
            text/event-stream:
              schema:
                type: string
                description: |
                  SSE stream: `data: {chunk}` events, then `data: [DONE]`.
        "400":
          $ref: "#/components/responses/GatewayError"
        "401":
          $ref: "#/components/responses/GatewayError"
        "402":
          $ref: "#/components/responses/GatewayError"
        "403":
          $ref: "#/components/responses/GatewayError"
        "404":
          $ref: "#/components/responses/GatewayError"
        "413":
          $ref: "#/components/responses/GatewayError"
        "429":
          $ref: "#/components/responses/GatewayError"
        "503":
          $ref: "#/components/responses/GatewayError"

components:
  schemas:
    PublicPricing:
      type: object
      description: Customer prices in USD per 1M tokens (search_call is per call).
      properties:
        input: { type: string }
        output: { type: string }
        cache_read: { type: string }
        cache_write_5m: { type: string }
        cache_write_1h: { type: string }
        reasoning_output: { type: string }
        search_call: { type: string, description: "USD per server-tool (e.g. web search) call, not per 1M tokens" }
        tiers:
          type: array
          description: >-
            Context-length price tiers, ascending. Above above_input_tokens
            of billed input tokens (uncached + cache-read + cache-write
            classes) the request bills at that tier's per-1M input/output
            prices instead of the base ones. Absent: flat pricing.
          items:
            type: object
            properties:
              above_input_tokens: { type: integer, minimum: 1 }
              input: { type: string }
              output: { type: string }
            required: [above_input_tokens, input, output]
            additionalProperties: false
        unit: { type: string, enum: [usd_per_million_tokens] }
      required: [input, output, unit]
      additionalProperties: false

    DevModel:
      type: object
      properties:
        id: { type: string }
        object: { type: string, enum: [model] }
        created: { type: integer }
        owned_by: { type: string }
        name: { type: string }
        description: { type: string }
        aliases:
          type: array
          description: |
            Alternative client-facing names that resolve to this model on
            every inference surface (compact IDE-friendly names, bare ids).
            Offer these to users whose client rejects the canonical id.
            Alias strings never reach the upstream provider.
          items: { type: string }
        variant_of:
          type: string
          description: >-
            Present only on reasoning-level variant entries (g6astra-xhigh,
            op55-max, dsv4p-think): the canonical id of the base model this
            entry runs on. Same price, context and capabilities as the base;
            using the variant name just applies a default reasoning setting,
            and an explicit reasoning parameter in the request wins. Absent
            on base models.
        context_length: { type: integer }
        max_output_tokens: { type: integer }
        architecture:
          type: object
          properties:
            input_modalities:
              type: array
              items: { type: string }
            output_modalities:
              type: array
              items: { type: string }
          required: [input_modalities, output_modalities]
          additionalProperties: false
        pricing:
          allOf:
            - $ref: "#/components/schemas/PublicPricing"
          description: |
            The CHEAPEST current customer price ("from" price) among the
            model's providers. Each request is charged the price of the
            provider that served it, so a request can cost more than this —
            up to `pricing_max`. The exact charge of any request is at
            `GET /v1/requests/{id}/cost`.
        pricing_max:
          allOf:
            - $ref: "#/components/schemas/PublicPricing"
          description: |
            The most expensive current customer price a request for this
            model can be charged at, computed PER PRICE CLASS: `input` is the
            highest input rate and `output` the highest output rate among the
            providers that may serve it (including on failover), each taken
            independently, so the two may come from different providers.
            Never below `pricing` on either side. Equal to `pricing` when
            every provider charges the same price. Present whenever `pricing`
            is.
        endpoints:
          type: array
          items: { type: string }
        supported_parameters:
          type: array
          items: { type: string }
        access:
          type: object
          properties:
            type: { type: string, enum: [public, gated] }
          required: [type]
          additionalProperties: false
        providers_count: { type: integer }
      required:
        - id
        - object
        - created
        - owned_by
        - name
        - aliases
        - architecture
        - endpoints
        - supported_parameters
        - access
        - providers_count
      additionalProperties: false

    DevModelProviders:
      type: object
      description: |
        Per-model provider options (§7.6). Provider names are opaque
        `provider-N` only. `stats` is null below the §10 sample threshold
        (≥ 20 requests) or when no publishable rollups exist (`dev.6.A`).
      properties:
        model: { type: string }
        mode: { type: string, enum: [auto, manual] }
        selected_provider_chain:
          type: array
          items: { type: string }
        auto_excluded:
          type: array
          items: { type: string }
        providers:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
                description: Opaque `provider-N` public id.
              auto_rank: { type: ["integer", "null"] }
              excluded_from_auto: { type: boolean }
              reduced_fidelity: { type: boolean }
              pricing:
                description: |
                  This provider's own current customer price — what a
                  request it serves is charged. Providers may differ.
                oneOf:
                  - type: "null"
                  - $ref: "#/components/schemas/PublicPricing"
              capabilities:
                type: object
                properties:
                  vision: { type: boolean }
                  tools: { type: boolean }
                  reasoning_effort: { type: boolean }
                required: [vision, tools, reasoning_effort]
                additionalProperties: false
              endpoints:
                type: array
                items: { type: string }
              context_length: { type: ["integer", "null"] }
              max_output_tokens: { type: ["integer", "null"] }
              service_tiers:
                type: array
                items: { type: string }
              stats:
                description: |
                  Public route stats from `dev_route_metrics_*` (§10). Null
                  below 20 samples or within the 5-minute publication delay.
                oneOf:
                  - type: "null"
                  - $ref: "#/components/schemas/ProviderStats"
            required:
              - name
              - auto_rank
              - excluded_from_auto
              - reduced_fidelity
              - pricing
              - capabilities
              - endpoints
              - context_length
              - max_output_tokens
              - service_tiers
              - stats
            additionalProperties: false
      required:
        - model
        - mode
        - selected_provider_chain
        - auto_excluded
        - providers
      additionalProperties: false

    ProviderStats:
      type: object
      description: Rounded public stats (§10 / §9.1 #13).
      properties:
        success_rate_1h: { type: ["number", "null"] }
        stability:
          type: object
          properties:
            h1:
              type: array
              items: { $ref: "#/components/schemas/StabilityBar" }
            h24:
              type: array
              items: { $ref: "#/components/schemas/StabilityBar" }
            d7:
              type: array
              items: { $ref: "#/components/schemas/StabilityBar" }
          required: [h1, h24, d7]
          additionalProperties: false
        latency_p50_ms: { type: ["integer", "null"] }
        streaming_tps_p50: { type: ["integer", "null"] }
        non_stream_tps_p50: { type: ["integer", "null"] }
        cache_hit_rate: { type: ["number", "null"] }
      required:
        - success_rate_1h
        - stability
        - latency_p50_ms
        - streaming_tps_p50
        - non_stream_tps_p50
        - cache_hit_rate
      additionalProperties: false

    StabilityBar:
      type: object
      properties:
        t: { type: string, format: date-time }
        status: { type: string, enum: [ok, degraded, down, none] }
      required: [t, status]
      additionalProperties: false

    AnthropicMessage:
      type: object
      description: |
        Anthropic message envelope. `content` blocks (text, thinking +
        signatures, redacted_thinking, tool_use, …) pass through verbatim.
      properties:
        id: { type: string, description: "Rapir-minted `msg_<24 base62>`." }
        type: { type: string, enum: [message] }
        role: { type: string, enum: [assistant] }
        model: { type: string, description: "Exact echo of the requested string." }
        content:
          type: array
          items: { type: object }
        stop_reason: { type: ["string", "null"] }
        stop_sequence: { type: ["string", "null"] }
        usage:
          type: object
          properties:
            input_tokens: { type: integer }
            output_tokens: { type: integer }
            cache_creation_input_tokens: { type: integer }
            cache_read_input_tokens: { type: integer }
            cache_creation:
              type: object
              properties:
                ephemeral_5m_input_tokens: { type: integer }
                ephemeral_1h_input_tokens: { type: integer }
              additionalProperties: false
            server_tool_use:
              type: object
              properties:
                web_search_requests: { type: integer }
              additionalProperties: false
            # service_tier / inference_geo are NOT forwarded on this surface:
            # the upstream controls those bytes (routing-group leak), so the
            # envelope filter drops them (same doctrine as the chat surface).
          additionalProperties: false
      required: [id, type, role, model, content]
      additionalProperties: false

    ResponsesResponse:
      type: object
      description: |
        Responses envelope. `output` items (reasoning items with
        `encrypted_content`, messages, tool calls, `web_search_call`, …)
        pass through verbatim; `resp_`/`rs_` ids round-trip unchanged.
      properties:
        id: { type: string, description: "Upstream-issued `resp_…` id (round-trip)." }
        object: { type: string, enum: [response, "response.compaction"] }
        created_at: { type: integer }
        status: { type: string, enum: [queued, in_progress, completed, failed, incomplete] }
        model: { type: string, description: "Exact echo of the requested string." }
        output:
          type: array
          items: { type: object }
        error:
          type: ["object", "null"]
          description: "Normalized `{code, message}` on failed/incomplete."
        incomplete_details: { type: ["object", "null"] }
        store: { type: boolean }
        previous_response_id: { type: ["string", "null"] }
        service_tier:
          type: string
          description: Present only when the client requested one.
        usage:
          type: object
          properties:
            input_tokens: { type: integer }
            output_tokens: { type: integer }
            total_tokens: { type: integer }
            input_tokens_details:
              type: object
              properties:
                cached_tokens: { type: integer }
              additionalProperties: false
            output_tokens_details:
              type: object
              properties:
                reasoning_tokens: { type: integer }
              additionalProperties: false
          additionalProperties: false
      required: [id, object, created_at, status, model, output]
      additionalProperties: true

    ChatCompletionResponse:
      type: object
      properties:
        id: { type: string, description: "Rapir-minted `chatcmpl-<29 base62>`." }
        object: { type: string, enum: ["chat.completion"] }
        created: { type: integer, description: "Gateway epoch seconds." }
        model: { type: string, description: "Exact echo of the requested string." }
        choices:
          type: array
          items:
            type: object
            properties:
              index: { type: integer }
              message: { type: object }
              finish_reason: { type: ["string", "null"] }
              logprobs: { type: ["object", "null"] }
            required: [index, message, finish_reason]
            additionalProperties: false
        usage:
          type: object
          properties:
            prompt_tokens: { type: integer }
            completion_tokens: { type: integer }
            total_tokens: { type: integer }
            prompt_tokens_details:
              type: object
              properties:
                cached_tokens: { type: integer }
              additionalProperties: false
            completion_tokens_details:
              type: object
              properties:
                reasoning_tokens: { type: integer }
              additionalProperties: false
          additionalProperties: false
        service_tier:
          type: string
          description: Present only when the client requested one.
      required: [id, object, created, model, choices]
      additionalProperties: false

    AccountCredits:
      type: object
      description: Customer wallet balances as USD decimal strings (§8.1).
      properties:
        balance_usd: { type: string }
        paid_usd: { type: string }
        bonus_usd: { type: string }
        reserved_usd: { type: string }
        total_spent_usd: { type: string }
        overdraft_limit_usd: { type: string }
      required:
        - balance_usd
        - paid_usd
        - bonus_usd
        - reserved_usd
        - total_spent_usd
        - overdraft_limit_usd
      additionalProperties: false

    AccountModelRoutingPreference:
      type: object
      description: |
        The account's routing behaviour for one model. `pinned` names opaque
        `provider-N` ids (as returned by GET /v1/account/routing) in the
        customer's chosen order; it is required for mode `pinned` and
        ignored otherwise.
      properties:
        mode:
          type: string
          enum: [auto, cheapest, fastest, pinned]
          description: |
            `auto` lets Rapir balance price, speed and reliability;
            `cheapest`/`fastest` always pick the lowest-cost/lowest-latency
            healthy provider; `pinned` tries the listed providers in order.
        pinned:
          type: array
          items: { type: string }
          maxItems: 8
          description: Opaque `provider-N` ids in the chosen order.
      required: [mode]
      additionalProperties: false

    AccountRoutingPutBody:
      type: object
      description: |
        The FULL preference map, keyed by public model id. PUT replaces the
        stored map; an omitted model is cleared.
      properties:
        preferences:
          type: object
          additionalProperties:
            $ref: "#/components/schemas/AccountModelRoutingPreference"
      required: [preferences]
      additionalProperties: false

    AccountRoutingOverviewProvider:
      type: object
      description: One serving provider for a model — opaque identity only.
      properties:
        id: { type: string, description: Opaque `provider-N` id. }
        status:
          type: string
          enum: [available, paused, circuit_open]
          description: |
            `paused` includes providers being onboarded; `circuit_open`
            means temporarily sidestepped after failures (requests fall
            over to healthy providers).
        speed_rank:
          type: ["integer", "null"]
          description: |
            1 = fastest among this model's available providers (6 h mean
            response start). Null when there are no samples yet.
        cost_rank:
          type: ["integer", "null"]
          description: 1 = lowest running cost among the available providers.
        pricing:
          description: |
            This provider's current customer price (what a request it serves
            is charged). Null when the provider is paused or unpriced.
          oneOf:
            - type: "null"
            - $ref: "#/components/schemas/PublicPricing"
      required: [id, status, speed_rank, cost_rank, pricing]
      additionalProperties: false

    AccountRoutingOverviewModel:
      type: object
      properties:
        model: { type: string, description: Public model id. }
        default_mode:
          type: string
          enum: [auto, cheapest, fastest, fixed]
          description: The operator's default routing behaviour for the model.
        preference:
          type: ["object", "null"]
          description: The account's stored preference for this model.
        effective_mode:
          type: string
          enum: [auto, cheapest, fastest, pinned, fixed]
          description: |
            What the next request without a suffix will do. When the
            account pinned providers that are all unhealthy, this reports
            the default the failover will use.
        providers:
          type: array
          items:
            $ref: "#/components/schemas/AccountRoutingOverviewProvider"
      required: [model, default_mode, preference, effective_mode, providers]
      additionalProperties: false

    AccountRoutingOverview:
      type: object
      description: |
        The stored preference map plus the per-model availability view.
        Provider entries are opaque; ranks are relative — no supplier
        identity, no absolute supplier rates.
      properties:
        preferences:
          type: object
          additionalProperties:
            $ref: "#/components/schemas/AccountModelRoutingPreference"
        models:
          type: array
          items:
            $ref: "#/components/schemas/AccountRoutingOverviewModel"
      required: [preferences, models]
      additionalProperties: false

    RequestUsage:
      type: object
      properties:
        input_tokens: { type: integer }
        cached_input_tokens: { type: integer }
        cache_write_5m_tokens: { type: integer }
        cache_write_1h_tokens: { type: integer }
        output_tokens: { type: integer }
        reasoning_tokens: { type: integer }
        server_tool_calls: { type: integer }
      required:
        - input_tokens
        - cached_input_tokens
        - cache_write_5m_tokens
        - cache_write_1h_tokens
        - output_tokens
        - reasoning_tokens
        - server_tool_calls
      additionalProperties: false

    RequestListItem:
      type: object
      description: Metadata-only request log row. No bodies, no vendor COGS.
      properties:
        id: { type: string }
        created_at: { type: string, format: date-time }
        model: { type: ["string", "null"] }
        provider:
          type: ["string", "null"]
          description: Opaque `provider-N` id.
        key_id: { type: ["string", "null"], format: uuid }
        status: { type: ["string", "null"] }
        surface: { type: ["string", "null"] }
        stream: { type: ["boolean", "null"] }
        http_status: { type: ["integer", "null"] }
        error_code: { type: ["string", "null"] }
        cost_usd: { type: ["string", "null"] }
        usage:
          oneOf:
            - $ref: "#/components/schemas/RequestUsage"
            - type: "null"
      required:
        - id
        - created_at
        - model
        - provider
        - key_id
        - status
        - surface
        - stream
        - http_status
        - error_code
        - cost_usd
        - usage
      additionalProperties: false

    RequestCost:
      type: object
      properties:
        request_id: { type: string }
        model: { type: ["string", "null"] }
        provider: { type: ["string", "null"] }
        usage:
          oneOf:
            - $ref: "#/components/schemas/RequestUsage"
            - type: "null"
        cost_usd: { type: ["string", "null"] }
        breakdown:
          type: object
          properties:
            input: { type: string }
            cache_read: { type: string }
            cache_write_5m: { type: string }
            cache_write_1h: { type: string }
            output: { type: string }
            server_tools: { type: string }
          required:
            - input
            - cache_read
            - cache_write_5m
            - cache_write_1h
            - output
            - server_tools
          additionalProperties: false
      required: [request_id, model, provider, usage, cost_usd, breakdown]
      additionalProperties: false

    UsageStatsRow:
      type: object
      properties:
        day: { type: string }
        model: { type: ["string", "null"] }
        provider: { type: ["string", "null"] }
        key_id: { type: ["string", "null"], format: uuid }
        requests: { type: integer }
        input_tokens: { type: integer }
        cached_input_tokens: { type: integer }
        cache_write_5m_tokens: { type: integer }
        cache_write_1h_tokens: { type: integer }
        output_tokens: { type: integer }
        reasoning_tokens: { type: integer }
        cost_usd: { type: string }
      required:
        - requests
        - input_tokens
        - cached_input_tokens
        - cache_write_5m_tokens
        - cache_write_1h_tokens
        - output_tokens
        - reasoning_tokens
        - cost_usd
      additionalProperties: false

    UsageStats:
      type: object
      properties:
        period: { type: string }
        group_by:
          type: string
          enum: [day, model, provider, key]
        data:
          type: array
          items:
            $ref: "#/components/schemas/UsageStatsRow"
      required: [period, group_by, data]
      additionalProperties: false

    ApiKey:
      type: object
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        key_prefix: { type: string }
        last4: { type: string }
        scopes:
          type: array
          items: { type: string, enum: [inference, management] }
        status: { type: string }
        rpm_limit: { type: ["integer", "null"] }
        concurrency_limit: { type: ["integer", "null"] }
        daily_spend_cap_usd: { type: ["string", "null"] }
        monthly_spend_cap_usd: { type: ["string", "null"] }
        total_spend_limit_usd: { type: ["string", "null"] }
        spent_total_usd: { type: string }
        allowed_models:
          type: ["array", "null"]
          items: { type: string }
        allowed_surfaces:
          type: ["array", "null"]
          items: { type: string }
        expires_at: { type: ["string", "null"], format: date-time }
        last_used_at: { type: ["string", "null"], format: date-time }
        created_via: { type: string }
        created_at: { type: string, format: date-time }
        revoked_at: { type: ["string", "null"], format: date-time }
      required:
        - id
        - name
        - key_prefix
        - last4
        - scopes
        - status
        - rpm_limit
        - concurrency_limit
        - daily_spend_cap_usd
        - monthly_spend_cap_usd
        - total_spend_limit_usd
        - spent_total_usd
        - allowed_models
        - allowed_surfaces
        - expires_at
        - last_used_at
        - created_via
        - created_at
        - revoked_at
      additionalProperties: false

    CreateApiKeyRequest:
      type: object
      properties:
        name: { type: string }
        scopes:
          type: array
          items: { type: string, enum: [inference, management] }
          description: >
            Optional. Omitted defaults to `[inference]` only. Management is
            added only when an authorized portal session explicitly requests
            it. API-created keys cannot request management.
        rpm_limit: { type: ["integer", "null"] }
        concurrency_limit: { type: ["integer", "null"] }
        daily_spend_cap_usd: { type: ["string", "null"] }
        monthly_spend_cap_usd: { type: ["string", "null"] }
        total_spend_limit_usd: { type: ["string", "null"] }
        allowed_models:
          type: ["array", "null"]
          items: { type: string }
        allowed_surfaces:
          type: ["array", "null"]
          items: { type: string }
        expires_at: { type: ["string", "null"], format: date-time }
        ip_allowlist:
          type: ["array", "null"]
          items: { type: string }
      required: [name]
      additionalProperties: false

    PatchApiKeyRequest:
      type: object
      description: >
        Rename / allow-lists / expiry only. Spend caps must use
        `PATCH /v1/keys/{id}/limit` — unknown fields (including
        `total_spend_limit_usd`) return 400 `unknown_field`.
      properties:
        name: { type: string }
        rpm_limit: { type: ["integer", "null"] }
        concurrency_limit: { type: ["integer", "null"] }
        allowed_models:
          type: ["array", "null"]
          items: { type: string }
        allowed_surfaces:
          type: ["array", "null"]
          items: { type: string }
        expires_at: { type: ["string", "null"], format: date-time }
        ip_allowlist:
          type: ["array", "null"]
          items: { type: string }
      additionalProperties: false

    PatchApiKeyLimitRequest:
      type: object
      properties:
        daily_spend_cap_usd: { type: ["string", "null"] }
        monthly_spend_cap_usd: { type: ["string", "null"] }
        total_spend_limit_usd: { type: ["string", "null"] }
      additionalProperties: false

    GatewayError:
      type: object
      description: |
        Unified error. OpenAI/management surfaces: `{"error":{…}}`. The
        Anthropic surface wraps the same `error` object in the
        protocol-native envelope: `{"type":"error","error":{…},"request_id"}`.
      properties:
        type: { type: string, enum: [error], description: "Anthropic surface only." }
        request_id: { type: string, description: "Anthropic surface only; equals error.metadata.request_id." }
        error:
          type: object
          properties:
            code:
              type: string
              enum:
                - invalid_request
                - unknown_field
                - invalid_api_key
                - insufficient_balance
                - telegram_link_required
                - permission_denied
                - model_not_found
                - request_too_large
                - rate_limited
                - no_available_provider
                - service_unavailable
                - internal_error
            message: { type: string }
            status: { type: integer }
            type: { type: string, description: "OpenAI-native error type on inference surfaces." }
            param: { type: ["string", "null"] }
            metadata:
              type: object
              properties:
                request_id: { type: string }
                limit_type: { type: string }
                required_reservation_usd: { type: string }
              required: [request_id]
              additionalProperties: true
          required: [code, message, status, metadata]
          additionalProperties: false
      required: [error]
      additionalProperties: false

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: rapir_
      description: "Developer key `Authorization: Bearer rapir_…`."
    apiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: "Developer key via `x-api-key: rapir_…`."

  responses:
    GatewayError:
      description: Unified gateway error.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/GatewayError"
