openapi: 3.1.0
info:
  title: Domainio API
  description: Domain registrar API for AI agents. Search, register, and manage domain names programmatically.
  version: 1.0.0
  contact:
    name: Domainio Support
    url: https://domainio.nl

servers:
  - url: https://domainio.nl
    description: Production
  - url: https://test.domainio.nl
    description: Sandbox

security:
  - BearerAuth: []

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: API key in format `dk_live_*` (production) or `dk_test_*` (sandbox)
    OwnerRegistrationAuth:
      type: http
      scheme: bearer
      description: One-time `dor_*` token approved by a signed-in Domainio admin for a specific registration.
    SessionAuth:
      type: apiKey
      in: cookie
      name: next-auth.session-token
      description: NextAuth session cookie for browser-based users

  # Every one of these was `$ref`'d from a path and NONE of them
  # existed: `#/components/responses/{Unauthorized,Forbidden,NotFound,
  # BadRequest,RateLimited}` were dangling pointers, so the document
  # advertised at `/.well-known/ai-plugin.json` did not resolve. A
  # client generator either errors or silently drops the response.
  responses:
    BadRequest:
      description: Validation failed — the request body or query is invalid
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example: { success: false, error: "Invalid request data" }
    Unauthorized:
      description: Missing or invalid credentials
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example: { success: false, error: "API key required" }
    Forbidden:
      description: Authenticated, but the key lacks the required scope
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            success: false
            error: "Scope 'domains:write' required. Key has: domains:read"
    NotFound:
      description: The resource does not exist, or is not yours
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example: { success: false, error: "Not found" }
    RateLimited:
      description: >-
        Rate limit exceeded for the key's subscription tier. Read
        `X-RateLimit-Reset` before retrying.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example: { success: false, error: "Rate limit exceeded" }

  schemas:
    Error:
      type: object
      required: [success, error]
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
    Success:
      type: object
      required: [success, data]
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
    OwnerRegistration:
      type: object
      required: [domainName, status, simulated]
      properties:
        domainName: { type: string, example: example.com }
        status: { type: string, enum: [ACTIVE, PENDING] }
        simulated: { type: boolean }
    Domain:
      type: object
      properties:
        id: { type: string }
        domainName: { type: string, example: example.com }
        status:
          type: string
          enum: [PENDING, ACTIVE, EXPIRING, EXPIRED, FAILED, SUSPENDED]
        expiryDate: { type: string, format: date-time }
        autoRenew: { type: boolean }
        privacyEnabled: { type: boolean }
    DomainIntelligence:
      type: object
      properties:
        domain: { type: string }
        reasoning: { type: string }
        brandabilityScore: { type: number, minimum: 1, maximum: 10 }
        pronunciationFlag:
          type: string
          enum: [easy, moderate, difficult]
        seoScore: { type: number, minimum: 1, maximum: 10 }
        trademarkRisk:
          type: string
          enum: [none, potential, high]
        reputationStatus:
          type: string
          enum: [clean, flagged]
        alternatives:
          type: array
          items: { type: string }
    Conversation:
      type: object
      properties:
        id: { type: string }
        title: { type: string, nullable: true }
        organizationId: { type: string, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    ConversationMessage:
      type: object
      properties:
        id: { type: string }
        conversationId: { type: string }
        role:
          type: string
          enum: [USER, ASSISTANT, TOOL, SYSTEM]
        content: { type: string }
        inputTokens: { type: integer, nullable: true }
        outputTokens: { type: integer, nullable: true }
        createdAt: { type: string, format: date-time }
    ApiKey:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        keyPrefix: { type: string, example: dk_live_ }
        scopes:
          type: array
          items: { type: string }
        lastUsedAt: { type: string, format: date-time, nullable: true }
        createdAt: { type: string, format: date-time }

paths:
  /api/agent/domains/register-owner:
    post:
      operationId: registerOwnerDomain
      summary: Place an approved owner domain registration
      tags: [Domains]
      security:
        - OwnerRegistrationAuth: []
      description: |-
        In Domainio, an admin opens **Admin → Domains**, checks the one-year
        registrar cost, selects a saved registrant, and chooses **Authorize
        an agent to register**. Use the resulting token before its 10-minute
        expiry. The token fixes the domain, registrant, and approved amount.
        Send no request body. Domainio rechecks availability, cost, and
        wallet funds before submitting. This operation uses the reseller
        wallet. After a 202 or an interrupted response, check Admin → Domains
        for the order before attempting another purchase.
      responses:
        "201":
          description: Registration confirmed
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success: { const: true }
                  data: { $ref: "#/components/schemas/OwnerRegistration" }
        "202":
          description: Registrar outcome pending reconciliation
          content:
            application/json:
              schema:
                type: object
                required: [success, data]
                properties:
                  success: { const: true }
                  data: { $ref: "#/components/schemas/OwnerRegistration" }
        "401":
          description: Missing, invalid, or expired owner registration token
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: Authorization used or invalidated, registration already exists, quote changed, or wallet funds are insufficient
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "502":
          description: Registrar quote or registration could not be completed
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  # ─── API Keys ──────────────────────────────────────────────
  /api/agent/api-keys:
    get:
      summary: List API keys
      tags: [API Keys]
      security:
        - SessionAuth: []
      responses:
        "200":
          description: List of active API keys
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Success"
                  - type: object
                    properties:
                      data:
                        type: array
                        items:
                          $ref: "#/components/schemas/ApiKey"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      summary: Create API key
      tags: [API Keys]
      security:
        - SessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, scopes]
              properties:
                name: { type: string, maxLength: 64 }
                scopes:
                  type: array
                  items:
                    type: string
                    enum:
                      [
                        domains:read,
                        domains:write,
                        dns:read,
                        dns:write,
                        email:read,
                        email:write,
                        account:read,
                        account:write,
                        billing:read,
                        billing:write,
                      ]
                spendLimit:
                  { type: number, description: Max spend per period (EUR) }
                spendLimitPeriod:
                  type: string
                  enum: [daily, weekly, monthly]
                requireApprovalAbove: { type: number }
                mode:
                  type: string
                  enum: [live, test]
                  default: live
            example:
              name: my-agent
              scopes: [domains:read, domains:write, dns:write]
              spendLimit: 100
              spendLimitPeriod: monthly
      responses:
        "201":
          description: Key created — full key shown ONCE
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Success"
                  - type: object
                    properties:
                      data:
                        allOf:
                          - $ref: "#/components/schemas/ApiKey"
                          - type: object
                            properties:
                              key:
                                type: string
                                example: dk_live_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4
        "400":
          $ref: "#/components/responses/BadRequest"

  /api/agent/api-keys/{id}:
    delete:
      summary: Revoke API key
      tags: [API Keys]
      security:
        - SessionAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Key revoked
        "404":
          $ref: "#/components/responses/NotFound"

  # ─── Balance ──────────────────────────────────────────────
  /api/agent/balance:
    get:
      summary: Get account balance
      tags: [Balance]
      security:
        - BearerAuth: []
      description: Requires scope `billing:read`
      parameters:
        - name: transactions
          in: query
          required: false
          schema: { type: boolean }
          description: If true, returns paginated transaction history instead of balance
        - name: page
          in: query
          required: false
          schema: { type: integer, default: 1 }
      responses:
        "200":
          description: Current balance or paginated transactions
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Success"
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          balance: { type: number, example: 42.50 }
                          currency: { type: string, example: EUR }
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"

  /api/agent/balance/topup:
    post:
      summary: Top up balance
      tags: [Balance]
      security:
        - BearerAuth: []
      description: Requires scope `billing:write`. Creates a Mollie payment URL.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount, redirectUrl]
              properties:
                amount: { type: number, minimum: 1, maximum: 500 }
                redirectUrl: { type: string, format: uri }
      responses:
        "201":
          description: Payment URL created
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Success"
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          paymentUrl: { type: string, format: uri }
                          paymentId: { type: string }

  # ─── AI Domain Suggestions ────────────────────────────────
  /api/agent/ai/suggest:
    post:
      summary: AI domain suggestions
      tags: [AI Search]
      security:
        - BearerAuth: []
      description: |
        Requires scope `domains:read`.
        Returns AI-generated domain suggestions with brandability, SEO,
        trademark risk, and reputation scoring.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [query]
              properties:
                query: { type: string, maxLength: 200 }
                keywords:
                  type: array
                  items: { type: string }
                  maxItems: 10
                count: { type: integer, minimum: 1, maximum: 20, default: 10 }
            example:
              query: eco-friendly yoga brand
              keywords: [yoga, eco, wellness]
              count: 10
      responses:
        "200":
          description: >-
            Scored domain suggestions, plus the conversation the call
            persisted. `conversationId` used to sit BESIDE `data`; it is
            inside it now, so a client reading only the envelope's `data`
            (as the official SDK does) can see it at all.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Success"
                  - type: object
                    properties:
                      data:
                        type: object
                        required: [suggestions, conversationId]
                        properties:
                          suggestions:
                            type: array
                            items:
                              $ref: "#/components/schemas/DomainIntelligence"
                          conversationId:
                            type: string
                            description: >-
                              Append to it with POST
                              /api/agent/conversations/{id}/messages, or
                              delete the row when done.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          description: >-
            Rate limit OR AI token quota exceeded — the two share this
            status and only the `error` string tells them apart.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "500":
          description: >-
            The suggestion failed upstream. The body is OUR sentence
            ("AI suggestion failed") — the thrown message is logged, not
            echoed (#381).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  # ─── MCP ──────────────────────────────────────────────────
  /api/mcp:
    post:
      summary: MCP JSON-RPC 2.0 endpoint
      tags: [MCP]
      security:
        - BearerAuth: []
      description: |
        Model Context Protocol server. AI platforms send JSON-RPC 2.0 requests.

        **Methods:**
        - `tools/list` — discover available tools
        - `tools/call` — execute a tool

        Use `X-Session-Id` header for multi-step workflow context (30-min TTL).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [jsonrpc, method, id]
              properties:
                jsonrpc: { type: string, enum: ["2.0"] }
                method: { type: string, enum: [tools/list, tools/call] }
                id: { type: [string, number, "null"] }
                params: { type: object }
            examples:
              list:
                summary: List tools
                value: { jsonrpc: "2.0", method: "tools/list", id: 1 }
              call:
                summary: Call a tool
                value:
                  jsonrpc: "2.0"
                  method: "tools/call"
                  id: 2
                  params:
                    name: search_domains
                    arguments: { query: eco yoga brand, mode: ai }
      responses:
        "200":
          description: JSON-RPC response

  # ─── Agent Webhooks ───────────────────────────────────────
  /api/agent/webhooks:
    get:
      summary: List webhook subscriptions
      tags: [Webhooks]
      security:
        - BearerAuth: []
      description: Requires scope `account:read`
      responses:
        "200":
          description: Webhook subscriptions
    post:
      summary: Subscribe to events
      tags: [Webhooks]
      security:
        - BearerAuth: []
      description: Requires scope `account:write`. URL must be HTTPS.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events, secret]
              properties:
                url: { type: string, format: uri }
                events:
                  type: array
                  items:
                    type: string
                    enum:
                      - domain.registered
                      - domain.expiring
                      - domain.expired
                      - transfer.initiated
                      - transfer.completed
                      - dns.propagated
                      - ssl.provisioned
                      - watchlist.available
                secret:
                  type: string
                  minLength: 16
                  description: Used to verify HMAC-SHA256 signatures
            example:
              url: https://my-agent.example.com/webhook
              events: [domain.registered, domain.expiring]
              secret: whsec_mySuperSecretKey1234567
      responses:
        "201":
          description: Subscribed

  /api/agent/webhooks/{id}:
    delete:
      summary: Unsubscribe webhook
      tags: [Webhooks]
      security:
        - BearerAuth: []
      description: Requires scope `account:write`
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Unsubscribed
        "404":
          $ref: "#/components/responses/NotFound"

  # ─── Conversations ─────────────────────────────────────────
  /api/agent/conversations:
    get:
      summary: List conversations
      tags: [Conversations]
      security:
        - BearerAuth: []
      description: >-
        Requires scope `conversations:read`. Returns the 50 most recent
        conversations visible to the key's owner; an org-scoped key also
        sees the organization's.
      responses:
        "200":
          description: Conversations
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Success"
                  - type: object
                    properties:
                      data:
                        type: array
                        items:
                          $ref: "#/components/schemas/Conversation"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"
    post:
      summary: Start a conversation
      tags: [Conversations]
      security:
        - BearerAuth: []
      description: >-
        Requires scope `conversations:write`. An org-scoped key creates an
        org-owned conversation. `firstMessage`, when given, is appended as
        the first USER message.
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                title: { type: string, maxLength: 200 }
                firstMessage: { type: string, minLength: 1, maxLength: 10000 }
            example:
              title: Finding a name for my bakery
              firstMessage: I need a short .nl domain for a sourdough bakery
      responses:
        "201":
          description: Conversation created
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Success"
                  - type: object
                    properties:
                      data:
                        $ref: "#/components/schemas/Conversation"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/RateLimited"

  /api/agent/conversations/{id}/messages:
    post:
      summary: Append a message
      tags: [Conversations]
      security:
        - BearerAuth: []
      description: >-
        Requires scope `conversations:write`. The token quota is checked on
        every append, so a looping agent is refused with 429 immediately
        rather than after the next model call. For an org-scoped key the
        quota is the OWNER's tier.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [role, content]
              properties:
                role:
                  type: string
                  enum: [USER, ASSISTANT, TOOL, SYSTEM]
                content: { type: string, minLength: 1, maxLength: 50000 }
                toolCalls:
                  description: Free-form record of tool calls made for this message
                inputTokens: { type: integer, minimum: 0 }
                outputTokens: { type: integer, minimum: 0 }
            example:
              role: ASSISTANT
              content: brood.nl and zuurdesem.nl are both available.
              inputTokens: 812
              outputTokens: 96
      responses:
        "201":
          description: Message appended
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Success"
                  - type: object
                    properties:
                      data:
                        $ref: "#/components/schemas/ConversationMessage"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          description: >-
            Rate limit OR token quota exceeded — the two share this status,
            and the `error` string is what tells them apart.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
              example:
                success: false
                error: "Monthly token quota exceeded for the FREE tier"
