openapi: 3.1.0
info:
  title: HPP Router Consumer API
  version: 0.1.0
  description: Consumer-facing API contract for HPP Router TypeScript SDK.
servers:
  - url: https://router.hpp.io
    description: HPP Router production gateway.
security:
  - ApiKeyAuth: []
  - BearerAuth: []
paths:
  /llm/v1/chat/completions:
    post:
      operationId: createChatCompletion
      summary: Create a chat completion
      description: >
        OpenAI-compatible chat completion. Callers always use this path.
        OpenAI text models (`openai/*` except `gpt-image-*`) are translated
        inside the gateway to OpenAI `/v1/responses` and mapped back to a chat
        completion. Forwarded fields on that path: `messages`, `stream`,
        `max_tokens` / `max_completion_tokens` (as `max_output_tokens`),
        `temperature`, `top_p`, `tools`, and `tool_choice`.
        `gpt-image-*`, Anthropic, Moonshot, and Ollama keep the chat body.
        Wallet rail (`X-Payment-Rail: wallet`) and the keyless Agent path return
        402 until the client retries with `PAYMENT-SIGNATURE` or `X-PAYMENT`.
      parameters:
        - name: X-Payment-Rail
          in: header
          description: >
            Payment rail for keyed callers. `quota` (default) uses API key credit.
            `wallet` triggers x402 on-chain payment for paid models.
            Keyless Agent calls omit the API key and are treated as wallet.
          required: false
          schema:
            type: string
            enum:
              - quota
              - wallet
        - name: PAYMENT-SIGNATURE
          in: header
          description: >
            Base64-encoded payment payload for x402 v2 (`upto` scheme). Send on
            retry after 402. Mutually exclusive with `X-PAYMENT`.
          required: false
          schema:
            type: string
        - name: X-PAYMENT
          in: header
          description: >
            Base64-encoded payment payload for x402 v1. Accepted on retry after 402.
            Prefer `PAYMENT-SIGNATURE`.
          required: false
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ChatCompletionRequest"
      responses:
        "200":
          description: Chat completion response.
          headers:
            X-HPP-Router-Resolved-Model:
              description: Resolved provider/model used for billing and routing.
              schema:
                type: string
            X-HPP-Router-Basket:
              description: Smart-routing basket when hpprouter/auto is used.
              schema:
                type: string
            X-HPP-Router-Rule-Id:
              description: Smart-routing rule id when hpprouter/auto is used.
              schema:
                type: string
            X-HPP-Router-Rules-Version:
              description: Smart-routing rules version when hpprouter/auto is used.
              schema:
                type: string
            X-HPP-Router-Tier:
              description: Smart-routing tier when available.
              schema:
                type: string
            X-PAYMENT-RESPONSE:
              description: >
                Base64-encoded on-chain settle receipt when the wallet rail was used.
                Decode to JSON to inspect the tx hash, settled amount, and network.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ChatCompletionResponse"
            text/event-stream:
              schema:
                type: string
                description: >
                  OpenAI-compatible SSE stream. Each `data:` line is a JSON chunk.
                  After the final content chunk, a settle event may appear:
                  `data: {"x402":{"tx":"0x...","amount":"1000","network":"...","payer":"0x..."}}`.
                  Followed by `data: [DONE]`.
        "402":
          description: >
            Payment required on the wallet rail and the keyless Agent path.
            Parse `accepts[0]`, sign it, and retry with `PAYMENT-SIGNATURE` or `X-PAYMENT`.
          headers:
            PAYMENT-REQUIRED:
              description: Base64-encoded copy of the 402 response body.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/X402PaymentRequired"
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "429":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
  /llm/v1/models:
    get:
      operationId: listModels
      summary: List available models
      description: >
        OpenAI-compatible model catalog with pricing and capability metadata.
        Authentication is optional for this endpoint.
      security: []
      responses:
        "200":
          description: OpenAI-compatible model list.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ModelListResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
  /v1/images/generations:
    post:
      operationId: createImageGeneration
      summary: Generate images
      description: >
        OpenAI-compatible image generation. `model` defaults to `gpt-image-1`.
        Other enabled `gpt-image-*` ids from `GET /llm/v1/models` are accepted.
        Wallet rail and the keyless Agent path use the same 402 retry as chat.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ImageGenerationRequest"
      responses:
        "200":
          description: Generated image response.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ImageGenerationResponse"
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "402":
          description: Payment required on the wallet rail or keyless Agent path.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/X402PaymentRequired"
        "429":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
  /api/usage:
    get:
      operationId: getUsage
      summary: Get current consumer usage
      description: >
        Usage and prepaid quota summary for the authenticated consumer.
        Pass `rail=wallet` to scope stats to the wallet payment rail and include
        on-chain USDC.e settlement fields.
      parameters:
        - name: rail
          in: query
          required: false
          schema:
            type: string
            enum: [wallet, quota]
          description: Optional payment-rail filter. `wallet` adds settlement fields.
      responses:
        "200":
          description: Usage and quota summary for the authenticated consumer.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/UsageResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "404":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
  /api/quota-check:
    get:
      operationId: checkQuota
      summary: Check current consumer quota
      responses:
        "200":
          description: Quota availability for the authenticated consumer.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/QuotaCheckResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "503":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
  /api/audit:
    get:
      operationId: listAuditLogs
      summary: List the caller usage logs
      description: >
        Usage log rows for the authenticated API key. This is the consumer
        audit list. `GET /api/user/audit/{logId}` is a portal session route and
        is not part of this contract.
      parameters:
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 500
            default: 100
        - name: offset
          in: query
          required: false
          schema:
            type: integer
            minimum: 0
            default: 0
        - name: rail
          in: query
          required: false
          schema:
            type: string
            enum: [wallet, quota]
          description: Optional payment-rail filter.
      responses:
        "200":
          description: Newest-first log rows for this consumer.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/AuditLog"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
  /api/logs/{logId}/verify:
    get:
      operationId: verifyAuditLog
      summary: Verify an on-chain audit anchor
      description: >
        Checks the Merkle anchor for a usage log id. Requires an API key.
        Returns `valid: false` when the log is missing or not yet batched.
      parameters:
        - name: logId
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Verification result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AuditVerifyResult"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "503":
          description: Blockchain audit is not configured.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorEnvelope"
        "500":
          $ref: "#/components/responses/ErrorResponse"
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: apikey
    BearerAuth:
      type: http
      scheme: bearer
  responses:
    ErrorResponse:
      description: Error response.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorEnvelope"
  schemas:
    ChatCompletionRequest:
      type: object
      additionalProperties: true
      required:
        - model
        - messages
      properties:
        model:
          type: string
          examples:
            - hpprouter/auto
            - openai/gpt-5
            - anthropic/claude-sonnet-4
            - moonshotai/kimi-k2.6
            - ollama/gpt-oss:120b
            - ollama/solidity-master:2
        messages:
          type: array
          items:
            $ref: "#/components/schemas/ChatMessage"
        stream:
          type: boolean
        max_tokens:
          type: integer
          minimum: 1
        max_completion_tokens:
          type: integer
          minimum: 1
        temperature:
          type: number
        stream_options:
          type: object
          additionalProperties: true
          description: >
            Forwarded on Anthropic, Moonshot, Ollama, and gpt-image chat calls.
            Dropped for OpenAI text models, which are translated to the Responses API.
    ChatMessage:
      type: object
      additionalProperties: true
      required:
        - role
        - content
      properties:
        role:
          type: string
          enum:
            - system
            - user
            - assistant
            - tool
        content:
          oneOf:
            - type: string
            - type: array
              items:
                $ref: "#/components/schemas/ChatContentPart"
    ChatContentPart:
      type: object
      additionalProperties: true
      required:
        - type
      properties:
        type:
          type: string
        text:
          type: string
        image_url:
          type: object
          additionalProperties: true
          properties:
            url:
              type: string
            detail:
              type: string
    ChatCompletionResponse:
      type: object
      additionalProperties: true
      properties:
        id:
          type: string
        object:
          type: string
        created:
          type: integer
        model:
          type: string
        choices:
          type: array
          items:
            type: object
            additionalProperties: true
        usage:
          $ref: "#/components/schemas/TokenUsage"
    TokenUsage:
      type: object
      additionalProperties: true
      properties:
        prompt_tokens:
          type: integer
        completion_tokens:
          type: integer
        total_tokens:
          type: integer
    ModelListResponse:
      type: object
      required:
        - object
        - data
      properties:
        object:
          type: string
          const: list
        data:
          type: array
          items:
            $ref: "#/components/schemas/Model"
    Model:
      type: object
      additionalProperties: true
      required:
        - id
        - object
        - owned_by
      properties:
        id:
          type: string
        object:
          type: string
          const: model
        owned_by:
          type: string
        name:
          oneOf:
            - type: string
            - type: "null"
        description:
          oneOf:
            - type: string
            - type: "null"
        pricing:
          oneOf:
            - $ref: "#/components/schemas/ModelPricing"
            - type: "null"
        context:
          oneOf:
            - type: number
            - type: "null"
        max_output:
          oneOf:
            - type: number
            - type: "null"
        tool:
          oneOf:
            - type: boolean
            - type: "null"
        structured:
          oneOf:
            - type: boolean
            - type: "null"
        knowledge_cutoff:
          oneOf:
            - type: string
            - type: "null"
        input_modalities:
          type: array
          items:
            type: string
        output_modalities:
          type: array
          items:
            type: string
    ModelPricing:
      type: object
      description: USD rates per token (multiply by 1_000_000 for $/1M).
      properties:
        input:
          type: number
          description: USD per input token.
        output:
          type: number
          description: USD per output token.
        cache_write:
          oneOf:
            - type: number
            - type: "null"
          description: USD per cache-write token, when applicable.
        cache_read:
          oneOf:
            - type: number
            - type: "null"
          description: USD per cache-read token, when applicable.
    ImageGenerationRequest:
      type: object
      required:
        - prompt
      properties:
        model:
          type: string
          default: gpt-image-1
        prompt:
          type: string
        n:
          type: integer
          minimum: 1
          maximum: 10
          default: 1
        size:
          type: string
          enum:
            - 1024x1024
            - 1024x1536
            - 1536x1024
          default: 1024x1024
        quality:
          type: string
          enum:
            - low
            - medium
            - high
            - auto
          default: auto
        background:
          type: string
        output_format:
          type: string
    ImageGenerationResponse:
      type: object
      additionalProperties: true
      properties:
        created:
          type: integer
        data:
          type: array
          items:
            type: object
            additionalProperties: true
            properties:
              b64_json:
                type: string
              url:
                type: string
        usage:
          type: object
          additionalProperties: true
    UsageResponse:
      type: object
      required:
        - consumer_id
        - quota
        - used
        - remaining
        - requests
        - total_tokens
        - total_cost
      properties:
        consumer_id:
          type: string
        username:
          oneOf:
            - type: string
            - type: "null"
        custom_id:
          oneOf:
            - type: string
            - type: "null"
        quota:
          type: number
          description: Prepaid quota limit (credit/quota rail snapshot).
        used:
          type: number
          description: Prepaid quota consumed.
        remaining:
          type: number
          description: Prepaid quota remaining.
        rail:
          type: string
          enum: [wallet, quota]
          description: Present when the request filtered by `?rail=`.
        spent_usdc_micro:
          type: number
          description: >
            Total USDC.e settled on-chain in atomic/micro units.
            Present when `rail=wallet`.
        settle_success_count:
          type: integer
          description: Successful on-chain settlements. Present when `rail=wallet`.
        settle_failed_count:
          type: integer
          description: Failed on-chain settlements. Present when `rail=wallet`.
        requests:
          type: integer
        total_tokens:
          type: integer
        total_cost:
          type: number
          description: >
            Dollar cost. For `rail=wallet`, reflects wallet-settled spend from
            usage logs rather than prepaid `used`.
    QuotaCheckResponse:
      type: object
      required:
        - has_quota
        - quota
        - used
        - remaining
      properties:
        has_quota:
          type: boolean
        quota:
          type: number
        used:
          type: number
        remaining:
          type: number
    AuditLog:
      type: object
      description: One row from `GET /api/audit`.
      properties:
        id:
          type: string
        consumer_id:
          type: string
        provider:
          type: string
        model:
          type: string
        displayName:
          type: string
        prompt_tokens:
          type: integer
        completion_tokens:
          type: integer
        total_tokens:
          type: integer
        cost:
          type: number
        status:
          type: string
        blockchain_tx_hash:
          type: string
        payment_rail:
          type: string
        settle_status:
          type: string
        settle_amount_micro:
          type: number
        created_at:
          type: number
          description: Unix timestamp in milliseconds.
    AuditVerifyResult:
      type: object
      properties:
        valid:
          type: boolean
        reason:
          type: string
          description: Present when `valid` is false.
        batchId:
          type: integer
        txHash:
          type: string
        nonce:
          type: integer
        blockNumber:
          type: integer
        merkleRoot:
          type: string
        leafHash:
          type: string
    X402PaymentRequired:
      type: object
      description: >
        x402 payment-required body returned with HTTP 402. Parse `accepts[0]`,
        sign it, encode the payload as base64, and retry with `PAYMENT-SIGNATURE`
        (v2) or `X-PAYMENT` (v1).
      required:
        - x402Version
        - error
        - resource
        - accepts
      properties:
        x402Version:
          type: integer
          description: x402 protocol version (currently 2).
          example: 2
        error:
          type: string
          example: Payment required
        resource:
          $ref: "#/components/schemas/X402Resource"
        accepts:
          type: array
          items:
            $ref: "#/components/schemas/X402Accepts"
        extensions:
          type: object
          additionalProperties: true
    X402Resource:
      type: object
      required:
        - url
      properties:
        url:
          type: string
        description:
          type: string
        mimeType:
          type: string
    X402Accepts:
      type: object
      required:
        - scheme
        - network
        - asset
        - amount
        - payTo
      properties:
        scheme:
          type: string
          example: upto
        network:
          type: string
          description: CAIP-2 chain identifier.
          example: eip155:84532
        asset:
          type: string
          description: ERC-20 token contract address.
        amount:
          type: string
          description: Maximum amount in token micro-units.
          example: "1000"
        payTo:
          type: string
        maxTimeoutSeconds:
          type: integer
        extra:
          type: object
          additionalProperties: true
    X402SettleMeta:
      type: object
      description: >
        Settle metadata in the SSE stream after content, as
        `data: {"x402":{...}}` before `data: [DONE]`.
      properties:
        tx:
          oneOf:
            - type: string
            - type: "null"
        amount:
          oneOf:
            - type: string
            - type: "null"
        network:
          oneOf:
            - type: string
            - type: "null"
        payer:
          oneOf:
            - type: string
            - type: "null"
        error:
          type: string
    ErrorEnvelope:
      oneOf:
        - type: object
          required:
            - error
          properties:
            error:
              type: string
            message:
              type: string
        - type: object
          required:
            - error
          properties:
            error:
              type: object
              additionalProperties: true
              properties:
                message:
                  type: string
                type:
                  type: string
                code:
                  type: string
                provider:
                  type: string
                upstream_status:
                  type: integer
                retryable:
                  type: boolean
