# Source of truth for the public TryItOn API (/api/v1). Derived from the code:
#   routes/developer/v1Routes.js, controllers/developer/v1/, services/liveApiSessions.js, services/liveGarments.js,
#   constants/tryon.js, utils/AppError.js, utils/globalErrorHandler.js.
# Edit HERE only, then run `node tryiton-sdk/sync-contract.mjs` to publish the copy in tryiton-documentation/public/.
# test/api-contract/openapi.test.js fails when a router path and this file drift apart.
# Embed (/embed/*) and internal-key routes are deliberately left out.

openapi: 3.1.0

info:
  title: TryItOn API
  version: 2.1.0
  summary: Photoreal AI virtual try-on for fashion, hairstyles, tattoos and live video.
  description: |
    The public TryItOn API. Photo try-ons are asynchronous. Submit with `POST /tryon/fashion`, `/tryon/hairstyle`
    or `/tryon/tattoo`, which return a `jobId` with `201`. Then poll `GET /status/{id}` until `status` is
    `completed` (read `output`) or `failed` (read `error`).

    **Authentication.** Every endpoint except `GET /health` and the three live *device* endpoints takes your API key
    as `Authorization: Bearer YOUR_API_KEY`. A missing or unknown key is rejected with **403** `Forbidden`, not 401.
    The live device endpoints (`/live/sessions/{id}/heartbeat`, `/garments/{garmentId}`, `/end`) take the session's
    `clientSecret` instead, so the API key never reaches a browser or app.

    **Images** are a public `http(s)` URL or a base64 data URI (`data:image/png;base64,...`). JSON bodies are limited
    to 12 MB on `/tryon/*` and `/live/garments`, and to 10 KB everywhere else. A larger body gets **413**
    `PayloadTooLarge`.

    **Credits.** Photo try-ons cost 1 credit per output image (`num_samples`). Credits are held while a job runs and
    released if it fails. Live try-on is billed in ticks of `secondsPerCredit` seconds (see `GET /live/config`).

    **Errors** use one envelope: `{ "ok": false, "error": { "name": "...", "message": "..." } }`. Branch on
    `error.name`; `message` is human-readable and may change. Successful responses carry `"ok": true`. A request
    body that isn't valid JSON is answered with 400 `BadRequest` ("Request body is not valid JSON.").

    **Rate limits.** Every endpoint shares a limit of 300 requests per minute per IP. On top of that:
    `/tryon/*` 10 per minute per account; `POST /live/garments` 120 per minute per account; `POST /live/sessions`
    300 per hour per account; per IP, `heartbeat` 90 per minute, garment switch 30 per minute and `end` 120 per
    minute. Exceeding a limit returns **429** `RateLimitExceeded`.

    **Concurrency.** A new photo try-on or live session is refused with **429** `ConcurrencyLimitExceeded` while 5 or
    more credits are held by in-flight work on the account (a `num_samples: 4` job holds 4, a live session holds 1).
    At most 3 live sessions stream at once per account (**429** `LiveTryonBusy`).
  contact:
    name: TryItOn API
    url: https://docs.tryiton.now
    email: contact@tryiton.now
  license:
    name: Proprietary
    url: https://tryiton.now/legal/tos

servers:
  - url: https://tryiton.now/api/v1
    description: Production

security:
  - bearerAuth: []

tags:
  - name: Health
    description: Liveness probe.
  - name: Try-On
    description: Submit an asynchronous photo try-on. Each returns a `jobId` to poll.
  - name: Jobs
    description: Poll a submitted try-on for its result.
  - name: Account
    description: Credit balance.
  - name: Live (server)
    description: |
      Real-time webcam try-on, called from **your server** with the API key: prepare garments, start, inspect and
      stop sessions. Send the whole start response to the end user's device.
  - name: Live (device)
    description: |
      Called from the **end user's device** during a live session (the `tryiton-live` SDK does this for you).
      Authenticated by the session's `clientSecret`, never the API key, and open to cross-origin requests from any
      site.

paths:
  /health:
    get:
      tags: [Health]
      summary: Liveness probe
      description: Unauthenticated. For uptime monitors. Counts against the per-IP limit.
      operationId: getHealth
      security: []
      responses:
        "200":
          description: The API is up.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/HealthResponse"
              example:
                ok: true
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

  /tryon/fashion:
    post:
      tags: [Try-On]
      summary: Try a garment or accessory on a person
      description: |
        Puts the item in `garment_image` on the person in `model_image` and returns a `jobId`.

        `category` says what the item is. Leave it out (or send `auto` with no `subcategory`) and the item is
        detected from the image. `clothing`, `jewelry` and `accessories` need a `subcategory` from their own list;
        `eyewear`, `footwear`, `headwear` and `others` must not have one.

        `clothing` goes to the clothing engine, every other category to the accessory engine. The flow and the
        response are the same either way.
      operationId: tryOnFashion
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/FashionTryonRequest"
            examples:
              top:
                summary: A top on a model
                value:
                  model_image: https://example.com/model.jpg
                  garment_image: https://example.com/shirt.jpg
                  category: clothing
                  subcategory: tops
              autoDetect:
                summary: Let the API detect the item
                value:
                  model_image: https://example.com/model.jpg
                  garment_image: https://example.com/product.jpg
              necklace:
                summary: Jewelry with two outputs as JPEG
                value:
                  model_image: https://example.com/model.jpg
                  garment_image: https://example.com/necklace.png
                  category: jewelry
                  subcategory: necklaces
                  num_samples: 2
                  output_format: jpeg
              sneakers:
                summary: Single-placement category (no subcategory)
                value:
                  model_image: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==
                  garment_image: https://example.com/sneakers.jpg
                  category: footwear
      responses:
        "201":
          $ref: "#/components/responses/JobAccepted"
        "400":
          description: Invalid request.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                modelImageMissing:
                  $ref: "#/components/examples/ErrModelImageMissing"
                garmentImageMissing:
                  $ref: "#/components/examples/ErrGarmentImageMissing"
                invalidCategory:
                  $ref: "#/components/examples/ErrInvalidCategory"
                invalidNumSamples:
                  $ref: "#/components/examples/ErrInvalidNumSamples"
                invalidOutputFormat:
                  $ref: "#/components/examples/ErrInvalidOutputFormat"
                invalidModerationLevel:
                  $ref: "#/components/examples/ErrInvalidModerationLevel"
        "403":
          $ref: "#/components/responses/ForbiddenOrDisabled"
        "404":
          $ref: "#/components/responses/UserNotFound"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "429":
          $ref: "#/components/responses/TryonTooManyRequests"
        "500":
          $ref: "#/components/responses/TryonEnqueueFailed"

  /tryon/hairstyle:
    post:
      tags: [Try-On]
      summary: Try a haircut (and optionally a hair color) on a person
      description: Restyles the hair in `face_image` to `haircut` and returns a `jobId`.
      operationId: tryOnHairstyle
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/HairstyleTryonRequest"
            examples:
              buzzCut:
                summary: Buzz cut, keep the current color
                value:
                  face_image: https://example.com/face.jpg
                  haircut: BuzzCut
              colored:
                summary: Long wavy with a new color
                value:
                  face_image: https://example.com/face.jpg
                  haircut: LongWavy
                  hair_color: ash blonde with subtle highlights
                  num_samples: 2
                  output_format: png
      responses:
        "201":
          $ref: "#/components/responses/JobAccepted"
        "400":
          description: Invalid request.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                faceImageRequired:
                  $ref: "#/components/examples/ErrFaceImageRequired"
                haircutRequired:
                  $ref: "#/components/examples/ErrHaircutRequired"
                invalidHaircut:
                  $ref: "#/components/examples/ErrInvalidHaircut"
                invalidNumSamples:
                  $ref: "#/components/examples/ErrInvalidNumSamples"
                invalidOutputFormat:
                  $ref: "#/components/examples/ErrInvalidOutputFormat"
        "403":
          $ref: "#/components/responses/ForbiddenOrDisabled"
        "404":
          $ref: "#/components/responses/UserNotFound"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "429":
          $ref: "#/components/responses/TryonTooManyRequests"
        "500":
          $ref: "#/components/responses/TryonEnqueueFailed"

  /tryon/tattoo:
    post:
      tags: [Try-On]
      summary: Try a tattoo design on skin
      description: |
        Inks `design_image` onto the skin in `body_image` and returns a `jobId`.

        Say where with `placement` (free text), `region` (an exact rectangle), or both. With a `region`, `placement`
        only describes size and style.
      operationId: tryOnTattoo
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TattooTryonRequest"
            examples:
              placementText:
                summary: Placement as free text
                value:
                  body_image: https://example.com/forearm.jpg
                  design_image: https://example.com/design.png
                  placement: on the right forearm, small
              region:
                summary: Exact region plus style notes
                value:
                  body_image: https://example.com/arm.jpg
                  design_image: https://example.com/design.png
                  placement: fine-line, black ink
                  region:
                    x: 0.32
                    y: 0.18
                    w: 0.28
                    h: 0.34
      responses:
        "201":
          $ref: "#/components/responses/JobAccepted"
        "400":
          description: Invalid request.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                invalidRegion:
                  $ref: "#/components/examples/ErrInvalidRegion"
                bodyImageRequired:
                  $ref: "#/components/examples/ErrBodyImageRequired"
                designImageRequired:
                  $ref: "#/components/examples/ErrDesignImageRequired"
                invalidNumSamples:
                  $ref: "#/components/examples/ErrInvalidNumSamples"
                invalidOutputFormat:
                  $ref: "#/components/examples/ErrInvalidOutputFormat"
        "403":
          $ref: "#/components/responses/ForbiddenOrDisabled"
        "404":
          $ref: "#/components/responses/UserNotFound"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "429":
          $ref: "#/components/responses/TryonTooManyRequests"
        "500":
          $ref: "#/components/responses/TryonEnqueueFailed"

  /status/{id}:
    get:
      tags: [Jobs]
      summary: Get the status and result of a try-on job
      description: |
        Works for every photo try-on type. Poll until `status` is `completed` or `failed`; every ~2 seconds is a
        good default. Jobs can be polled for 3 days after they were created; after that, and for an id that isn't
        yours or isn't a valid id, the answer is `404`. Output URLs are kept for 72 hours, so download what you
        need to keep.

        A failed job is a `200` with `status: "failed"` and the reason in `error`, a plain string. Failed jobs are
        not charged.
      operationId: getStatus
      parameters:
        - name: id
          in: path
          required: true
          description: The `jobId` returned when the try-on was submitted.
          schema:
            type: string
          example: 64b7f1a9d9a3b8e5c7f9a123
      responses:
        "200":
          description: The job's current status.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/JobStatusResponse"
              examples:
                processing:
                  summary: Still generating
                  value:
                    ok: true
                    status: processing
                    output: []
                    error: null
                completed:
                  summary: Done
                  value:
                    ok: true
                    status: completed
                    output:
                      - https://cdn.tryiton.now/64b7f1a9d9a3b8e5c7f9a000/tryons/64b7f1a9d9a3b8e5c7f9a123-0.png
                      - https://cdn.tryiton.now/64b7f1a9d9a3b8e5c7f9a000/tryons/64b7f1a9d9a3b8e5c7f9a123-1.png
                    error: null
                failed:
                  summary: Failed (not charged)
                  value:
                    ok: true
                    status: failed
                    output: []
                    error: We couldn't find a person in the photo.
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: No such job on this account, or it is older than 3 days.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                tryonNotFound:
                  $ref: "#/components/examples/ErrTryonNotFound"
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

  /credits:
    get:
      tags: [Account]
      summary: Get your credit balance
      operationId: getCredits
      responses:
        "200":
          description: The account's current balance.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CreditsResponse"
              example:
                ok: true
                credits:
                  on_demand: 151
                  subscription: 50
                  purchased: 100
                  reserved: 1
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/UserNotFound"
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

  /live/config:
    get:
      tags: [Live (server)]
      summary: Live try-on availability and pricing
      operationId: getLiveConfig
      responses:
        "200":
          description: Current live try-on settings.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/LiveConfigResponse"
              example:
                ok: true
                enabled: true
                secondsPerCredit: 2
                maxSeconds: 180
                minCredits: 5
                maxConcurrentSessions: 3
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

  /live/garments:
    post:
      tags: [Live (server)]
      summary: Prepare a garment for live try-on
      description: |
        Turns a product image into what the live stream needs. This is the slow step (fetch, normalize, describe:
        seconds), so do it ahead of time, e.g. at catalog sync. Idempotent per image and category pick: a repeat call
        returns the stored garment with `200` instead of `201`. Free.
      operationId: prepareLiveGarment
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/LiveGarmentRequest"
            examples:
              top:
                summary: A top, category given
                value:
                  garment_image: https://example.com/products/shirt.jpg
                  category: clothing
                  subcategory: tops
              detect:
                summary: Detect the category
                value:
                  garment_image: https://example.com/products/sunglasses.jpg
      responses:
        "200":
          description: Already prepared from the same image and pick (cached).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/LiveGarmentResponse"
              example:
                ok: true
                garment:
                  id: 6b0827eba2f220ae7dd7c7fb
                  category: clothing
                  subcategory: tops
                  description: a navy short-sleeve pique polo shirt
                  createdAt: "2026-11-26T12:20:59.512Z"
        "201":
          description: Newly prepared.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/LiveGarmentResponse"
              example:
                ok: true
                garment:
                  id: 6b0827eba2f220ae7dd7c7fb
                  category: clothing
                  subcategory: tops
                  description: a navy short-sleeve pique polo shirt
                  createdAt: "2026-11-26T12:20:59.512Z"
        "400":
          description: Invalid or unreadable image, or an invalid category pick.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                garmentImageRequired:
                  $ref: "#/components/examples/ErrLiveGarmentImageRequired"
                garmentImageScheme:
                  $ref: "#/components/examples/ErrLiveGarmentImageScheme"
                garmentImageUnreadable:
                  $ref: "#/components/examples/ErrLiveGarmentImageUnreadable"
                invalidCategory:
                  $ref: "#/components/examples/ErrLiveInvalidCategory"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: The `garment_image` URL answered 404.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                remoteImageNotFound:
                  $ref: "#/components/examples/ErrRemoteImageNotFound"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "429":
          $ref: "#/components/responses/RateLimitedByAccount"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /live/sessions:
    post:
      tags: [Live (server)]
      summary: Start a live session
      description: |
        Starts a live session for one end user and holds its first credit. Call it from your server and send the
        whole response, unchanged, to the end user's device (e.g. to `connectLiveTryOn` from `tryiton-live`). Open
        the camera before calling: the session holds a credit from the moment it starts.

        With `end_user_id`, each end user gets one stream: starting again ends their previous session with
        `endReason: "superseded"`. Its held credit is charged if that session streamed (a settled tick or reported
        video) and returned if it never did.
      operationId: startLiveSession
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/LiveSessionStartRequest"
            examples:
              web:
                summary: Web storefront
                value:
                  garment_id: 6b0827eba2f220ae7dd7c7fb
                  end_user_id: shopper-42
                  allowed_origin: https://shop.example.com
              minimal:
                summary: No options (the device names a garment later)
                value: {}
      responses:
        "201":
          description: Session started. Hand this body to the device.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/LiveSessionStartResponse"
              example:
                ok: true
                session:
                  id: 6b0828e5ed117d43a6d10ad1
                  status: active
                  endReason: null
                  seconds: 0
                  creditsCharged: 0
                  endUserId: shopper-42
                  createdAt: "2026-11-26T12:21:57.402Z"
                  endedAt: null
                clientSecret: 3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3
                connection:
                  provider: decart
                  model: lucy-vton-latest
                  token: ek_live_8f2b9c4d1a7e
                secondsPerCredit: 2
                maxSeconds: 180
                secondsLeft: 116
                garment:
                  id: 6b0827eba2f220ae7dd7c7fb
                  category: clothing
                  subcategory: tops
                  description: a navy short-sleeve pique polo shirt
                  createdAt: "2026-11-26T12:20:59.512Z"
                  input:
                    prompt: Substitute the current top with a navy short-sleeve pique polo shirt.
                    enhancePrompt: true
                    referenceImage: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD
        "400":
          description: An invalid parameter.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                invalidGarmentId:
                  $ref: "#/components/examples/ErrInvalidGarmentId"
                invalidMaxSeconds:
                  $ref: "#/components/examples/ErrInvalidMaxSeconds"
                invalidEndUserId:
                  $ref: "#/components/examples/ErrInvalidEndUserId"
                invalidAllowedOrigin:
                  $ref: "#/components/examples/ErrInvalidAllowedOrigin"
        "403":
          $ref: "#/components/responses/ForbiddenOrDisabled"
        "404":
          description: Unknown `garment_id` on this account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                garmentNotFound:
                  $ref: "#/components/examples/ErrGarmentNotFound"
                userNotFound:
                  $ref: "#/components/examples/ErrUserNotFound"
        "409":
          description: Two starts for the same `end_user_id` raced. Retry once.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                sessionActive:
                  $ref: "#/components/examples/ErrLiveSessionActive"
        "429":
          description: Too many streams, not enough credits, too much in flight, or rate limited.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                liveBusy:
                  $ref: "#/components/examples/ErrLiveTryonBusy"
                belowMinCredits:
                  $ref: "#/components/examples/ErrLiveMinCredits"
                outOfCredits:
                  $ref: "#/components/examples/ErrLiveOutOfCredits"
                concurrency:
                  $ref: "#/components/examples/ErrConcurrencyLimitExceeded"
                rateLimited:
                  $ref: "#/components/examples/ErrRateLimitByAccount"
        "500":
          $ref: "#/components/responses/InternalServerError"
        "503":
          description: Live try-on is switched off, at capacity, or the media token could not be minted. Nothing was charged.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                disabled:
                  $ref: "#/components/examples/ErrLiveDisabled"
                atCapacity:
                  $ref: "#/components/examples/ErrLiveAtCapacity"
                unavailable:
                  $ref: "#/components/examples/ErrLiveUnavailable"

  /live/sessions/{id}:
    get:
      tags: [Live (server)]
      summary: Get a live session
      description: Status and usage of one of your sessions.
      operationId: getLiveSession
      parameters:
        - $ref: "#/components/parameters/SessionId"
      responses:
        "200":
          $ref: "#/components/responses/LiveSession"
        "400":
          $ref: "#/components/responses/InvalidSession"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/SessionNotFound"
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

  /live/sessions/{id}/stop:
    post:
      tags: [Live (server)]
      summary: Stop a live session from your server
      description: |
        Ends a session, e.g. when the end user leaves the page. Idempotent: stopping an ended session returns it
        unchanged. Ends with `endReason: "user"`. No request body is needed. The held credit is charged if the
        session streamed (a settled tick or reported video) and returned if it never did.
      operationId: stopLiveSession
      parameters:
        - $ref: "#/components/parameters/SessionId"
      responses:
        "200":
          $ref: "#/components/responses/LiveSession"
        "400":
          $ref: "#/components/responses/InvalidSession"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/SessionNotFound"
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

  /live/sessions/{id}/heartbeat:
    post:
      tags: [Live (device)]
      summary: Billing heartbeat
      description: |
        Send one every `secondsPerCredit` seconds once the first try-on frame arrives (`tryiton-live` sends the first
        one `secondsPerCredit` seconds after that frame). Each heartbeat charges the credit held for the tick that
        just ended and holds the next one. A heartbeat less than half a tick after the previous one, or a retried or
        concurrent one, is never charged twice: it answers `stop: false` with the current `secondsLeft`. When the
        response has `stop: true`, stop streaming at once.

        **Auth:** the session's `clientSecret`, as `secret` in the JSON body (or the `secret` query parameter). No
        API key. A wrong secret is a `404`, so the endpoint never reveals whether a session exists.
      operationId: liveHeartbeat
      security: []
      parameters:
        - $ref: "#/components/parameters/SessionId"
        - $ref: "#/components/parameters/SecretQuery"
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/LiveHeartbeatRequest"
            example:
              secret: 3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3
              connect_ms: 2834
      responses:
        "200":
          description: "Keep streaming (`stop: false`) or stop now (`stop: true`)."
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/LiveHeartbeatResponse"
              examples:
                keepStreaming:
                  summary: Next tick held
                  value:
                    ok: true
                    stop: false
                    secondsLeft: 18
                stop:
                  summary: The stream must end
                  value:
                    ok: true
                    stop: true
                    reason: out_of_credits
                    session:
                      id: 6b0828e5ed117d43a6d10ad1
                      status: ended
                      endReason: out_of_credits
                      seconds: 24
                      creditsCharged: 12
                      endUserId: shopper-42
                      createdAt: "2026-11-26T12:21:57.402Z"
                      endedAt: "2026-11-26T12:22:24.880Z"
        "400":
          $ref: "#/components/responses/InvalidSession"
        "404":
          $ref: "#/components/responses/SessionNotFound"
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

  /live/sessions/{id}/garments/{garmentId}:
    post:
      tags: [Live (device)]
      summary: Switch garment mid-stream
      description: |
        Returns a prepared garment's stream input for a mid-stream switch and records the switch on the session.
        The garment must be prepared on the same account. Free.

        **Auth:** the session's `clientSecret`, as `secret` in the JSON body (or the `secret` query parameter). No
        API key.
      operationId: liveSwitchGarment
      security: []
      parameters:
        - $ref: "#/components/parameters/SessionId"
        - name: garmentId
          in: path
          required: true
          description: A garment `id` from `POST /live/garments`.
          schema:
            $ref: "#/components/schemas/ObjectId"
          example: 6b0827eba2f220ae7dd7c7fb
        - $ref: "#/components/parameters/SecretQuery"
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/LiveClientSecretBody"
            example:
              secret: 3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3
      responses:
        "200":
          description: The garment with its stream input.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/LiveGarmentSwitchResponse"
              example:
                ok: true
                garment:
                  id: 6b0827eba2f220ae7dd7c7fb
                  category: clothing
                  subcategory: tops
                  description: a navy short-sleeve pique polo shirt
                  createdAt: "2026-11-26T12:20:59.512Z"
                  input:
                    prompt: Substitute the current top with a navy short-sleeve pique polo shirt.
                    enhancePrompt: true
                    referenceImage: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD
        "400":
          description: The session or garment id is malformed.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                invalidSession:
                  $ref: "#/components/examples/ErrInvalidSession"
                invalidGarment:
                  $ref: "#/components/examples/ErrInvalidGarment"
        "404":
          description: Unknown session, wrong secret, or a garment not prepared on this account.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              examples:
                sessionNotFound:
                  $ref: "#/components/examples/ErrSessionNotFound"
                garmentNotFound:
                  $ref: "#/components/examples/ErrGarmentNotFound"
        "409":
          description: The session has already ended, so there's no stream to switch.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                ok: false
                error:
                  name: LiveSessionEnded
                  message: This live session has ended.
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

  /live/sessions/{id}/end:
    post:
      tags: [Live (device)]
      summary: End a live session from the device
      description: |
        Idempotent. The held tick is charged unless the stream provably never produced video (`connected: false`
        within a minute of the start, before any tick), in which case it is returned.

        **Auth:** the session's `clientSecret`, as `secret` in the JSON body or the `secret` query parameter. No API
        key. When the page is closing, send a `text/plain` keepalive request with the secret in the URL
        (`.../end?secret=...`) so no CORS preflight is needed. A `text/plain` body is parsed as JSON, so `reason`,
        `connected` and `connect_ms` count exactly as in a JSON request. A body that isn't a JSON object (empty,
        malformed, an array) is treated as `{}`: the session ends with `reason: "unload"` and the held tick is
        charged.
      operationId: liveEndSession
      security: []
      parameters:
        - $ref: "#/components/parameters/SessionId"
        - $ref: "#/components/parameters/SecretQuery"
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/LiveEndRequest"
            examples:
              userEnded:
                summary: The end user closed the try-on
                value:
                  secret: 3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3
                  reason: user
                  connected: true
                  connect_ms: 2834
              neverConnected:
                summary: The stream failed before any video
                value:
                  secret: 3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3
                  reason: error
                  connected: false
                  error: no video track within 15s
          text/plain:
            schema:
              type: string
              description: |
                The same fields as the JSON body, serialized as a JSON string (a CORS-simple request for a page-unload
                keepalive). Parsed as JSON; anything that isn't a JSON object counts as an empty body. Send the
                secret in the `secret` query parameter. Limited to 10 KB.
            example: '{"reason":"unload","connected":true,"connect_ms":2834}'
      responses:
        "200":
          $ref: "#/components/responses/LiveSession"
        "400":
          $ref: "#/components/responses/InvalidSession"
        "404":
          $ref: "#/components/responses/SessionNotFound"
        "429":
          $ref: "#/components/responses/RateLimitedByIp"

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        Your API key from https://tryiton.now/app/developer, sent as `Authorization: Bearer YOUR_API_KEY`. Keep it on
        your server. A missing, malformed or unknown key is rejected with 403 `Forbidden`.

  parameters:
    SessionId:
      name: id
      in: path
      required: true
      description: A live session `id` from `POST /live/sessions`. Anything other than 24 hex characters is a `400`.
      schema:
        $ref: "#/components/schemas/ObjectId"
      example: 6b0828e5ed117d43a6d10ad1
    SecretQuery:
      name: secret
      in: query
      required: false
      description: |
        The session's `clientSecret`, when it isn't sent as `secret` in the JSON body. One of the two is required;
        the body wins when both are present. Meant for the page-unload `end` keepalive, which is sent as
        `text/plain` (a JSON content type would need a CORS preflight that a closing page can't wait for).
      schema:
        type: string
      example: 3f9c2a7b1e4d6f80a2c5e7b9d1f3a5c7e9b2d4f6a8c0e1b3

  schemas:
    ObjectId:
      type: string
      description: A 24-character hexadecimal id.
      pattern: "^[a-fA-F0-9]{24}$"
      examples:
        - 6b0827eba2f220ae7dd7c7fb

    ImageInput:
      type: string
      minLength: 1
      description: A public `http(s)` URL, or a base64 data URI such as `data:image/png;base64,...`.
      examples:
        - https://example.com/model.jpg

    TryonCategory:
      type: string
      description: |
        What the item is. `auto` detects it from the image. `clothing`, `jewelry` and `accessories` need a
        `subcategory`; `auto`, `eyewear`, `footwear`, `headwear` and `others` must not have one.
      enum: [auto, clothing, eyewear, footwear, headwear, jewelry, accessories, others]

    TryonSubcategory:
      type: string
      description: |
        Where the item goes. Valid values depend on `category`:
        `clothing`: `auto`, `tops`, `bottoms`, `dresses`.
        `jewelry`: `rings`, `earrings`, `necklaces`, `bracelets`, `anklets`.
        `accessories`: `watches`, `belts`, `scarves`, `bags`, `gloves`, `ties`.
      enum: [auto, tops, bottoms, dresses, rings, earrings, necklaces, bracelets, anklets, watches, belts, scarves, bags, gloves, ties]

    CategorySubcategoryRules:
      description: The valid `category` / `subcategory` pairs (constants/tryon.js TRYON_GARMENT_TAXONOMY).
      allOf:
        - if:
            required: [category]
            properties:
              category:
                const: clothing
          then:
            required: [subcategory]
            properties:
              subcategory:
                enum: [auto, tops, bottoms, dresses]
        - if:
            required: [category]
            properties:
              category:
                const: jewelry
          then:
            required: [subcategory]
            properties:
              subcategory:
                enum: [rings, earrings, necklaces, bracelets, anklets]
        - if:
            required: [category]
            properties:
              category:
                const: accessories
          then:
            required: [subcategory]
            properties:
              subcategory:
                enum: [watches, belts, scarves, bags, gloves, ties]
        - if:
            required: [category]
            properties:
              category:
                enum: [auto, eyewear, footwear, headwear, others]
          then:
            properties:
              subcategory:
                type: "null"

    NumSamples:
      type: integer
      minimum: 1
      maximum: 4
      default: 1
      description: Number of output images. Each costs 1 credit.

    OutputFormat:
      type: string
      enum: [png, jpeg]
      default: png
      description: Format of the output images.

    ModerationLevel:
      type: string
      enum: [conservative, permissive, none]
      default: permissive
      deprecated: true
      description: |
        Deprecated. Accepted for compatibility: the value is validated (anything outside the enum is a 400
        `InvalidModerationLevel`) but has no effect on the result. The model providers' own safety filters always
        apply. Omit it; it will be removed in a future API version.

    Haircut:
      type: string
      description: A supported haircut (constants/tryon.js `haircuts`).
      enum:
        - Afro
        - BobCut
        - BowlCut
        - BoxBraids
        - BuzzCut
        - Chignon
        - CombOver
        - CornrowBraids
        - CurlyBob
        - CurlyShag
        - DoubleBun
        - Dreadlocks
        - FauxHawk
        - FishtailBraid
        - LongCurly
        - LongHairTiedUp
        - LongHimeCut
        - LongStraight
        - LongTwintails
        - LongWavy
        - LongWavyCurtainBangs
        - ManBun
        - MessyTousled
        - PixieCut
        - Pompadour
        - Ponytail
        - ShortCurlyPixie
        - ShortTwintails
        - ShoulderLengthHair
        - Spiky
        - TexturedFringe
        - TwinBraids
        - Updo
        - WavyShag

    FashionTryonRequest:
      type: object
      required: [model_image, garment_image]
      properties:
        model_image:
          $ref: "#/components/schemas/ImageInput"
          description: The person.
        garment_image:
          $ref: "#/components/schemas/ImageInput"
          description: The garment or accessory.
        category:
          $ref: "#/components/schemas/TryonCategory"
          default: auto
        subcategory:
          description: Required for `clothing`, `jewelry` and `accessories`; omit (or `null`) otherwise.
          anyOf:
            - $ref: "#/components/schemas/TryonSubcategory"
            - type: "null"
        mode:
          type: string
          default: balanced
          deprecated: true
          description: |
            Deprecated. Accepted for backward compatibility and ignored: it isn't validated and has no effect on the
            result. Omit it; it will be removed in a future API version.
          examples:
            - balanced
        num_samples:
          $ref: "#/components/schemas/NumSamples"
        output_format:
          $ref: "#/components/schemas/OutputFormat"
        moderation_level:
          $ref: "#/components/schemas/ModerationLevel"
      allOf:
        - $ref: "#/components/schemas/CategorySubcategoryRules"
        # No category means global auto, which takes no subcategory.
        - anyOf:
            - required: [category]
              properties:
                category:
                  $ref: "#/components/schemas/TryonCategory"
            - properties:
                subcategory:
                  type: "null"

    HairstyleTryonRequest:
      type: object
      required: [face_image, haircut]
      properties:
        face_image:
          $ref: "#/components/schemas/ImageInput"
          description: The person's face. A portrait works best.
        haircut:
          $ref: "#/components/schemas/Haircut"
        hair_color:
          type: string
          description: |
            Optional free-text color, e.g. `ash blonde with subtle highlights`. Trimmed and cut to 120 characters.
            Omit (or send an empty string) to keep the current color.
          maxLength: 120
          examples:
            - copper red, subtle balayage
        num_samples:
          $ref: "#/components/schemas/NumSamples"
        output_format:
          $ref: "#/components/schemas/OutputFormat"

    TattooRegion:
      type: object
      description: |
        Exact spot for the ink: a rectangle on `body_image`, normalized 0-1 from the top-left corner. Each side must be
        at least 0.06 (before and after clamping into the frame), or the request is a 400 `InvalidRegion`. A
        JSON-encoded string of this object is also accepted.
      required: [x, y, w, h]
      properties:
        x:
          type: number
          description: Left edge. Clamped to 0-1.
        y:
          type: number
          description: Top edge. Clamped to 0-1.
        w:
          type: number
          minimum: 0.06
          description: Width. Clamped to `1 - x`.
        h:
          type: number
          minimum: 0.06
          description: Height. Clamped to `1 - y`.
      examples:
        - x: 0.32
          y: 0.18
          w: 0.28
          h: 0.34

    TattooTryonRequest:
      type: object
      required: [body_image, design_image]
      properties:
        body_image:
          $ref: "#/components/schemas/ImageInput"
          description: A close-up of bare skin (arm, leg, shoulder, back).
        design_image:
          $ref: "#/components/schemas/ImageInput"
          description: The tattoo design on its own, ideally on a plain background.
        placement:
          type: string
          description: |
            Free-text placement and size, e.g. `on the right forearm, small`. Line breaks are flattened and the text
            is cut to 140 characters (never rejected). Omitted: placed naturally on the most visible skin, about
            palm-sized. With a `region`, it only describes size and style.
          maxLength: 140
        region:
          description: Optional exact rectangle. `null` is the same as leaving it out.
          anyOf:
            - $ref: "#/components/schemas/TattooRegion"
            - type: "null"
        num_samples:
          $ref: "#/components/schemas/NumSamples"
        output_format:
          $ref: "#/components/schemas/OutputFormat"

    JobAcceptedResponse:
      type: object
      required: [ok, jobId]
      properties:
        ok:
          type: boolean
          const: true
        jobId:
          $ref: "#/components/schemas/ObjectId"
          description: Poll `GET /status/{id}` with this.

    JobStatus:
      type: string
      enum: [processing, completed, failed]

    JobStatusResponse:
      type: object
      required: [ok, status, output, error]
      properties:
        ok:
          type: boolean
          const: true
        status:
          $ref: "#/components/schemas/JobStatus"
        output:
          type: array
          description: CDN URLs of the result images once `completed`, otherwise empty. Kept for 72 hours.
          items:
            type: string
            format: uri
        error:
          type: [string, "null"]
          description: Why the job failed, as a plain string, when `status` is `failed`. Otherwise `null`.

    Credits:
      type: object
      required: [on_demand, subscription, purchased, reserved]
      properties:
        on_demand:
          type: integer
          description: |
            `subscription + purchased + reserved` as the backend computes it today (`User.baselineCredits`). What you
            can spend now is `subscription + purchased - reserved`.
        subscription:
          type: integer
          description: Credits from the current API subscription. Reset each billing cycle.
        purchased:
          type: integer
          description: Credits bought separately. They don't expire.
        reserved:
          type: integer
          description: Credits held by in-flight try-ons and live sessions.

    CreditsResponse:
      type: object
      required: [ok, credits]
      properties:
        ok:
          type: boolean
          const: true
        credits:
          $ref: "#/components/schemas/Credits"

    HealthResponse:
      type: object
      required: [ok]
      properties:
        ok:
          type: boolean
          const: true

    LiveConfigResponse:
      type: object
      required: [ok, enabled, secondsPerCredit, maxSeconds, minCredits, maxConcurrentSessions]
      properties:
        ok:
          type: boolean
          const: true
        enabled:
          type: boolean
          description: Whether live try-on is available right now. When `false`, starts fail with 503.
        secondsPerCredit:
          type: integer
          minimum: 1
          maximum: 60
          description: Seconds of video one credit buys (one tick). 2 by default.
        maxSeconds:
          type: integer
          minimum: 30
          maximum: 1800
          description: Longest session allowed, and the upper bound of `max_seconds`. 180 by default.
        minCredits:
          type: integer
          minimum: 1
          description: Credits needed to start a session (10 seconds' worth, at least 1).
        maxConcurrentSessions:
          type: integer
          description: Sessions one account can stream at the same time.

    LiveGarmentRequest:
      type: object
      required: [garment_image]
      properties:
        garment_image:
          type: string
          minLength: 1
          description: |
            A public `http(s)` URL or a `data:image/...;base64,` URI of the garment. A product photo on a plain
            background works best.
          examples:
            - https://example.com/products/shirt.jpg
        category:
          description: |
            Recommended. What the item is, or `auto` / omitted to detect it. Detection can misread photos that show
            more than the item.
          anyOf:
            - $ref: "#/components/schemas/TryonCategory"
            - type: "null"
        subcategory:
          description: Must be valid for `category` (see `TryonSubcategory`). Ignored when `category` is omitted.
          anyOf:
            - $ref: "#/components/schemas/TryonSubcategory"
            - type: "null"
      allOf:
        - $ref: "#/components/schemas/CategorySubcategoryRules"

    LiveGarment:
      type: object
      description: A garment prepared for live try-on.
      required: [id, category, subcategory, description, createdAt]
      properties:
        id:
          $ref: "#/components/schemas/ObjectId"
        category:
          $ref: "#/components/schemas/TryonCategory"
          description: The pick you sent, else what detection saw, else `auto`.
        subcategory:
          anyOf:
            - $ref: "#/components/schemas/TryonSubcategory"
            - type: "null"
        description:
          type: [string, "null"]
          description: A short description of the item from detection.
        createdAt:
          type: string
          format: date-time

    LiveGarmentInput:
      type: object
      description: What the device hands the media provider for this garment.
      required: [prompt, enhancePrompt, referenceImage]
      properties:
        prompt:
          type: string
        enhancePrompt:
          type: boolean
        referenceImage:
          type: string
          description: The normalized garment image as a JPEG data URI.

    LiveGarmentWithInput:
      allOf:
        - $ref: "#/components/schemas/LiveGarment"
        - type: object
          required: [input]
          properties:
            input:
              $ref: "#/components/schemas/LiveGarmentInput"

    LiveGarmentResponse:
      type: object
      required: [ok, garment]
      properties:
        ok:
          type: boolean
          const: true
        garment:
          $ref: "#/components/schemas/LiveGarment"

    LiveGarmentSwitchResponse:
      type: object
      required: [ok, garment]
      properties:
        ok:
          type: boolean
          const: true
        garment:
          $ref: "#/components/schemas/LiveGarmentWithInput"

    LiveSessionStartRequest:
      type: object
      properties:
        garment_id:
          description: |
            A prepared garment to start with. Its stream input comes back in the response, so the first frame doesn't
            wait on another call. Without it, the device names a garment when it connects.
          anyOf:
            - $ref: "#/components/schemas/ObjectId"
            - type: "null"
        max_seconds:
          type: [integer, "null"]
          minimum: 10
          maximum: 180
          description: Cap for this session, from 10 to `maxSeconds` in `GET /live/config` (180 by default). Defaults to `maxSeconds`.
        end_user_id:
          type: [string, "null"]
          pattern: "^[\\w.@:-]{1,100}$"
          description: |
            Your id for the end user: 1-100 letters, digits and `_ . - @ :`. One stream per end user: starting again
            ends their previous session.
          examples:
            - shopper-42
        allowed_origin:
          type: [string, "null"]
          pattern: "^https?://[^/\\s]+$"
          description: |
            The browser origin the media token is locked to, e.g. `https://shop.example.com` (scheme matched
            case-insensitively, no path). Recommended for web integrations; leave it out for native apps.
          examples:
            - https://shop.example.com

    LiveSessionStatus:
      type: string
      enum: [active, ended]

    LiveEndReason:
      type: string
      description: |
        `user`: ended by the end user or by your server (stop). `idle`, `hidden`, `unload`, `error`: reported by the
        device. `out_of_credits`: the next tick couldn't be paid. `time_limit`: reached `max_seconds`. `stale`: the
        device stopped sending heartbeats. `superseded`: the same `end_user_id` started a new session. `budget`: the
        service was at capacity (free credits only).
      enum: [user, idle, hidden, error, unload, out_of_credits, time_limit, stale, superseded, budget]

    LiveClientEndReason:
      type: string
      description: The reasons a device may report. Anything else is recorded as `unload`.
      enum: [user, idle, hidden, error, unload]

    LiveSession:
      type: object
      required: [id, status, endReason, seconds, creditsCharged, endUserId, createdAt, endedAt]
      properties:
        id:
          $ref: "#/components/schemas/ObjectId"
        status:
          $ref: "#/components/schemas/LiveSessionStatus"
        endReason:
          anyOf:
            - $ref: "#/components/schemas/LiveEndReason"
            - type: "null"
        seconds:
          type: integer
          minimum: 0
          description: Streamed seconds once ended; while running, billed seconds (whole ticks).
        creditsCharged:
          type: integer
          minimum: 0
        endUserId:
          type: [string, "null"]
          description: The `end_user_id` the session was started with.
        createdAt:
          type: string
          format: date-time
        endedAt:
          type: [string, "null"]
          format: date-time

    LiveSessionResponse:
      type: object
      required: [ok, session]
      properties:
        ok:
          type: boolean
          const: true
        session:
          $ref: "#/components/schemas/LiveSession"

    LiveConnection:
      type: object
      description: How the device reaches the media provider. `tryiton-live` uses it.
      required: [provider, model, token]
      properties:
        provider:
          type: string
          const: decart
        model:
          type: string
          examples:
            - lucy-vton-latest
        token:
          type: string
          description: Short-lived media token, capped to this session's length and locked to `allowed_origin` when given.

    LiveSessionStartResponse:
      type: object
      required: [ok, session, clientSecret, connection, secondsPerCredit, maxSeconds, secondsLeft, garment]
      properties:
        ok:
          type: boolean
          const: true
        session:
          $ref: "#/components/schemas/LiveSession"
        clientSecret:
          type: string
          pattern: "^[a-f0-9]{48}$"
          description: Session-scoped secret for the device's calls. Never log or store it.
        connection:
          $ref: "#/components/schemas/LiveConnection"
        secondsPerCredit:
          type: integer
          description: Tick length for this session, fixed at start.
        maxSeconds:
          type: integer
          description: This session's cap.
        secondsLeft:
          type: integer
          minimum: 0
          description: Seconds this session can stream now, the lower of the credit balance and the session cap.
        garment:
          description: The first garment with its stream input when `garment_id` was given, else `null`.
          anyOf:
            - $ref: "#/components/schemas/LiveGarmentWithInput"
            - type: "null"

    LiveClientSecretBody:
      type: object
      properties:
        secret:
          type: string
          description: The session's `clientSecret`. Required unless sent as the `secret` query parameter.

    LiveHeartbeatRequest:
      allOf:
        - $ref: "#/components/schemas/LiveClientSecretBody"
        - type: object
          properties:
            connect_ms:
              type: number
              minimum: 0
              description: Milliseconds from start to the first frame, for analytics. Rounded and capped at 120000; invalid values are ignored.

    LiveHeartbeatContinue:
      type: object
      required: [ok, stop, secondsLeft]
      properties:
        ok:
          type: boolean
          const: true
        stop:
          type: boolean
          const: false
        secondsLeft:
          type: integer
          minimum: 0

    LiveHeartbeatStop:
      type: object
      required: [ok, stop, reason, session]
      properties:
        ok:
          type: boolean
          const: true
        stop:
          type: boolean
          const: true
        reason:
          $ref: "#/components/schemas/LiveEndReason"
        session:
          $ref: "#/components/schemas/LiveSession"

    LiveHeartbeatResponse:
      oneOf:
        - $ref: "#/components/schemas/LiveHeartbeatContinue"
        - $ref: "#/components/schemas/LiveHeartbeatStop"

    LiveEndRequest:
      allOf:
        - $ref: "#/components/schemas/LiveClientSecretBody"
        - type: object
          properties:
            reason:
              $ref: "#/components/schemas/LiveClientEndReason"
              default: unload
            connected:
              type: boolean
              description: Whether video ever arrived. `false` (before any tick, within a minute of the start) returns the held credit.
            connect_ms:
              type: number
              minimum: 0
              description: Milliseconds from start to the first frame. Rounded and capped at 120000.
            error:
              type: string
              maxLength: 300
              description: What went wrong. Kept only when `reason` is `error`; cut to 300 characters.

    ErrorResponse:
      type: object
      description: The error envelope every endpoint uses.
      required: [ok, error]
      properties:
        ok:
          type: boolean
          const: false
        error:
          type: object
          required: [name, message]
          additionalProperties: true
          properties:
            name:
              type: string
              description: |
                Machine-readable error name. Branch on this. Values in use: `BadRequest`, `ImageLoadError`,
                `InvalidCategory`, `InvalidNumSamples`, `InvalidOutputFormat`, `InvalidModerationLevel`,
                `InvalidRegion`, `Forbidden`, `NotFound`, `PayloadTooLarge`, `LiveSessionActive`, `OutOfCredits`,
                `ConcurrencyLimitExceeded`, `RateLimitExceeded`, `LiveTryonBusy`, `InternalServerError`,
                `LiveTryonUnavailable`. New names may be added.
            message:
              type: string
              description: Human-readable. May change; don't parse it.

  responses:
    JobAccepted:
      description: Job accepted. Poll `GET /status/{id}` with `jobId`.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/JobAcceptedResponse"
          example:
            ok: true
            jobId: 64b7f1a9d9a3b8e5c7f9a123

    LiveSession:
      description: The session.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/LiveSessionResponse"
          example:
            ok: true
            session:
              id: 6b0828e5ed117d43a6d10ad1
              status: ended
              endReason: user
              seconds: 9
              creditsCharged: 5
              endUserId: shopper-42
              createdAt: "2026-11-26T12:21:57.402Z"
              endedAt: "2026-11-26T12:22:12.118Z"

    Forbidden:
      description: Missing, malformed or unknown API key.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            missingKey:
              $ref: "#/components/examples/ErrMissingAuthHeader"
            invalidKey:
              $ref: "#/components/examples/ErrInvalidApiKey"

    ForbiddenOrDisabled:
      description: Missing, malformed or unknown API key, or a disabled account.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            missingKey:
              $ref: "#/components/examples/ErrMissingAuthHeader"
            invalidKey:
              $ref: "#/components/examples/ErrInvalidApiKey"
            accountDisabled:
              $ref: "#/components/examples/ErrAccountDisabled"

    UserNotFound:
      description: The API key's account no longer exists.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            userNotFound:
              $ref: "#/components/examples/ErrUserNotFound"

    PayloadTooLarge:
      description: The JSON body is over 12 MB. Send large images as a URL.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            payloadTooLarge:
              $ref: "#/components/examples/ErrPayloadTooLarge"

    TryonTooManyRequests:
      description: Not enough credits for `num_samples`, too much in flight, or rate limited.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            outOfCredits:
              $ref: "#/components/examples/ErrOutOfCredits"
            concurrency:
              $ref: "#/components/examples/ErrConcurrencyLimitExceeded"
            rateLimited:
              $ref: "#/components/examples/ErrRateLimitByAccount"

    RateLimitedByAccount:
      description: Too many requests from this account (or IP).
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            rateLimited:
              $ref: "#/components/examples/ErrRateLimitByAccount"

    RateLimitedByIp:
      description: Too many requests from this IP.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            rateLimited:
              $ref: "#/components/examples/ErrRateLimitByIp"

    TryonEnqueueFailed:
      description: The job could not be queued. Nothing was charged; retry.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            enqueueFailed:
              $ref: "#/components/examples/ErrEnqueueFailed"
            internal:
              $ref: "#/components/examples/ErrInternal"

    InternalServerError:
      description: Unexpected server error. Retry after a delay.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            internal:
              $ref: "#/components/examples/ErrInternal"

    InvalidSession:
      description: The session id is not 24 hex characters.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            invalidSession:
              $ref: "#/components/examples/ErrInvalidSession"

    SessionNotFound:
      description: No such session on this account (or, on device endpoints, a wrong secret).
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
          examples:
            sessionNotFound:
              $ref: "#/components/examples/ErrSessionNotFound"

  examples:
    ErrModelImageMissing:
      summary: model_image missing
      value: { ok: false, error: { name: ImageLoadError, message: Model image is missing. } }
    ErrGarmentImageMissing:
      summary: garment_image missing
      value: { ok: false, error: { name: ImageLoadError, message: Garment image is missing. } }
    ErrInvalidCategory:
      summary: Invalid category/subcategory pair
      value: { ok: false, error: { name: InvalidCategory, message: Invalid category. } }
    ErrInvalidNumSamples:
      summary: num_samples out of range
      value: { ok: false, error: { name: InvalidNumSamples, message: num_samples must be an integer between 1 and 4. } }
    ErrInvalidOutputFormat:
      summary: Unknown output_format
      value: { ok: false, error: { name: InvalidOutputFormat, message: "output_format must be one of: png, jpeg." } }
    ErrInvalidModerationLevel:
      summary: Unknown moderation_level
      value:
        ok: false
        error: { name: InvalidModerationLevel, message: "moderation_level must be one of: conservative, permissive, none." }
    ErrFaceImageRequired:
      summary: face_image missing
      value: { ok: false, error: { name: BadRequest, message: Face image is required. } }
    ErrHaircutRequired:
      summary: haircut missing
      value: { ok: false, error: { name: BadRequest, message: Haircut is required. } }
    ErrInvalidHaircut:
      summary: Unknown haircut
      value: { ok: false, error: { name: BadRequest, message: Invalid haircut. } }
    ErrBodyImageRequired:
      summary: body_image missing
      value: { ok: false, error: { name: ImageLoadError, message: Body image is required. } }
    ErrDesignImageRequired:
      summary: design_image missing
      value: { ok: false, error: { name: ImageLoadError, message: Design image is required. } }
    ErrInvalidRegion:
      summary: Malformed region
      value:
        ok: false
        error:
          name: InvalidRegion
          message: region must be an object { x, y, w, h } with values normalized 0-1 (top-left origin), each side at least 0.06.
    ErrTryonNotFound:
      summary: Unknown or expired job
      value: { ok: false, error: { name: NotFound, message: Tryon not found. } }
    ErrMissingAuthHeader:
      summary: No Bearer token
      value: { ok: false, error: { name: Forbidden, message: Missing or invalid Authorization header. } }
    ErrInvalidApiKey:
      summary: Unknown API key
      value: { ok: false, error: { name: Forbidden, message: API key is invalid. } }
    ErrAccountDisabled:
      summary: Disabled account
      value: { ok: false, error: { name: Forbidden, message: Your account has been disabled. Please contact support. } }
    ErrUserNotFound:
      summary: The key's account is gone
      value: { ok: false, error: { name: NotFound, message: User not found. } }
    ErrPayloadTooLarge:
      summary: Body over 12 MB
      value:
        ok: false
        error:
          name: PayloadTooLarge
          message: Request body is too large (limit 12288kb). Send large images as a URL instead of inline base64.
    ErrOutOfCredits:
      summary: Not enough credits for num_samples
      value: { ok: false, error: { name: OutOfCredits, message: You do not have enough credits left. } }
    ErrConcurrencyLimitExceeded:
      summary: Too much in flight
      value:
        ok: false
        error:
          name: ConcurrencyLimitExceeded
          message: Too many concurrent requests. Please wait for the current requests to complete.
    ErrRateLimitByAccount:
      summary: Per-account rate limit
      value: { ok: false, error: { name: RateLimitExceeded, message: You have sent too many requests. Please try again later. } }
    ErrRateLimitByIp:
      summary: Per-IP rate limit
      value: { ok: false, error: { name: RateLimitExceeded, message: You have sent too many requests. Please try again later } }
    ErrEnqueueFailed:
      summary: Could not queue the job
      value: { ok: false, error: { name: InternalServerError, message: Failed to start try-on processing. Please try again. } }
    ErrInternal:
      summary: Unexpected error
      value: { ok: false, error: { name: InternalServerError, message: Something went wrong! Please try again or report this error. } }
    ErrLiveGarmentImageRequired:
      summary: garment_image missing
      value:
        ok: false
        error: { name: ImageLoadError, message: garment_image is required (an image URL or a base64 data URI). }
    ErrLiveGarmentImageScheme:
      summary: garment_image is neither http(s) nor a data URI
      value:
        ok: false
        error: { name: ImageLoadError, message: garment_image must be an http(s) URL or a base64 data URI. }
    ErrLiveGarmentImageUnreadable:
      summary: The image could not be decoded
      value: { ok: false, error: { name: ImageLoadError, message: We couldn't read that garment image. } }
    ErrRemoteImageNotFound:
      summary: The image URL answered 404
      value: { ok: false, error: { name: ImageLoadError, message: The image could not be found at the specified URL (404). } }
    ErrLiveInvalidCategory:
      summary: Invalid category/subcategory pair
      value: { ok: false, error: { name: InvalidCategory, message: Invalid category/subcategory. } }
    ErrInvalidGarmentId:
      summary: Malformed garment_id
      value: { ok: false, error: { name: BadRequest, message: Invalid garment_id. } }
    ErrInvalidMaxSeconds:
      summary: max_seconds out of range
      value: { ok: false, error: { name: BadRequest, message: max_seconds must be an integer from 10 to 180. } }
    ErrInvalidEndUserId:
      summary: Malformed end_user_id
      value: { ok: false, error: { name: BadRequest, message: "end_user_id must be 1-100 characters of letters, digits and . _ - @ :" } }
    ErrInvalidAllowedOrigin:
      summary: Malformed allowed_origin
      value: { ok: false, error: { name: BadRequest, message: "allowed_origin must be a browser origin like https://shop.example.com" } }
    ErrGarmentNotFound:
      summary: Unknown garment
      value: { ok: false, error: { name: NotFound, message: Garment not found. } }
    ErrLiveSessionActive:
      summary: Racing starts for one end user
      value: { ok: false, error: { name: LiveSessionActive, message: A live session is already running for this end user. } }
    ErrLiveTryonBusy:
      summary: Too many streams on the account
      value: { ok: false, error: { name: LiveTryonBusy, message: At most 3 live sessions can run at once on this account. } }
    ErrLiveMinCredits:
      summary: Below minCredits
      value: { ok: false, error: { name: OutOfCredits, message: Live try-on needs at least 5 credits. Please buy more. } }
    ErrLiveOutOfCredits:
      summary: The first tick could not be held
      value: { ok: false, error: { name: OutOfCredits, message: You do not have enough credits left. Please buy more. } }
    ErrLiveDisabled:
      summary: Live try-on switched off
      value: { ok: false, error: { name: LiveTryonUnavailable, message: Live try-on is not available right now. } }
    ErrLiveAtCapacity:
      summary: At capacity (free credits only)
      value: { ok: false, error: { name: LiveTryonUnavailable, message: Live try-on is very busy right now. Please try again later. } }
    ErrLiveUnavailable:
      summary: Token mint or garment load failed
      value:
        ok: false
        error: { name: LiveTryonUnavailable, message: Live try-on is temporarily unavailable. Please try again in a moment. }
    ErrInvalidSession:
      summary: Malformed session id
      value: { ok: false, error: { name: BadRequest, message: Invalid session. } }
    ErrInvalidGarment:
      summary: Malformed garment id
      value: { ok: false, error: { name: BadRequest, message: Invalid garment. } }
    ErrSessionNotFound:
      summary: Unknown session or wrong secret
      value: { ok: false, error: { name: NotFound, message: Session not found. } }
