openapi: 3.1.0
info:
  title: ChessDrive API
  version: "1"
  summary: "Four chess APIs: Generate (Knight, Queen), Embed (the Embedding model), Engine (Stockfish, with Lc0 coming soon) and Search (the Games database, with similar moments coming soon), and the Usage API to see what they cost you."
  description: |
    Contract from the [API lineup map](https://github.com/cem-unuvar/chesslm/issues/215) (2026-10-10).
    Conventions and the reasons behind them are in `devplatform/docs/api-contract.md`.

    - Every API is `POST /v1/<api>` with a JSON body. Generate and Embed require `model` and echo the versioned
      Model ID that served them; Search and Engine take no `model`.
    - The Usage API, `GET /v1/usage` and `GET /v1/balance`, reads what your calls cost and what is left to spend.
      It is free and never refused for money. Payments, Top-ups and limits stay in the Dashboard.
    - Authenticate with `Authorization: Bearer <API key>`.
    - A Study key, from `POST /v1/study_keys`, is made for one Study page: it calls only Engine and Generate, from a
      browser too, with a $1 daily Key limit, and expires after 7 days.
    - Positions are FEN, or PGN plus a main-line `ply`. Moves are returned as `{san, uci}`; no request field takes a move.
    - Every response carries a `request-id` header. Every response to a call that reached the rate-limit step (200,
      402, 429, 500, 503) carries the `x-ratelimit-*` headers, which report the requests-per-minute limit (and requests
      in flight, on Engine and Embed); the 400, 401, 403, 413 and 501 refusals before that step carry none.
    - Errors share one envelope (`Error`). Only 2xx responses are billed; a client that hangs up mid-stream is
      billed for what was processed so far.
servers:
  - url: https://api.chessdrive.io
    description: Production.
  - url: https://api-staging.chessdrive.io
    description: Staging, with its own keys, Stripe sandbox and data.
security:
  - apiKey: []
tags:
  - name: Generate
  - name: Embed
  - name: Search
  - name: Engine
  - name: Models
  - name: Usage
  - name: Balance
  - name: Study keys

# The headers on every success, defined once as a YAML anchor.
x-standard-headers: &standardHeaders
  request-id: { $ref: "#/components/headers/RequestId" }
  x-ratelimit-limit-requests: { $ref: "#/components/headers/RateLimitLimit" }
  x-ratelimit-remaining-requests: { $ref: "#/components/headers/RateLimitRemaining" }
  x-ratelimit-reset-requests: { $ref: "#/components/headers/RateLimitReset" }

paths:
  /v1/generate:
    post:
      tags: [Generate]
      operationId: generate
      # x-mcp makes an operation an MCP tool, in the CLI's `chesslm mcp` and the Connector at /mcp, both written by
      # `make generate` (api/openapi/gen/tools.go). Every tool is read-only to the agent; `idempotent: true` marks the
      # free ones, which bill nothing, and `connector: false` keeps a tool out of the Connector.
      x-mcp:
        name: generate
        title: Generate
        description: >-
          Ask Knight or Queen, chess language models, about chess, optionally about one position (a FEN, or a PGN with
          a ply). Returns the reply in markdown, with every move it names as a legal Line. Billed.
      summary: Ask Knight or Queen, optionally about a position, and get prose with its named moves checked.
      description: |
        Stateless: send the whole conversation each time. The reply is markdown. Every move it names comes back as a
        Line, which the prose links as `[text](line:L1)`; a Line is cut at its first illegal move, so every move in
        `lines` is legal. Without a `position`, `lines` is empty. Coaching, explaining and picking a move are Recipes
        in the Docs, not APIs. With `stream: true` the response is Server-Sent Events (see `GenerateStreamEvent`).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/GenerateRequest" }
            example:
              model: knight
              system: You are a patient chess coach for a 1400-rated player.
              position: { pgn: "1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6", ply: 10 }
              messages:
                - { role: user, content: "What is the idea behind 5...a6?" }
      responses:
        "200":
          description: The reply, or an event stream when `stream` is true.
          headers: *standardHeaders
          content:
            application/json:
              schema: { $ref: "#/components/schemas/GenerateResponse" }
              example:
                id: req_01J9Z6Q8F3
                model: knight-1
                content: "5...a6 prepares [...b5](line:L1), gaining space on the queenside, and keeps White's knights off b5."
                lines:
                  - id: L1
                    from_fen: rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP2PPP/R1BQKB1R w KQkq - 0 6
                    moves:
                      - { san: Be2, uci: f1e2, fen: rnbqkb1r/1p2pppp/p2p1n2/8/3NP3/2N5/PPP1BPPP/R1BQK2R b KQkq - 1 6 }
                      - { san: b5, uci: b7b5, fen: rnbqkb1r/4pppp/p2p1n2/1p6/3NP3/2N5/PPP1BPPP/R1BQK2R w KQkq - 0 7 }
                finish_reason: end
                usage: { input_tokens: 1840, output_tokens: 96, cached_tokens: 1152, grounding_tokens: 1530, reasoning_tokens: 0 }
                cost_usd: "0.000963"
            text/event-stream:
              schema: { $ref: "#/components/schemas/GenerateStreamEvent" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/PaymentRequired" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "413": { $ref: "#/components/responses/TooLarge" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "500": { $ref: "#/components/responses/InternalError" }
        "503": { $ref: "#/components/responses/Overloaded" }

  /v1/embed:
    post:
      tags: [Embed]
      operationId: embed
      x-mcp:
        name: embed
        title: Embed
        connector: false
        description: >-
          Turn chess positions and texts, mixed, into vectors in one shared space (one per item, up to 256), to compare
          or cluster them. Billed.
      summary: Turn positions and texts into vectors in one space.
      description: |
        Up to 256 items per call, positions and texts mixed in any order, each typed. Vectors compare only within one
        Embedding model version, so `model` takes a versioned ID and never an alias. One bad item rejects the whole
        call, with `param` naming it (`input[3].fen`).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/EmbedRequest" }
            example:
              model: chessdrive-embed-1
              input:
                - { type: position, fen: "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1" }
                - { type: text, text: "an isolated queen's pawn" }
      responses:
        "200":
          description: One vector per item, in request order.
          headers:
            request-id: { $ref: "#/components/headers/RequestId" }
            x-ratelimit-limit-requests: { $ref: "#/components/headers/RateLimitLimit" }
            x-ratelimit-remaining-requests: { $ref: "#/components/headers/RateLimitRemaining" }
            x-ratelimit-reset-requests: { $ref: "#/components/headers/RateLimitReset" }
            x-ratelimit-limit-concurrent: { $ref: "#/components/headers/RateLimitLimitConcurrent" }
            x-ratelimit-remaining-concurrent: { $ref: "#/components/headers/RateLimitRemainingConcurrent" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/EmbedResponse" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/PaymentRequired" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "413": { $ref: "#/components/responses/TooLarge" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "500": { $ref: "#/components/responses/InternalError" }
        "501": { $ref: "#/components/responses/ComingSoon" }
        "503": { $ref: "#/components/responses/Overloaded" }

  /v1/search:
    post:
      tags: [Search]
      operationId: search
      # Search on the Games database (#995): docs/api-contract.md has the whole of it. `query` stays coming soon and
      # not promised: its fields and SearchResponse carry `x-coming-soon`, which keeps them out of the API reference.
      # `where` (W4-115, #1053) is described as an object: the Position filter's schema is recursive, which the MCP
      # tools' inlined schemas can't hold. The chessdrive-position-filter Skill ships the schema itself.
      x-mcp:
        name: search
        title: Search
        description: >-
          Search real games. Send `position` (`{fen}` or `{pgn, ply}`) for every move played from
          it, most played first, with how those games ended: $5 per 1,000 calls. Or send `player` (`{fide_id}`, or
          `{name}` as FIDE's list writes it) for that player's games, newest first: `limit` 1 to 200 (default 50),
          `cursor` for the next page, `pgn: true` for the moves, and `filters` on `date`, `eco`, `result`, `color` and
          `opponent`; $5 per 1,000 games, at least one a call. A name that could be several players answers up to 5
          candidates, unbilled: ask which one. Or send `where`, a Position filter, for the Positions it holds for, each
          with how often games reached it, whether it is quiet and its highest-rated game: a JSON tree of board
          expressions (`piece` "wN", `attacks` "wB" or "white", `occupied`, `squares`, `rank`, `file`, `and`, `or`,
          `not`, `shift` and `fill` [X, "N"…"SW"], `flip`) inside tests (`any`, `none`, `count` with `gte`, `lte` or
          `eq`, `to_move`, `castling`, `en_passant`, `all`, `some`, `not`, `flip`), with `define` for named parts used
          as `{"ref": name}`; `limit` 1 to 200 (default 20) and `cursor`; $5 per 1,000 Positions, at least one a call.
          A filter that is wrong is `invalid_filter` with `param` at the node: mend that node and send again. Search by
          similar moments (`query`) is coming soon.
      summary: Every move played from a position, one player's games, or the positions a filter holds for.
      description: |
        Search answers from real games, in one of three modes, exactly one a call. `position` gives
        every move played from it, most played first, with how those games ended: one query, $5 per 1,000. `player`
        gives that player's games, newest first: $5 per 1,000 games returned, at least one a call, and nothing for a
        name that could be several players, which answers their `candidates`. `where` takes a Position filter and
        gives the Positions it holds for, each with how often games reached it, whether it is quiet, and the
        highest-rated game that reaches it: $5 per 1,000 Positions returned, at least one a call. A filter that is
        wrong is 400 `invalid_filter`, unbilled, with `param` naming the node at fault; one that runs too long is 503
        `upstream_unavailable`, unbilled: narrow it. No answer names where a game came from. Search by similar
        moments, with `query`, is coming soon: it answers 501 `coming_soon`, unbilled.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/SearchRequest" }
            example:
              position: { fen: "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1" }
      responses:
        "200":
          description: >-
            `SearchMovesResponse` for `position`, `SearchGamesResponse` for `player`, `SearchPositionsResponse` for
            `where`, and `SearchResponse` for `query` once it opens.
          headers: *standardHeaders
          content:
            application/json:
              schema:
                oneOf:
                  - { $ref: "#/components/schemas/SearchMovesResponse" }
                  - { $ref: "#/components/schemas/SearchGamesResponse" }
                  - { $ref: "#/components/schemas/SearchPositionsResponse" }
                  - { $ref: "#/components/schemas/SearchResponse" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/PaymentRequired" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "413": { $ref: "#/components/responses/TooLarge" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "500": { $ref: "#/components/responses/InternalError" }
        "501": { $ref: "#/components/responses/ComingSoon" }
        "503": { $ref: "#/components/responses/Overloaded" }

  /v1/engine:
    post:
      tags: [Engine]
      operationId: engine
      x-mcp:
        name: engine
        title: Engine
        description: >-
          Analyse a position with Stockfish (Lc0 is coming soon) to a depth, node or time limit: the score from White's
          point of view, win/draw/loss chances and up to 5 best Lines. Or review a whole game in one call: send a PGN
          with no ply, and every move comes back with its evaluation before and after, its Move verdict (best, good,
          inaccuracy, mistake, blunder) and Engine's best Line. Or check up to 100 positions in one call: send
          `positions` instead of `position`, rather than one call per position. Billed by engine time.
      summary: Analyse a position, a list of positions or a whole game, with Stockfish.
      description: |
        At most one limit (`depth`, `nodes` or `movetime_ms`) under the engine's cap, or the engine's default. Every
        call also stops at a 60 s wall-clock cap and returns the deepest completed result. Scores are from White's
        point of view. Engine takes no `model`; billing is by Engine time, at least 100 ms a call. With
        `stream: true` the response is Server-Sent Events, one per completed depth (see `EngineStreamEvent`).

        **A whole game:** a `position` that is a `pgn` with no `ply` runs Engine on every position of the PGN's main
        line and answers with an `EngineGameResponse`, one entry per move. The limit applies to each position, and
        the default is `depth` 14 rather than 20. The whole game shares the one 60 s budget: a `movetime_ms` that
        can't fit is refused up front, and a game that runs past it fails with `limit_too_high` and is not billed.
        It is billed by the Engine time of all its positions together, at least 100 ms. A whole game takes no
        `lines` (each move gets Engine's best Line) and no `stream`.

        **A list of positions:** `positions`, instead of `position`, takes up to 100 and answers with an
        `EngineBatchResponse`, one result per position in order. It counts as one request and one in flight. The
        limit and `lines` apply to each position, the default is `depth` 14 rather than 20, and each Line is cut to
        its first 8 half-moves. The positions run one after another inside the one 60 s budget. A position Engine can't
        take refuses the whole call, naming it, and nothing is billed. A finished game comes back as `game_over` and
        doesn't stop the others. At the budget, or when the engine fails part way, the call still answers 200: what
        finished is billed, and the rest comes back as `not_run`, unbilled, to send again. If nothing finished, it is
        the usual error, unbilled. Billing is the Engine time of all its positions together, at least 100 ms. A list
        takes no `stream`.

        **A burst:** a call over the Plan's requests in flight waits up to 5 s for one to finish before it answers
        `429 rate_limited`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/EngineRequest" }
            example:
              engine: stockfish
              position: { fen: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" }
              depth: 30
              lines: 2
      responses:
        "200":
          description: The analysis, or an event stream when `stream` is true.
          headers:
            request-id: { $ref: "#/components/headers/RequestId" }
            x-ratelimit-limit-requests: { $ref: "#/components/headers/RateLimitLimit" }
            x-ratelimit-remaining-requests: { $ref: "#/components/headers/RateLimitRemaining" }
            x-ratelimit-reset-requests: { $ref: "#/components/headers/RateLimitReset" }
            x-ratelimit-limit-concurrent: { $ref: "#/components/headers/RateLimitLimitConcurrent" }
            x-ratelimit-remaining-concurrent: { $ref: "#/components/headers/RateLimitRemainingConcurrent" }
          content:
            application/json:
              schema:
                description: >-
                  `EngineResponse` for one position, `EngineGameResponse` for a whole game, and
                  `EngineBatchResponse` for a list of positions.
                oneOf:
                  - { $ref: "#/components/schemas/EngineResponse" }
                  - { $ref: "#/components/schemas/EngineGameResponse" }
                  - { $ref: "#/components/schemas/EngineBatchResponse" }
              example:
                id: req_01J9Z6Q8F3
                engine: stockfish
                version: Stockfish 19
                network: null
                fen: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
                depth: 30
                seldepth: 41
                nodes: 18200000
                time_ms: 7400
                stop_reason: limit
                best_move: { san: e4, uci: e2e4 }
                lines:
                  - rank: 1
                    depth: 30
                    cp: 34
                    mate: null
                    wdl: { win: 312, draw: 620, loss: 68 }
                    moves: [{ san: e4, uci: e2e4 }, { san: e5, uci: e7e5 }]
                  - rank: 2
                    depth: 30
                    cp: 28
                    mate: null
                    wdl: { win: 290, draw: 640, loss: 70 }
                    moves: [{ san: d4, uci: d2d4 }, { san: Nf6, uci: g8f6 }]
                usage: { engine_ms: 7400 }
                cost_usd: "0.009250"
            text/event-stream:
              schema: { $ref: "#/components/schemas/EngineStreamEvent" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "402": { $ref: "#/components/responses/PaymentRequired" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "413": { $ref: "#/components/responses/TooLarge" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "500": { $ref: "#/components/responses/InternalError" }
        "501": { $ref: "#/components/responses/ComingSoon" }
        "503": { $ref: "#/components/responses/Overloaded" }

  /v1/models:
    get:
      tags: [Models]
      operationId: listModels
      x-mcp:
        name: list_models
        title: List Models
        idempotent: true
        description: >-
          List the Models: their IDs and aliases, the APIs they serve, context windows and embedding dimensions. Free.
      summary: List the Models, their IDs, aliases, limits and the APIs they serve.
      description: Public; no API key needed, so the Site and Docs read it too.
      security: []
      responses:
        "200":
          description: Every Model version currently served.
          headers:
            request-id: { $ref: "#/components/headers/RequestId" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ModelList" }
              example:
                data:
                  - id: knight-1
                    aliases: [knight]
                    name: Knight
                    apis: [generate]
                    context_window: 32768
                    embed_dimensions: null
                    downloadable: true
                    status: available
                  - id: queen-1
                    aliases: [queen]
                    name: Queen
                    apis: [generate]
                    context_window: 131072
                    embed_dimensions: null
                    downloadable: false
                    status: available
                  - id: chessdrive-embed-1
                    aliases: []
                    name: ChessDrive Embed
                    apis: [embed]
                    context_window: null
                    embed_dimensions: 512
                    downloadable: false
                    status: available

  /v1/usage:
    get:
      tags: [Usage]
      operationId: getUsage
      x-mcp:
        name: usage
        title: Usage
        idempotent: true
        description: Your requests, failed requests and cost per UTC day between two days, by API, Model or API key. Free.
      summary: Your requests and what they cost, per UTC day, by API, Model or API key.
      description: |
        The numbers the Dashboard's Usage page shows for the same range and grouping. An Admin's or an Individual's
        key sees the whole Account; a Team member's key sees what its creator sees there: the calls of the keys they
        created, and their own Playground calls. The Dashboard's Playground calls are a series of their own,
        `playground`, last.

        Free: never refused for money (no 402), nothing drawn from the Balance and no row in the Request log, so you
        can check why calls fail. A key restricted to other APIs or Models may call it. Its rate limit is its own,
        60 requests a minute per Account, shared with `GET /v1/balance`.
      parameters:
        - name: from
          in: query
          required: true
          description: The first UTC day, `YYYY-MM-DD`.
          schema: { type: string, format: date }
          example: "2026-10-01"
        - name: to
          in: query
          required: true
          description: The last UTC day, included, at most 365 days after `from`.
          schema: { type: string, format: date }
          example: "2026-10-03"
        - name: group_by
          in: query
          required: false
          description: What each series is.
          schema: { $ref: "#/components/schemas/UsageGroupBy" }
          example: model
      responses:
        "200":
          description: One series per API, Model or key that called in the range, each with a value for every day.
          headers: *standardHeaders
          content:
            application/json:
              schema: { $ref: "#/components/schemas/UsageResponse" }
              example:
                from: "2026-10-01"
                to: "2026-10-03"
                group_by: model
                days: ["2026-10-01", "2026-10-02", "2026-10-03"]
                series:
                  - id: knight-1
                    name: Knight
                    requests: [120, 85, 0]
                    cost_usd: ["0.014400", "0.010200", "0.000000"]
                  - id: playground
                    name: Playground
                    requests: [0, 3, 1]
                    cost_usd: ["0.000000", "0.000360", "0.000120"]
                errors: [2, 0, 0]
                total: { requests: 209, cost_usd: "0.025080" }
        "400": { $ref: "#/components/responses/BadQuery" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "500": { $ref: "#/components/responses/InternalError" }

  /v1/balance:
    get:
      tags: [Balance]
      operationId: getBalance
      x-mcp:
        name: balance
        title: Balance
        idempotent: true
        description: >-
          Your Account's Plan, Balance, Monthly credit, Trial credits, this month's spend and Spend limit. Free. A Team
          member's key is refused with 403; usage shows their own spend.
      summary: Your Account's Plan, Balance, Monthly credit, Trial credits left, this month's spend and Spend limit.
      description: |
        The money the Dashboard's Billing page shows, for an Admin's or an Individual's key. A Team member's key is
        refused with 403 `key_not_allowed`, as Team members see none of an Organization's billing; `GET /v1/usage`
        still shows them their own keys' spend.

        Free: never refused for money (no 402), nothing drawn from the Balance and no row in the Request log. A key
        restricted to other APIs or Models may call it. Its rate limit is its own, 60 requests a minute per Account,
        shared with `GET /v1/usage`. To top up or change the Spend limit, use the Dashboard.
      responses:
        "200":
          description: The Account's money now.
          headers: *standardHeaders
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BalanceResponse" }
              example:
                plan: free
                balance_usd: "9.213500"
                monthly_credit_usd: "0.000000"
                monthly_credit_expires_at: null
                trial_credits_usd: "9.213500"
                trial_credits_expire_at: null
                month_spend_usd: "0.786500"
                spend_limit_usd: null
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "500": { $ref: "#/components/responses/InternalError" }

  /v1/study_keys:
    post:
      tags: [Study keys]
      operationId: createStudyKey
      x-mcp:
        name: study_key
        title: Study key
        readOnly: false
        description: >-
          Make a Study key for one Study page you're building, so the page can call Engine and Generate itself when the
          person asks: only those two, $1 a day at most, for 7 days. Name it after the Study, and give the artifact's
          link as `url` if it has one. Free. The key goes in the page as the Study Skill says, never in a
          copy someone downloads.
      summary: Make a Study key, for one Study page to call Engine and Generate.
      description: |
        A Study is a page a person's agent builds for them with the Study Skill. Its Study key lets the
        page call `POST /v1/engine` and `POST /v1/generate` from the browser when the person asks: the key can call
        only those two, with a Key limit of $1 a UTC day, and expires 7 days after it was made. Each is its own key,
        listed under Study keys on the Dashboard's API keys page, where it can be revoked.

        The page holds the key, so anyone who opens the page can spend it, up to its limit. Engine and Generate answer
        a browser from any origin, a page opened as a local file included, with the CORS headers, and so does
        `GET /v1/models`, which a page can read first, free and with no key, to learn whether it can reach the API.

        A Study key takes the Model restriction of the key that made it, and is refused when that key can't call
        both Engine and Generate. It is never refused for money (no 402), and its own calls are billed to the same
        Account. A Study key can't make another, read the Usage API or sign in to the Connector: each answers 403
        `key_not_allowed`. Its rate limit is the Usage API's, 60 requests a minute per Account.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/StudyKeyRequest" }
            example:
              name: Your game against Ana
              url: https://claude.ai/public/artifacts/0b6c1f0e-2a51-4d37-9a5e-7d3f8a9c2e11
      responses:
        "201":
          description: The Study key, the only time its secret is shown.
          headers: *standardHeaders
          content:
            application/json:
              schema: { $ref: "#/components/schemas/StudyKey" }
              example:
                id: 9f8e7d6c-5b4a-4321-8fed-cba987654321
                key: ck_3fJ9aQ7LmP2xV8nR4tY6uW1zB5cD0eGhKkS7oN2pXqA0T9vQe
                name: Your game against Ana
                url: https://claude.ai/public/artifacts/0b6c1f0e-2a51-4d37-9a5e-7d3f8a9c2e11
                api_url: https://api.chessdrive.io
                apis: [generate, engine]
                limit_usd: "1.000000"
                expires_at: "2026-11-11T09:30:00Z"
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { $ref: "#/components/responses/Unauthorized" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "429": { $ref: "#/components/responses/RateLimited" }
        "500": { $ref: "#/components/responses/InternalError" }

components:
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      description: |
        `Authorization: Bearer ck_…`. Keys are `ck_` + 43 base62 characters + a 6-character base62 CRC32
        checksum. Shown once at creation. Server-side use only.

  headers:
    RequestId:
      description: Our id for this request (`req_…`), also in every error body. Quote it to support.
      schema: { type: string, examples: [req_01J9Z6Q8F3] }
    RateLimitLimit:
      description: |
        Requests allowed per minute: for this Account and Model on Generate and Embed, on Search for this Account,
        and on Engine for this Account and engine. Only the requests-per-minute limit is reported (and requests
        in flight, on Engine and Embed); the other limits show only as a 429 naming them.
      schema: { type: integer }
    RateLimitRemaining:
      description: Requests left this minute.
      schema: { type: integer }
    RateLimitReset:
      description: Seconds until the requests-per-minute bucket is full again.
      schema: { type: integer }
    RateLimitLimitConcurrent:
      description: Requests this Account may have in flight at once, on this engine or on Embed.
      schema: { type: integer }
    RateLimitRemainingConcurrent:
      description: Requests this Account may still start while the ones in flight run, on Engine or Embed.
      schema: { type: integer }
    RetryAfter:
      description: Seconds to wait before retrying, whichever limit refused the call (429 only).
      schema: { type: integer }

  responses:
    BadRequest:
      description: |
        `invalid_request_error`. Codes: `invalid_json`, `missing_field`, `invalid_field`, `unknown_model`,
        `invalid_fen`, `invalid_pgn`, `invalid_ply`, `context_too_long` (Generate), `too_many_inputs` and
        `text_too_long` (Embed), `unknown_engine`, `unknown_network`, `limit_too_high` and `game_over` (Engine).
      headers: { request-id: { $ref: "#/components/headers/RequestId" } }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            type: error
            error: { type: invalid_request_error, code: invalid_fen, message: "The FEN has 7 ranks; a board has 8.", param: position.fen }
            request_id: req_01J9Z6Q8F3
    BadQuery:
      description: |
        `invalid_request_error`. Code: `invalid_field`, with `param` naming the query parameter at fault (`from`, `to`
        or `group_by`).
      headers: { request-id: { $ref: "#/components/headers/RequestId" } }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            type: error
            error: { type: invalid_request_error, code: invalid_field, message: "to is a UTC date, yyyy-mm-dd.", param: to }
            request_id: req_01J9Z6Q8F3
    Unauthorized:
      description: "`authentication_error`. Codes: `missing_api_key`, `invalid_api_key`, `revoked_api_key`, `expired_api_key`, `disabled_api_key`."
      headers: { request-id: { $ref: "#/components/headers/RequestId" } }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    PaymentRequired:
      description: |
        `billing_error`: the call was refused for money, not speed. Codes: `insufficient_balance` (the Balance
        is used up, or has never held credits), `spend_limit_reached` (the Account's Spend limit for this month), `key_limit_reached`
        (this API key's Key limit for its period, with `resets_at`).
      headers:
        request-id: { $ref: "#/components/headers/RequestId" }
        x-ratelimit-limit-requests: { $ref: "#/components/headers/RateLimitLimit" }
        x-ratelimit-remaining-requests: { $ref: "#/components/headers/RateLimitRemaining" }
        x-ratelimit-reset-requests: { $ref: "#/components/headers/RateLimitReset" }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            type: error
            error: { type: billing_error, code: insufficient_balance, message: "Your balance is used up. Top up to continue." }
            request_id: req_01J9Z6Q8F3
    Forbidden:
      description: |
        `permission_error`. Codes: `account_suspended`, `key_not_allowed` (the API key is restricted to other APIs, or
        to another Model on an API that takes `model`; on `GET /v1/balance`, the key is a Team member's; a Study key
        anywhere but Engine and Generate), and
        `plan_required` (Queen on the Free plan past its 100 calls in any 7 days, counted per Account; Knight still
        works). A `plan_required` refusal carries the rate-limit headers, `Retry-After`, and `resets_at`, when the
        oldest of those calls leaves the 7 days. A Skill falls back to Knight on it; Hobby or Pro lifts it at once.
      headers: { request-id: { $ref: "#/components/headers/RequestId" } }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    TooLarge:
      description: "`invalid_request_error`. Code: `request_too_large` (the body is over 16 MB, or took over 30 seconds to arrive)."
      headers: { request-id: { $ref: "#/components/headers/RequestId" } }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    RateLimited:
      description: |
        `rate_limit_error`: slow down; `Retry-After` says how long. The code names the limit: `rate_limited`
        (requests per minute, Embed items per minute, or requests in flight on Engine and Embed), `daily_limit_reached` (Free's
        requests per day), `token_rate_limited` (tokens per minute, Generate).
      headers:
        request-id: { $ref: "#/components/headers/RequestId" }
        retry-after: { $ref: "#/components/headers/RetryAfter" }
        x-ratelimit-limit-requests: { $ref: "#/components/headers/RateLimitLimit" }
        x-ratelimit-remaining-requests: { $ref: "#/components/headers/RateLimitRemaining" }
        x-ratelimit-reset-requests: { $ref: "#/components/headers/RateLimitReset" }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    InternalError:
      description: "`api_error`. Code: `internal_error`."
      headers:
        request-id: { $ref: "#/components/headers/RequestId" }
        x-ratelimit-limit-requests: { $ref: "#/components/headers/RateLimitLimit" }
        x-ratelimit-remaining-requests: { $ref: "#/components/headers/RateLimitRemaining" }
        x-ratelimit-reset-requests: { $ref: "#/components/headers/RateLimitReset" }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    ComingSoon:
      description: |
        `api_error`. Code: `coming_soon`: the API, or the `engine` you named (with `param: engine`), is listed but
        isn't open yet. Refused straight after the key check, so it is never billed and counts toward no rate limit.
        Its opening is announced in the Changelog.
      headers: { request-id: { $ref: "#/components/headers/RequestId" } }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            type: error
            error: { type: api_error, code: coming_soon, message: "Lc0 is coming soon. Stockfish is live: send \"engine\": \"stockfish\".", param: engine }
            request_id: req_01J9Z6Q8F3
    Overloaded:
      description: "`overloaded_error`. Code: `upstream_unavailable`. Retry with backoff."
      headers:
        request-id: { $ref: "#/components/headers/RequestId" }
        x-ratelimit-limit-requests: { $ref: "#/components/headers/RateLimitLimit" }
        x-ratelimit-remaining-requests: { $ref: "#/components/headers/RateLimitRemaining" }
        x-ratelimit-reset-requests: { $ref: "#/components/headers/RateLimitReset" }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }

  schemas:
    # ---------- shared ----------
    RequestIdField:
      type: string
      description: Same value as the `request-id` header.
      examples: [req_01J9Z6Q8F3]
    Fen:
      type: string
      description: A position in Forsyth–Edwards Notation.
      examples: ["rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1"]
    Pgn:
      type: string
      description: >-
        A game in PGN. Only its main line counts; variations and comments are ignored. The main line holds at
        most 1,000 half-moves, and one request sends at most 256 KB of PGN, each distinct PGN counted once.
      examples: ["1. e4 e5 2. Nf3 Nc6 3. Bb5"]
    Ply:
      type: integer
      minimum: 0
      description: Half-moves into the PGN's main line; 0 is the start position.
    Position:
      description: |
        A FEN, or a PGN plus `ply`: the position after `ply` half-moves of the PGN's main line (0 = the start).
        Variations and comments in the PGN are ignored. For a side line, send its FEN, or a PGN whose main line it is.
      oneOf:
        - type: object
          required: [fen]
          additionalProperties: false
          properties:
            fen: { $ref: "#/components/schemas/Fen" }
        - type: object
          required: [pgn, ply]
          additionalProperties: false
          properties:
            pgn: { $ref: "#/components/schemas/Pgn" }
            ply: { $ref: "#/components/schemas/Ply" }
    Move:
      type: object
      required: [san, uci]
      properties:
        san: { type: string, examples: [Nf3] }
        uci: { type: string, examples: [g1f3] }
    Color:
      type: string
      enum: [white, black]
    CostUsd:
      type: string
      description: What this call drew from the Balance, as a decimal string in dollars.
      examples: ["0.000420"]
    Error:
      type: object
      required: [type, error, request_id]
      properties:
        type: { const: error }
        error:
          type: object
          required: [type, code, message]
          properties:
            type:
              type: string
              enum: [invalid_request_error, authentication_error, billing_error, permission_error, not_found_error, rate_limit_error, api_error, overloaded_error]
            code: { type: string, description: "A stable machine-readable code; see each response for the list." }
            message: { type: string, description: "For humans; may change. Never contains provider text." }
            param: { type: string, description: "The request field at fault, as a path: `position.fen`, `input[3].text`." }
            resets_at:
              type: string
              format: date-time
              description: |
                When the refusal lifts, RFC 3339 in UTC, such as the end of a Key limit's period on `key_limit_reached`,
                or when the next Queen call frees up on `plan_required`.
        request_id: { $ref: "#/components/schemas/RequestIdField" }
    StreamErrorEvent:
      description: |
        `event: error`. Same body as a non-streamed error. It ends the stream, and the call is not billed.
      allOf:
        - { $ref: "#/components/schemas/Error" }
    Item:
      description: |
        One typed item: a position, `{type: "position", fen}` or `{type: "position", pgn, ply}`, or a text,
        `{type: "text", text}`. Embed takes a list of them and Search one, as its query.
      oneOf:
        - { $ref: "#/components/schemas/PositionItem" }
        - { $ref: "#/components/schemas/TextItem" }
    PositionItem:
      description: |
        The shared Position, typed. Validated as on Generate and Engine. Embed reads up to 8 boards of a `{pgn, ply}`'s
        main line, oldest first, and a `{fen}` as the board alone, so compare positions sent the same way.
      oneOf:
        - type: object
          required: [type, fen]
          additionalProperties: false
          properties:
            type: { const: position }
            fen: { $ref: "#/components/schemas/Fen" }
        - type: object
          required: [type, pgn, ply]
          additionalProperties: false
          properties:
            type: { const: position }
            pgn: { $ref: "#/components/schemas/Pgn" }
            ply: { $ref: "#/components/schemas/Ply" }
    TextItem:
      type: object
      required: [type, text]
      additionalProperties: false
      properties:
        type: { const: text }
        text:
          type: string
          minLength: 1
          maxLength: 1000
          description: |
            On Embed, at most 77 tokens, about 300 characters. On Search, at most 1,000 characters. Never truncated
            (`text_too_long` on Embed, `query_too_long` on Search). Empty or whitespace-only text is `invalid_field`.

    # ---------- Generate ----------
    GenerateModelId:
      type: string
      description: |
        Knight or Queen: a versioned Model ID (`knight-1`, `queen-1`) or an alias for the latest version (`knight`,
        `queen`). The Embedding model is `invalid_field`.
      examples: [knight, knight-1, queen, queen-1]
    GenerateMessage:
      type: object
      required: [role, content]
      properties:
        role: { type: string, enum: [user, assistant] }
        content: { type: string, description: "Markdown. Assistant turns are sent back as received, `line:` links included." }
    GenerateRequest:
      type: object
      required: [model, messages]
      properties:
        model: { $ref: "#/components/schemas/GenerateModelId" }
        system: { type: string, description: "Instructions for the Model, ahead of the conversation." }
        messages:
          type: array
          minItems: 1
          description: The whole conversation, alternating `user` and `assistant`, ending with `user`.
          items: { $ref: "#/components/schemas/GenerateMessage" }
        position:
          allOf: [{ $ref: "#/components/schemas/Position" }]
          description: The position the conversation is about. Without one, `lines` is always empty.
        max_tokens:
          type: integer
          minimum: 1
          description: |
            The most output tokens to generate, up to the Model's output cap: 3,072 on Knight, 4,096 on Queen.
            Left out, it is 1,024 on Knight and 4,096 on Queen, whose reasoning can't be turned off.
            Over the cap is `invalid_field`. Estimated input plus `max_tokens` over the Model's context window is
            `context_too_long`, never silently clamped. Reasoning counts toward it, so a low `max_tokens` can cut the
            reply short or leave no room for it. A reply with no text is `upstream_unavailable`, unbilled.
        temperature: { type: number, minimum: 0, maximum: 1, default: 1 }
        stream: { type: boolean, default: false }
    GenerateLine:
      type: object
      description: A sequence of legal moves from a position, for a client to show on a board.
      required: [id, from_fen, moves]
      properties:
        id: { type: string, description: "Referenced from the prose as `[text](line:<id>)`.", examples: [L1] }
        from_fen: { $ref: "#/components/schemas/Fen" }
        moves:
          type: array
          minItems: 1
          items:
            allOf:
              - { $ref: "#/components/schemas/Move" }
              - type: object
                required: [fen]
                properties:
                  fen: { $ref: "#/components/schemas/Fen", description: "The position after this move." }
    TokenUsage:
      type: object
      description: |
        Generate is priced in tokens: every token the Model processes is billed, including the grounding we add and
        its reasoning. `cached_tokens` and `grounding_tokens` are part of `input_tokens`, and `reasoning_tokens` is
        part of `output_tokens`; each is 0 when there is none.
      required: [input_tokens, output_tokens, cached_tokens, grounding_tokens, reasoning_tokens]
      properties:
        input_tokens: { type: integer, minimum: 0, description: "Every input token, cached and grounding included." }
        output_tokens: { type: integer, minimum: 0, description: "Every output token, reasoning included." }
        cached_tokens:
          type: integer
          minimum: 0
          description: Input tokens read from cache (the conversation history a client resends), billed at the cached-input price.
        grounding_tokens:
          type: integer
          minimum: 0
          description: Input tokens we added to ground the Model in the position, billed as input.
        reasoning_tokens:
          type: integer
          minimum: 0
          description: Output tokens the Model spent reasoning before it answered, billed as output.
    FinishReason:
      type: string
      description: "`end` when the Model finished, `max_tokens` when it was cut off there."
      enum: [end, max_tokens]
    GenerateResponse:
      type: object
      required: [id, model, content, lines, finish_reason, usage, cost_usd]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        model: { type: string, description: "The versioned Model ID that served the request.", examples: [knight-1] }
        content:
          type: string
          description: Markdown; Lines are referenced as `[text](line:L1)`. A `line:` link with no matching Line is plain text.
        lines: { type: array, items: { $ref: "#/components/schemas/GenerateLine" } }
        finish_reason: { $ref: "#/components/schemas/FinishReason" }
        usage: { $ref: "#/components/schemas/TokenUsage" }
        cost_usd: { $ref: "#/components/schemas/CostUsd" }
    GenerateStreamEvent:
      description: |
        SSE with named events, in this order: `message_start`, any number of `text_delta`, one `line` per Line (after
        the text ends, since moves are checked on the finished reply), then `message_end`. The text streams as it is
        written, once its opening (the first sentence after about 40 words) has passed our checks, so a `line:` link
        whose Line is then dropped is shown as plain text. A failure after the 200 was sent, text sent or not,
        arrives as an `error` event and ends the stream; it is not billed. A client that hangs up before
        `message_end` is billed for the tokens processed so far.
      oneOf:
        - { $ref: "#/components/schemas/MessageStartEvent" }
        - { $ref: "#/components/schemas/TextDeltaEvent" }
        - { $ref: "#/components/schemas/LineEvent" }
        - { $ref: "#/components/schemas/MessageEndEvent" }
        - { $ref: "#/components/schemas/StreamErrorEvent" }
    MessageStartEvent:
      type: object
      description: "`event: message_start`"
      required: [id, model]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        model: { type: string, examples: [knight-1] }
    TextDeltaEvent:
      type: object
      description: "`event: text_delta`"
      required: [text]
      properties:
        text: { type: string }
    LineEvent:
      type: object
      description: "`event: line`"
      required: [line]
      properties:
        line: { $ref: "#/components/schemas/GenerateLine" }
    MessageEndEvent:
      type: object
      description: "`event: message_end`"
      required: [usage, cost_usd, finish_reason]
      properties:
        usage: { $ref: "#/components/schemas/TokenUsage" }
        cost_usd: { $ref: "#/components/schemas/CostUsd" }
        finish_reason: { $ref: "#/components/schemas/FinishReason" }

    # ---------- Embed ----------
    EmbedRequest:
      type: object
      required: [model, input]
      properties:
        model:
          type: string
          description: |
            A versioned Embedding model ID. There is no alias: vectors compare only within one version. Any other
            name, Knight and Queen included, is `unknown_model`.
          examples: [chessdrive-embed-1]
        input:
          type: array
          minItems: 1
          maxItems: 256
          description: 1 to 256 items, positions and texts mixed in any order. Over 256 is `too_many_inputs`.
          items: { $ref: "#/components/schemas/Item" }
        encoding_format:
          type: string
          enum: [float, base64]
          default: float
          description: >-
            `base64` gives each vector's bytes in base64: little-endian float32 numbers, one signed byte per number
            under `precision` `int8`, or the packed bits under `binary`.
        dimensions:
          type: integer
          enum: [64, 128, 256, 512]
          default: 512
          description: >-
            How long each vector is. A shorter vector is the first numbers of the full one, at unit length again:
            `chessdrive-embed-1` puts the most useful dimensions first, so it costs a little recall for a much
            smaller file. The price is the same.
        precision:
          type: string
          enum: [float32, int8, binary]
          default: float32
          description: >-
            How each number is stored. `int8` is an integer from -127 to 127, one byte each. `binary` is each
            number's sign, 1 for zero or above, packed 8 to a byte with the first dimension in the high bit:
            `dimensions` / 8 integers from 0 to 255. Compare int8 vectors by cosine and binary ones by Hamming
            distance. The price is the same.
    EmbedResponse:
      type: object
      required: [id, model, dimensions, data, usage, cost_usd]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        model: { type: string, examples: [chessdrive-embed-1] }
        dimensions:
          type: integer
          description: >-
            Each vector's length in dimensions: the request's `dimensions`, or 512 for `chessdrive-embed-1`. A binary
            vector holds `dimensions` / 8 bytes.
          examples: [512]
        data:
          type: array
          description: One vector per item, in request order. A float32 vector is L2-normalised.
          items:
            type: object
            required: [index, embedding]
            properties:
              index: { type: integer, minimum: 0, description: "The item's place in `input`." }
              embedding:
                description: >-
                  A list of numbers, integers under `precision` `int8` or `binary`, or a base64 string under
                  `encoding_format` `base64`.
                oneOf:
                  - { type: array, items: { type: number } }
                  - { type: string, contentEncoding: base64 }
        usage:
          type: object
          description: Items by kind, each with its own price; both are always present.
          required: [positions, texts]
          properties:
            positions: { type: integer, minimum: 0 }
            texts: { type: integer, minimum: 0 }
        cost_usd: { $ref: "#/components/schemas/CostUsd" }

    # ---------- Search ----------
    Speed:
      type: string
      description: A game's speed, by its time control.
      enum: [ultraBullet, bullet, blitz, rapid, classical, correspondence]
    GameResult:
      type: string
      enum: ["1-0", "0-1", "1/2-1/2"]
    YearMonth:
      type: string
      pattern: "^[0-9]{4}-(0[1-9]|1[0-2])$"
      examples: ["2026-09"]
    Venue:
      type: string
      description: Where a game was played.
      enum: [otb, online]
    Platform:
      type: string
      description: The platform an online game was played on.
      enum: [lichess, chesscom]
    SearchFilters:
      type: object
      description: >-
        All optional, combined with AND. `date`, `eco` and `result` mean the same in both modes. `rating`, `speed` and
        `player` are for a query (coming soon, and not promised), and `color` and `opponent` for a player's games; sent
        in the other mode, or with `position`, they are `invalid_field`.
      additionalProperties: false
      properties:
        rating:
          type: object
          x-coming-soon: true
          description: The players' average rating.
          additionalProperties: false
          properties:
            min: { type: integer, minimum: 0 }
            max: { type: integer, minimum: 0 }
        speed:
          type: array
          x-coming-soon: true
          minItems: 1
          description: Never matches a game of unknown speed. Leave it out to get those games.
          items: { $ref: "#/components/schemas/Speed" }
        date:
          type: object
          description: When the game was played, by month, both ends included.
          additionalProperties: false
          properties:
            from: { $ref: "#/components/schemas/YearMonth" }
            to: { $ref: "#/components/schemas/YearMonth" }
        player:
          type: object
          x-coming-soon: true
          required: [name]
          additionalProperties: false
          properties:
            name: { type: string, minLength: 1, description: "The player's name in the game, case ignored." }
            color: { $ref: "#/components/schemas/Color" }
        eco:
          type: array
          minItems: 1
          description: ECO codes or prefixes (`B90`, `C4`, `E`).
          items: { type: string, pattern: "^[A-E]([0-9]([0-9])?)?$" }
        result:
          type: array
          minItems: 1
          description: The game's result, from White's side as PGN writes it.
          items: { $ref: "#/components/schemas/GameResult" }
        color:
          allOf: [{ $ref: "#/components/schemas/Color" }]
          description: The side the player had.
        opponent:
          type: object
          description: The other side, by FIDE ID.
          required: [fide_id]
          additionalProperties: false
          properties:
            fide_id: { type: integer, minimum: 1 }
    SearchPlayer:
      type: object
      description: "`fide_id` or `name`, never both."
      additionalProperties: false
      properties:
        fide_id: { type: integer, minimum: 1, description: "A player on FIDE's list.", examples: [1503014] }
        name:
          type: string
          minLength: 1
          description: >-
            A name as FIDE's list writes it, "Carlsen, Magnus", case ignored. A name that could be several players
            answers their `candidates`.
          examples: ["Carlsen, Magnus"]
    SearchRequest:
      type: object
      description: "Exactly one of `position`, `player`, `where` and `query`: none is `missing_field`, two are `invalid_field`."
      properties:
        position:
          allOf: [{ $ref: "#/components/schemas/Position" }]
          description: Every move played from this Position in the Games database, most played first.
        player:
          allOf: [{ $ref: "#/components/schemas/SearchPlayer" }]
          description: The player whose games to find.
        where:
          type: object
          description: >-
            A Position filter: a test, true or false for each Position, whose Positions the answer holds. Board
            expressions give a set of squares: `{"piece": "wN"}` (`w` or `b`, then `P N B R Q K`), `{"attacks": "wB"}`
            or `{"attacks": "white"}` (own pieces count as attacked), `{"occupied": "white" | "black" | "any"}`,
            `{"squares": ["g8", "h7"]}`, `{"rank": 7}`, `{"file": "a"}`, `and`, `or` and `not`, `{"shift": [X, "N"]}`
            (one step: N S E W NE NW SE SW), `{"fill": [X, "N"]}` (1 to 7 steps), and `{"flip": X}` (colours swapped,
            ranks mirrored). Tests: `{"any": X}`, `{"none": X}`, `{"count": X, "gte" | "lte" | "eq": n}`,
            `{"to_move": "white" | "black"}`, `{"castling": "K" | "Q" | "k" | "q"}`, `{"en_passant": true}` or
            `{"en_passant": X}`, `all`, `some`, `not` and `flip`, and `{"ref": name}` for a part named in `define`.
            Each node is one key. A wrong filter is `invalid_filter`, with `param` at the node; past 2,000 nodes or 64
            levels once refs are replaced, it is too big.
          examples:
            - { all: [{ to_move: white }, { count: { piece: wN }, gte: 3 }] }
            - { any: { and: [{ piece: wN }, { or: [{ file: a }, { file: h }] }] } }
        define:
          type: object
          description: >-
            With `where`: named parts of the filter, each a board expression or a test, used as `{"ref": name}`. A part
            may use others, never itself.
          additionalProperties: { type: object }
          examples:
            - rook_ending:
                all:
                  - none: { or: [{ piece: wQ }, { piece: bQ }, { piece: wB }, { piece: bB }, { piece: wN }, { piece: bN }] }
                  - any: { piece: wR }
                  - any: { piece: bR }
        query:
          allOf: [{ $ref: "#/components/schemas/Item" }]
          x-coming-soon: true
          description: >-
            Coming soon, and not promised. Exactly one item, a position or a text. A text over 1,000 characters is
            `query_too_long`.
        top_k: { type: integer, minimum: 1, maximum: 50, default: 10, x-coming-soon: true, description: "With `query`: how many hits at most. No paging." }
        limit:
          type: integer
          minimum: 1
          maximum: 200
          description: >-
            With `player`, how many games at most (default 50); with `where`, how many Positions (default 20).
            `limit_too_high` past 200.
        cursor:
          type: string
          description: >-
            With `player` or `where`: the last answer's `next_cursor`, for the next page, sent with the same `player`
            and `filters`, or the same `where` and `define`. Opaque. A cursor from before the games were rebuilt is
            `cursor_expired`.
        pgn: { type: boolean, default: false, description: "With `player`: each game carries its PGN." }
        filters: { $ref: "#/components/schemas/SearchFilters" }
    Player:
      type: object
      description: One side of a game.
      required: [name, rating, title, fide_id]
      properties:
        name: { type: string }
        rating: { type: [integer, "null"], description: "Null when the game records none." }
        title: { type: [string, "null"], examples: [FM] }
        fide_id: { type: [integer, "null"], description: "Null means unknown, never a guess." }
    Game:
      type: object
      description: One game, the same in a Moment and among a player's games.
      required:
        - id
        - url
        - white
        - black
        - event
        - date
        - speed
        - speed_basis
        - time_control
        - eco
        - opening
        - result
        - venue
        - platform
        - rated
        - pgn
      properties:
        id: { type: string, description: "The game's id in the Games database, stable across its rebuilds." }
        url: { type: [string, "null"], format: uri, description: "The game on its platform. Null unless it was played online." }
        white: { $ref: "#/components/schemas/Player" }
        black: { $ref: "#/components/schemas/Player" }
        event: { type: [string, "null"] }
        date: { type: [string, "null"], format: date, description: "Null when the whole date isn't known." }
        speed:
          description: Null when unknown, never a guess, and a `speed` filter leaves those games out.
          oneOf:
            - { $ref: "#/components/schemas/Speed" }
            - { type: "null" }
        speed_basis:
          description: What decided `speed`. Null when the speed is unknown.
          oneOf:
            - type: string
              enum: [rating_list, source, time_control, event_name]
            - { type: "null" }
        time_control: { type: [string, "null"], examples: ["180+2"] }
        eco: { type: [string, "null"], examples: [B90] }
        opening: { type: [string, "null"] }
        result: { $ref: "#/components/schemas/GameResult" }
        venue:
          description: Where a game was played. Null when unknown, never a guess.
          oneOf:
            - { $ref: "#/components/schemas/Venue" }
            - { type: "null" }
        platform:
          description: The platform an online game was played on. Null unless it was played online.
          oneOf:
            - { $ref: "#/components/schemas/Platform" }
            - { type: "null" }
        rated: { type: [boolean, "null"], description: "Whether an online game was rated. Null unless it was played online." }
        pgn: { type: [string, "null"], description: "The game as PGN, when the call asks for it." }
    Moment:
      type: object
      description: One ply of a real game.
      required: [game, ply, fen, move]
      properties:
        game: { $ref: "#/components/schemas/Game" }
        ply: { $ref: "#/components/schemas/Ply" }
        fen: { $ref: "#/components/schemas/Fen" }
        move:
          description: The move that led to this ply; null at ply 0.
          oneOf:
            - { $ref: "#/components/schemas/Move" }
            - { type: "null" }
    SearchHit:
      type: object
      required: [score, moment]
      properties:
        score:
          type: number
          minimum: 0
          maximum: 1
          description: Higher is closer; 1 is an identical position. Comparable only within one Corpus version.
        moment: { $ref: "#/components/schemas/Moment" }
    SearchResponse:
      type: object
      x-coming-soon: true
      description: "Coming soon, and not promised: this can change before a query opens."
      required: [id, model, corpus, hits, usage, cost_usd]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        model: { type: string, description: "The Embedding model version the Corpus was built with.", examples: [chessdrive-embed-1] }
        corpus: { type: string, description: "The Corpus version.", examples: [corpus-2026-09] }
        hits:
          type: array
          description: Sorted by `score`, highest first, at most one per game.
          items: { $ref: "#/components/schemas/SearchHit" }
        usage:
          type: object
          required: [queries]
          properties:
            queries: { type: integer, minimum: 0 }
        cost_usd: { $ref: "#/components/schemas/CostUsd" }
    PlayerRatings:
      type: object
      description: The player's ratings on FIDE's list, null when they have none.
      required: [standard, rapid, blitz]
      properties:
        standard: { type: [integer, "null"] }
        rapid: { type: [integer, "null"] }
        blitz: { type: [integer, "null"] }
    PlayerProfile:
      type: object
      description: The player a call found, as FIDE's list has them.
      required: [fide_id, name, federation, title, ratings, birth_year]
      properties:
        fide_id: { type: integer, examples: [1503014] }
        name: { type: string, examples: ["Carlsen, Magnus"] }
        federation: { type: [string, "null"], examples: [NOR] }
        title: { type: [string, "null"], examples: [GM] }
        ratings: { $ref: "#/components/schemas/PlayerRatings" }
        birth_year: { type: [integer, "null"] }
    PlayerCandidate:
      type: object
      description: One player an ambiguous name could be.
      required: [fide_id, name, federation, title, ratings]
      properties:
        fide_id: { type: integer }
        name: { type: string }
        federation: { type: [string, "null"] }
        title: { type: [string, "null"] }
        ratings: { $ref: "#/components/schemas/PlayerRatings" }
    PlayerGame:
      type: object
      required: [color, game]
      properties:
        color:
          allOf: [{ $ref: "#/components/schemas/Color" }]
          description: The side the player had.
        game: { $ref: "#/components/schemas/Game" }
    SearchGamesResponse:
      type: object
      description: A player's games. It has no `model` or `corpus`, and names no source.
      required: [id, match, player, candidates, games, next_cursor, usage, cost_usd]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        match:
          type: string
          description: >-
            `fide`: one player on FIDE's list, with their games. `ambiguous`: a name that could be several, in
            `candidates`, with no games and nothing billed.
          enum: [fide, ambiguous]
        player:
          description: Null on an ambiguous name.
          oneOf:
            - { $ref: "#/components/schemas/PlayerProfile" }
            - { type: "null" }
        candidates:
          type: array
          maxItems: 5
          description: On an ambiguous name, the players it could be. Call again with one's `fide_id`. Empty otherwise.
          items: { $ref: "#/components/schemas/PlayerCandidate" }
        games:
          type: array
          description: Newest first.
          items: { $ref: "#/components/schemas/PlayerGame" }
        next_cursor:
          type: [string, "null"]
          description: >-
            Send as `cursor`, with the same `player` and `filters`, for the next page. Null on the last page. It
            expires when the games are rebuilt.
        usage:
          type: object
          required: [games]
          properties:
            games:
              type: integer
              minimum: 0
              description: The true count. The bill counts at least one game, except on an ambiguous name, which is free.
        cost_usd: { $ref: "#/components/schemas/CostUsd" }
    PositionMove:
      type: object
      description: One move played from the Position, and how the games that played it ended.
      required: [uci, san, count, white_wins, draws, black_wins]
      properties:
        uci: { type: string, examples: [e2e4] }
        san: { type: string, examples: [e4] }
        count: { type: integer, minimum: 1, description: "How many games played it." }
        white_wins: { type: integer, minimum: 0 }
        draws: { type: integer, minimum: 0 }
        black_wins: { type: integer, minimum: 0 }
    SearchMovesResponse:
      type: object
      description: >-
        Every move played from a Position in the Games database, most played first. It has no `model` or `corpus`,
        and names no source.
      required: [id, fen, moves, usage, cost_usd]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        fen: { $ref: "#/components/schemas/Fen" }
        moves:
          type: array
          description: Empty when no stored game reaches the Position.
          items: { $ref: "#/components/schemas/PositionMove" }
        usage:
          type: object
          required: [queries]
          properties:
            queries: { type: integer, minimum: 0, description: "Always 1." }
        cost_usd: { $ref: "#/components/schemas/CostUsd" }

    PositionExample:
      type: object
      description: A game that reaches the Position, and the ply at which it first does.
      required: [ply, game]
      properties:
        ply: { $ref: "#/components/schemas/Ply" }
        game: { $ref: "#/components/schemas/Game" }
    FoundPosition:
      type: object
      description: One Position the filter holds for.
      required: [fen, occurrences, quiet, examples]
      properties:
        fen: { $ref: "#/components/schemas/Fen" }
        occurrences: { type: integer, minimum: 1, description: "How many times the games reach it." }
        quiet:
          type: boolean
          description: The side to move is out of check and has no capture or promotion that wins material.
        examples:
          type: array
          maxItems: 1
          description: The highest-rated game that reaches it, without its moves.
          items: { $ref: "#/components/schemas/PositionExample" }
    SearchPositionsResponse:
      type: object
      description: >-
        The Positions a filter holds for, in the Games database's own order. It has no `model` or `corpus`, and names
        no source.
      required: [id, positions, next_cursor, usage, cost_usd]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        positions:
          type: array
          description: Empty when the filter holds for no stored Position.
          items: { $ref: "#/components/schemas/FoundPosition" }
        next_cursor:
          type: [string, "null"]
          description: >-
            Send as `cursor`, with the same `where` and `define`, for the next page. Null on the last page. It expires
            when the games are rebuilt.
        usage:
          type: object
          required: [positions]
          properties:
            positions:
              type: integer
              minimum: 0
              description: The true count. The bill counts at least one Position.
        cost_usd: { $ref: "#/components/schemas/CostUsd" }

    # ---------- Engine ----------
    EngineName:
      type: string
      description: Stockfish, or Lc0, which is coming soon; a call naming `lc0` returns 501 `coming_soon`.
      enum: [stockfish, lc0]
    Network:
      type: string
      description: |
        Lc0's network: `bt4` (the default), `t82` or `t1-256`. Only Lc0 takes one; on Stockfish it is `invalid_field`.
      enum: [bt4, t82, t1-256]
    EngineRequest:
      type: object
      description: Send `position` or `positions`, not both.
      required: [engine]
      properties:
        engine:
          allOf: [{ $ref: "#/components/schemas/EngineName" }]
          description: Any other name is `unknown_engine`.
        position: { $ref: "#/components/schemas/EnginePosition" }
        positions:
          type: array
          minItems: 1
          maxItems: 100
          description: >-
            1 to 100 positions to analyse in one call, instead of `position`. Over 100 is `too_many_inputs`.
          items: { $ref: "#/components/schemas/Position" }
        depth:
          type: integer
          minimum: 1
          maximum: 50
          description: >-
            Stockfish only (`invalid_field` on Lc0). Stockfish's default is `depth` 20 on a position and 14 on each
            position of a whole game or a list. On a whole game leave it out: at `depth` 20 a game of 25 moves or
            more passes the 60 s a call has and fails as `limit_too_high`.
        nodes:
          type: integer
          minimum: 1
          maximum: 1000000000
          description: At most 1,000,000,000 on Stockfish and 2,000,000 visits on Lc0, whose default is `nodes` 10,000.
        movetime_ms: { type: integer, minimum: 1, maximum: 60000 }
        lines:
          type: integer
          minimum: 1
          maximum: 5
          default: 1
          description: How many ranked Lines to return. A whole game takes only 1.
        network: { $ref: "#/components/schemas/Network" }
        stream: { type: boolean, default: false, description: "Not on a whole game or a list of positions." }
    EnginePosition:
      description: |
        A position, as the other APIs take it (a FEN, or a PGN plus `ply`), or a whole game: a PGN with no `ply`
        runs Engine on every position of its main line.
      oneOf:
        - { $ref: "#/components/schemas/Position" }
        - type: object
          required: [pgn]
          additionalProperties: false
          properties:
            pgn: { $ref: "#/components/schemas/Pgn" }
    Wdl:
      type: object
      description: Win, draw and loss chances for White, per mille.
      required: [win, draw, loss]
      properties:
        win: { type: integer, minimum: 0, maximum: 1000 }
        draw: { type: integer, minimum: 0, maximum: 1000 }
        loss: { type: integer, minimum: 0, maximum: 1000 }
    EngineLine:
      type: object
      description: One ranked Line, its score from White's point of view. Exactly one of `cp` and `mate` is set.
      required: [rank, depth, cp, mate, wdl, moves]
      properties:
        rank: { type: integer, minimum: 1 }
        depth: { type: integer, minimum: 1 }
        cp: { type: [integer, "null"], description: "Centipawns." }
        mate: { type: [integer, "null"], description: "Moves to mate; positive means White mates." }
        wdl: { $ref: "#/components/schemas/Wdl" }
        moves: { type: array, minItems: 1, items: { $ref: "#/components/schemas/Move" } }
    EngineAnalysis:
      type: object
      description: The analysis so far.
      required: [id, engine, version, network, fen, depth, seldepth, nodes, time_ms, best_move, lines]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        engine: { $ref: "#/components/schemas/EngineName" }
        version: { type: string, examples: [Stockfish 19] }
        network:
          description: The Network Lc0 ran; null on Stockfish.
          oneOf:
            - { $ref: "#/components/schemas/Network" }
            - { type: "null" }
        fen: { $ref: "#/components/schemas/Fen" }
        depth: { type: integer, minimum: 1 }
        seldepth: { type: integer, minimum: 1 }
        nodes: { type: integer, minimum: 0 }
        time_ms: { type: integer, minimum: 0 }
        best_move: { $ref: "#/components/schemas/Move" }
        lines: { type: array, minItems: 1, items: { $ref: "#/components/schemas/EngineLine" } }
    EngineStopReason:
      type: string
      description: "`limit` when the requested limit was reached, `time_cap` when the time cap stopped it."
      enum: [limit, time_cap]
    EngineResponse:
      allOf:
        - { $ref: "#/components/schemas/EngineAnalysis" }
        - type: object
          required: [stop_reason, usage, cost_usd]
          properties:
            stop_reason: { $ref: "#/components/schemas/EngineStopReason" }
            usage:
              type: object
              description: Engine time, the engine's own search time. The bill counts at least 100 ms a call.
              required: [engine_ms]
              properties:
                engine_ms: { type: integer, minimum: 0 }
            cost_usd: { $ref: "#/components/schemas/CostUsd" }
    EngineEval:
      type: object
      description: |
        A position's evaluation from White's point of view. Exactly one of `cp` and `mate` is set; `mate` 0 is a
        checkmate on the board, and `wdl` says who won.
      required: [cp, mate, wdl]
      properties:
        cp: { type: [integer, "null"], description: "Centipawns." }
        mate: { type: [integer, "null"], description: "Moves to mate; positive means White mates." }
        wdl: { $ref: "#/components/schemas/Wdl" }
    MoveVerdict:
      type: string
      description: |
        How good the move was, by the win chance it lost for the side that played it, the way Lichess judges: `best`
        is Engine's own best move; otherwise 0.3 or more lost is a `blunder`, 0.2 a `mistake`, 0.1 an `inaccuracy`,
        and less is `good`.
      enum: [best, good, inaccuracy, mistake, blunder]
    EngineGameMove:
      type: object
      description: One move of the game's main line, judged by Engine.
      required: [ply, move_number, color, move, fen, eval_before, eval_after, win_chance_lost, verdict, best_line]
      properties:
        ply:
          type: integer
          minimum: 0
          description: >-
            The position the move was played from, as `{pgn, ply}` names it: 0 for White's first move. Send it as
            the `position` of a Generate call to talk about this move.
        move_number: { type: integer, minimum: 1, description: "The move's number, as a PGN writes it." }
        color: { $ref: "#/components/schemas/Color" }
        move: { $ref: "#/components/schemas/Move" }
        fen: { $ref: "#/components/schemas/Fen" }
        eval_before: { $ref: "#/components/schemas/EngineEval" }
        eval_after: { $ref: "#/components/schemas/EngineEval" }
        win_chance_lost:
          type: number
          minimum: 0
          maximum: 2
          description: >-
            The win chance the move lost for the side that played it, on Lichess's scale from -1 to +1:
            `2 / (1 + exp(-0.00368208 × cp)) - 1`, and ±1 for a mate. 0 when it lost none.
        verdict: { $ref: "#/components/schemas/MoveVerdict" }
        best_line:
          type: array
          minItems: 1
          maxItems: 8
          description: >-
            Engine's best Line from `fen`, its first 8 half-moves at most; `eval_before` is its score. For the
            whole Line or more Lines, call Engine on `{pgn, ply}`.
          items: { $ref: "#/components/schemas/Move" }
    EngineGameResponse:
      type: object
      description: A whole game reviewed, one entry per move of the PGN's main line, in order.
      required: [id, engine, version, network, moves, usage, cost_usd]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        engine: { $ref: "#/components/schemas/EngineName" }
        version: { type: string, examples: [Stockfish 19] }
        network:
          description: The Network Lc0 ran; null on Stockfish.
          oneOf:
            - { $ref: "#/components/schemas/Network" }
            - { type: "null" }
        moves:
          type: array
          items: { $ref: "#/components/schemas/EngineGameMove" }
        usage:
          type: object
          description: >-
            Engine time, the engine's own search time on every position together. The bill counts at least 100 ms.
          required: [engine_ms]
          properties:
            engine_ms: { type: integer, minimum: 0 }
        cost_usd: { $ref: "#/components/schemas/CostUsd" }
    EngineBatchResult:
      type: object
      description: |
        One position of a list. `status` says what happened: `ok`, analysed, with every field below; `game_over`,
        a position with no legal moves, not analysed or billed; `not_run`, not reached, not billed, to send again.
      required: [status, fen]
      properties:
        status: { type: string, enum: [ok, game_over, not_run] }
        fen: { $ref: "#/components/schemas/Fen" }
        depth: { type: integer, minimum: 1 }
        seldepth: { type: integer, minimum: 1 }
        nodes: { type: integer, minimum: 0 }
        time_ms: { type: integer, minimum: 0 }
        stop_reason: { $ref: "#/components/schemas/EngineStopReason" }
        best_move: { $ref: "#/components/schemas/Move" }
        lines:
          type: array
          description: The ranked Lines, each its first 8 half-moves at most.
          items: { $ref: "#/components/schemas/EngineLine" }
    EngineBatchResponse:
      type: object
      description: A list of positions analysed, one result per position, in the order they were sent.
      required: [id, engine, version, network, results, usage, cost_usd]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        engine: { $ref: "#/components/schemas/EngineName" }
        version: { type: string, examples: [Stockfish 19] }
        network:
          description: The Network Lc0 ran; null on Stockfish.
          oneOf:
            - { $ref: "#/components/schemas/Network" }
            - { type: "null" }
        results:
          type: array
          items: { $ref: "#/components/schemas/EngineBatchResult" }
        usage:
          type: object
          description: >-
            Engine time, the engine's own search time on every `ok` position together. The bill counts at least 100 ms.
          required: [engine_ms]
          properties:
            engine_ms: { type: integer, minimum: 0 }
        cost_usd: { $ref: "#/components/schemas/CostUsd" }
    EngineStreamEvent:
      description: |
        SSE with named events, in this order: `analysis_start`, one `depth` per completed depth, then `analysis_end`
        with the full body. A failure after the 200 was sent arrives as an `error` event and ends the stream; it is
        not billed. A client that hangs up before `analysis_end` is billed for the Engine time so far.
      oneOf:
        - { $ref: "#/components/schemas/AnalysisStartEvent" }
        - { $ref: "#/components/schemas/DepthEvent" }
        - { $ref: "#/components/schemas/AnalysisEndEvent" }
        - { $ref: "#/components/schemas/StreamErrorEvent" }
    AnalysisStartEvent:
      type: object
      description: "`event: analysis_start`"
      required: [id, engine, version, network]
      properties:
        id: { $ref: "#/components/schemas/RequestIdField" }
        engine: { $ref: "#/components/schemas/EngineName" }
        version: { type: string }
        network:
          oneOf:
            - { $ref: "#/components/schemas/Network" }
            - { type: "null" }
    DepthEvent:
      description: "`event: depth`, the analysis after each completed depth."
      allOf:
        - { $ref: "#/components/schemas/EngineAnalysis" }
    AnalysisEndEvent:
      description: "`event: analysis_end`, the full body."
      allOf:
        - { $ref: "#/components/schemas/EngineResponse" }

    # ---------- Models ----------
    Api:
      type: string
      enum: [generate, embed, search, engine]
    ModelList:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items:
            type: object
            required: [id, aliases, name, apis, context_window, embed_dimensions, downloadable, status]
            properties:
              id: { type: string, examples: [knight-1] }
              aliases: { type: array, items: { type: string }, description: "Empty for the Embedding model, which has none." }
              name: { type: string, description: "The public name, e.g. Knight." }
              apis:
                type: array
                description: The APIs that take this Model as `model`.
                items: { $ref: "#/components/schemas/Api" }
              context_window:
                type: [integer, "null"]
                description: Tokens, on Generate; over it is 400 `context_too_long`. Null for the Embedding model.
              embed_dimensions: { type: [integer, "null"], description: "Each vector's length, on Embed. Null otherwise." }
              downloadable: { type: boolean }
              status:
                type: string
                enum: [available, coming_soon]
                x-enum-varnames: [ModelAvailable, ModelComingSoon]
                description: "`coming_soon` for a Model that is listed but isn't open yet: a call naming it returns 501 `coming_soon`."

    # ---------- the Usage API ----------
    Usd:
      type: string
      description: An amount in dollars, as a decimal string to six places, like `cost_usd`.
      examples: ["4.213500"]
    UsageGroupBy:
      type: string
      enum: [api, model, key]
      x-enum-varnames: [UsageByAPI, UsageByModel, UsageByKey]
      default: api
      description: |
        `api`: one series per API. `model`: one per Model of Generate and Embed, with `""` (`No Model`) for the calls
        that name none: Search's, Engine's, and those refused before their Model was known. `key`: one per API key,
        revoked ones included.
    UsageSeries:
      type: object
      required: [id, name, requests, cost_usd]
      properties:
        id:
          type: string
          description: |
            The API (`generate`), the Model ID (`knight-1`, or `""`), the API key's id, or `playground` for the
            Dashboard's Playground calls.
        name:
          type: string
          description: The Model's or the key's name, `No Model` or `Playground`; for an API, its id.
        requests:
          type: array
          description: The calls each day, failed ones included, in the order of `days`.
          items: { type: integer, minimum: 0 }
        cost_usd:
          type: array
          description: What the calls drew from the Balance each day, in the order of `days`. Only successes cost anything.
          items: { $ref: "#/components/schemas/Usd" }
    UsageResponse:
      type: object
      required: [from, to, group_by, days, series, errors, total]
      properties:
        from: { type: string, format: date }
        to: { type: string, format: date }
        group_by: { $ref: "#/components/schemas/UsageGroupBy" }
        days:
          type: array
          description: Every UTC day from `from` to `to`, in order.
          items: { type: string, format: date }
        series:
          type: array
          description: |
            One per API, Model or key with calls in the range, none for those without: APIs in this contract's
            order, Models in `GET /v1/models`'s order (then any no longer served, then `""`), keys oldest first, and
            the Playground last.
          items: { $ref: "#/components/schemas/UsageSeries" }
        errors:
          type: array
          description: The calls that failed each day, across every series, in the order of `days`.
          items: { type: integer, minimum: 0 }
        total:
          type: object
          description: Every series over the whole range.
          required: [requests, cost_usd]
          properties:
            requests: { type: integer, minimum: 0 }
            cost_usd: { $ref: "#/components/schemas/Usd" }
    StudyKeyRequest:
      type: object
      required: [name]
      additionalProperties: false
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 100
          description: The Study's name, as its title says, which the Dashboard lists the key by.
        url:
          type: [string, "null"]
          format: uri
          description: |
            The Study's `https` link, such as a Claude artifact's, which the Dashboard links to. Leave it out for a
            local file, which the Dashboard can't open.
    StudyKey:
      type: object
      required: [id, key, name, url, api_url, apis, limit_usd, expires_at]
      properties:
        id:
          type: string
          format: uuid
          description: The key's ID, as the Dashboard knows it.
        key:
          type: string
          description: "The secret, shown this once. The page sends it as `Authorization: Bearer <key>`."
        name:
          type: string
          description: The Study's name.
        url:
          type: [string, "null"]
          description: The Study's link, or null.
        api_url:
          type: string
          description: Where the page calls Engine and Generate, this API's address.
        apis:
          type: array
          items: { type: string, enum: [generate, engine] }
          description: The APIs the key may call.
        limit_usd:
          allOf: [{ $ref: "#/components/schemas/Usd" }]
          description: The Key limit, per UTC day.
        expires_at:
          type: string
          format: date-time
          description: When the key stops working, 7 days after it was made.
    BalanceResponse:
      type: object
      required: [plan, balance_usd, monthly_credit_usd, monthly_credit_expires_at, trial_credits_usd, trial_credits_expire_at, month_spend_usd, spend_limit_usd]
      properties:
        plan:
          type: string
          enum: [free, hobby, pro]
          x-enum-varnames: [PlanFree, PlanHobby, PlanPro]
          description: |
            The Account's Plan, which sets its rate limits. Every Account starts on `free`; a Top-up never changes it.
            On `free`, Queen takes 100 calls in any 7 days, then answers 403 `plan_required`.
        balance_usd:
          allOf: [{ $ref: "#/components/schemas/Usd" }]
          description: |
            What is left to spend on calls, Monthly credit and Promo credits included. At 0 or below, calls are refused
            with 402 `insufficient_balance`; a call already running may take it a little below 0.
        monthly_credit_usd:
          allOf: [{ $ref: "#/components/schemas/Usd" }]
          description: |
            The Monthly credit left from the paid Plan's current month, part of `balance_usd` and spent before any other
            dollars. `0.000000` on Free.
        monthly_credit_expires_at:
          type: [string, "null"]
          format: date-time
          description: When the Monthly credit left expires, at the end of the Plan's month. Null when none is left.
        trial_credits_usd:
          allOf: [{ $ref: "#/components/schemas/Usd" }]
          description: |
            The Trial credits left, part of `balance_usd`. They are spent after Monthly credit and expiring Promo
            credits, and before Top-ups.
        trial_credits_expire_at:
          type: [string, "null"]
          format: date-time
          description: |
            When the Trial credits left expire. Null when none are left, or when they never expire, as Trial credits
            given today don't.
        month_spend_usd:
          allOf: [{ $ref: "#/components/schemas/Usd" }]
          description: The spend this calendar month in UTC, which the Spend limit counts against.
        spend_limit_usd:
          type: [string, "null"]
          description: |
            The Spend limit for each calendar month, in dollars like `cost_usd`; once `month_spend_usd` reaches it,
            calls are refused with 402 `spend_limit_reached`. Null when the Account has none.
