openapi: 3.0.3
info:
  title: naturali.ai — Channels API
  version: 1.0.0
  description: >
    Channels, scoped to a project. A channel is a customer's connected messaging
    surface — a WhatsApp number, a Discord app whose bot converses in DMs
    and in server threads, or an X bot answering X Chat direct messages. Unlike agents and tools, a
    channel is naturali-native (the runtime has no channel concept), so the
    naturali record carries its state. The access token is stored write-only as
    a secret on the runtime and never returned — reads report only
    `has_credential`. Discord's bot token is instead sealed in naturali's
    encrypted store, because the Gateway worker must present the raw token to
    authenticate its WebSocket.

    A customer authorizes naturali to send on their number without handing over a
    token via Meta Embedded Signup (`credential_source: embedded_signup`) where
    this deployment enables it, else `501`; otherwise the same secret is filled
    by a customer-pasted token (`byot`). Both paths share the entire downstream
    pipeline.

    Every channel carries a **default action** — what happens when nothing else
    matches (agent / fixed message / silence), required on connect and
    patchable after. A project's own `routes` can answer differently per surface
    and condition, and an `address` can override both for one identifier —
    three places, one shape.
  contact:
    name: naturali.ai
    url: https://naturali.ai
servers:
  - url: '{baseUrl}'
    description: Host of your naturali.ai deployment; every path carries the /v1 prefix.
    variables:
      baseUrl:
        description: Base host URL.
        default: https://api.naturali.ai
tags:
  - name: Channels
    description: Connect and manage a project's messaging surfaces (WhatsApp, Discord, X).
security:
  - bearerAuth: []
  - oauth2:
      - mcp:access
paths:
  /v1/projects/{project_id}/channels:
    parameters:
      - $ref: '#/components/parameters/ProjectId'
    get:
      tags: [Channels]
      summary: List channels
      description: Lists the channels connected in the project.
      operationId: listChannels
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: A page of channels.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - properties:
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/Channel'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    post:
      tags: [Channels]
      summary: Connect a channel
      description: >
        Connect a channel. The required fields depend on `channel`; no
        credential is ever returned.

        **Discord** (`channel: discord`) — supply `application_id` and
        `bot_token`, plus the `modes` selecting which Gateway flows to serve
        (direct messages, and/or @mention-opens-a-thread). The token is
        checked with Discord first: `400 INVALID_BOT_TOKEN` when Discord
        rejects it, `400 APPLICATION_MISMATCH` when it belongs to another
        application, `502 DISCORD_UNAVAILABLE` when Discord cannot be read.
        Returns `501` when this deployment does not enable
        Discord channels.

        **X** (`channel: x`) — supply the bot's `bot_token` (X developer
        portal, Chat bots) and the `consumer_key` and `consumer_secret` of the
        app that issued it. naturali then registers its own webhook on that
        app, subscribes it to the bot's incoming direct messages and
        registers the bot's chat encryption key, keeping the private key
        sealed: replies are end-to-end encrypted, and the project never
        handles keys, webhooks or ciphertext. Pass `chat_private_keys` and
        `chat_key_version` instead to keep a key the bot already registered.
        `400 INVALID_BOT_TOKEN` or `400 INVALID_CONSUMER_CREDENTIALS` when X
        rejects a credential, `409 BOT_IN_USE` when another channel holds the
        bot, `502 X_PROVISIONING_FAILED` when X refuses the webhook or the
        subscription (an app holds a limited number of webhooks), `429
        X_KEY_REGISTRATION_LIMITED` when the bot used its few daily key
        registrations, `502 X_UNAVAILABLE` when X cannot be reached. Returns
        `501` when this deployment does not enable X channels.

        **WhatsApp** (default) — one of two credential paths, both filling the
        same write-only secret:

        * **BYOT** (`credential_source: byot`, default) — supply
          `phone_number_id` and `access_token` from your own Meta app. The
          number is read with the token first: `400 INVALID_ACCESS_TOKEN` when
          Meta rejects the token, `400 PHONE_NUMBER_NOT_ACCESSIBLE` when it
          cannot reach that number, `502 META_UNAVAILABLE` when Meta fails.
          The token's app is then subscribed to the WABA Meta reports as the
          number's owner, which is the `waba_id` stored:
          `400 WABA_NOT_MANAGEABLE` when the token cannot subscribe to it.

        * **Embedded signup** (`credential_source: embedded_signup`) — supply
          `code` and `waba_id` from the Meta popup; naturali exchanges the
          `code` for the token, subscribes its app to the WABA and registers the
          number for sending when it is not yet, so the customer never hands
          over a token. Returns `501` on deployments where Meta App credentials
          are not configured.


        The project's plan limits how many channels it may hold. At the limit
        this responds `403` with `PLAN_LIMIT_REACHED`, whose `meta` carries the
        `plan` and the `limit`, before any credential is acquired. Only `active`
        channels count, so disabling one frees allowance without deleting it.
      operationId: createChannel
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChannelCreate'
      responses:
        '201':
          description: Channel created.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Channel'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          description: >
            `X_KEY_REGISTRATION_LIMITED` — the X bot used its daily chat key
            registrations; `meta.reset_at` says when it may register again.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '501':
          $ref: '#/components/responses/NotImplemented'
        '502':
          $ref: '#/components/responses/UpstreamUnavailable'
  /v1/projects/{project_id}/channels/whatsapp/signup-links:
    parameters:
      - $ref: '#/components/parameters/ProjectId'
    post:
      tags:
        - Channels
      summary: Create a WhatsApp signup link
      description: >
        A Meta Embedded Signup URL for this project, to hand to the person who
        owns the WhatsApp number. They sign in with Meta and pick or create the
        business account and number; no popup is needed. The dialog ends on
        naturali's app, where a signed-in member of this project confirms the
        number, and it is linked as a channel with
        `credential_source: embedded_signup` (`POST
        /v1/channels/whatsapp/signup/complete`).


        The link only links the number: the channel starts with
        `default: { action: silence }`, so it answers nothing until an agent
        is bound to it with `PATCH
        /v1/projects/{project_id}/channels/{channel_id}` or a route.


        The link is good for 30 minutes. A number not yet registered
        for sending is registered with a two-step verification PIN naturali
        generates and does not keep; the owner can reset it in WhatsApp
        Manager. Returns `501` on deployments where Meta signup is not
        configured.
      operationId: createWhatsappSignupLink
      responses:
        '201':
          description: Link created.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WhatsAppSignupLink'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '501':
          $ref: '#/components/responses/NotImplemented'
  /v1/channels/whatsapp/signup/complete:
    post:
      tags:
        - Channels
      summary: Complete a WhatsApp signup
      description: >
        Finish a signup link: the app's result page receives `pending` and the
        numbers Meta granted, and sends back the one to connect. The caller
        must be a member of the project the link was created for (`404`
        otherwise), so a link opened by anyone else connects nothing.
        `pending` expires 10 minutes after the dialog returns
        (`400 LINK_EXPIRED`).
      operationId: completeWhatsappSignup
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WhatsAppSignupComplete'
      responses:
        '201':
          description: Channel created.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Channel'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '501':
          $ref: '#/components/responses/NotImplemented'
        '502':
          $ref: '#/components/responses/UpstreamUnavailable'
  /v1/projects/{project_id}/channels/{channel_id}:
    parameters:
      - $ref: '#/components/parameters/ProjectId'
      - $ref: '#/components/parameters/ChannelId'
    get:
      tags: [Channels]
      summary: Get a channel
      description: >
        The channel's state, its transport modes and its default action. The
        access token is never returned — `has_credential` is all a read says
        about it.
      operationId: getChannel
      responses:
        '200':
          description: Channel details.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Channel'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    patch:
      tags: [Channels]
      summary: Update a channel
      description: >
        Rotate the credential, update the kind's config (`waba_id` /
        `credential_source` for WhatsApp, `modes` for Discord), or flip the
        naturali-side status. At least one field is required. Rotating a
        WhatsApp token first reads the number with it, as connect does
        (`400 INVALID_ACCESS_TOKEN`, `400 PHONE_NUMBER_NOT_ACCESSIBLE`,
        `502 META_UNAVAILABLE`, keeping the old token), then stores a new
        write-only secret, repoints the send tool and deletes the old secret;
        rotating a Discord bot token reseals it and the gateway worker
        reconnects with it.
      operationId: updateChannel
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChannelUpdate'
      responses:
        '200':
          description: Channel updated.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Channel'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '502':
          $ref: '#/components/responses/UpstreamUnavailable'
    delete:
      tags: [Channels]
      summary: Delete a channel
      description: >
        Deletes the channel and whatever it provisioned — the WhatsApp send tool
        and write-only credential secret, or the Discord channel's sealed bot
        token (dropped with the row, closing its gateway connection).
      operationId: deleteChannel
      responses:
        '204':
          description: Channel deleted.
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '502':
          $ref: '#/components/responses/UpstreamUnavailable'
  /v1/projects/{project_id}/channels/{channel_id}/conversations:
    parameters:
      - $ref: '#/components/parameters/ProjectId'
      - $ref: '#/components/parameters/ChannelId'
    post:
      tags: [Channels]
      summary: Open a conversation
      description: >
        The outbound-first path: open a conversation for an `identifier` ahead of
        any inbound message, which falls out of making the identifier the unit
        rather than the message. Resolves the same three-layer action an inbound
        would; a `409` when that does not land on an agent — there is nothing to
        open for a `message`/`silence` outcome.
      operationId: openChannelConversation
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [identifier]
              properties:
                identifier:
                  type: string
                  description: >-
                    The address identifier, in this channel's kind
                    (`whatsapp:dm:<phone>`, `discord:dm:<user_id>`,
                    `x:dm:<user_id>`); any other form is `400`.
                  example: 'discord:dm:425678901234567890'
      responses:
        '201':
          description: Conversation opened (or already existing).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Conversation'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'
        '502':
          $ref: '#/components/responses/UpstreamUnavailable'
    get:
      tags: [Channels]
      summary: List the channel's conversations
      description: >
        A cursor page of the channel's conversations, newest first. A
        conversation is one address's dialogue on the channel — the continuity
        anchor that resumes the same runtime session instead of starting fresh per
        message — so this is the read path for who has talked to the channel and
        which actor/session their dialogue resolved to.

        Conversations are created by the inbound path (the WhatsApp and X
        webhooks, the Discord gateway worker) when a real message arrives; there is no way to
        create one directly.
      operationId: listChannelConversations
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
        - name: identifier
          in: query
          required: false
          description: >
            Filter to one address by the identifier conversations carry
            (`discord:dm:<user_id>`, `discord:thread:<guild_id>:<channel_id>`,
            `whatsapp:dm:<phone>`, `x:dm:<user_id>`), in this channel's kind; any other form is
            `400`. At most one row matches.
          schema:
            type: string
            example: 'discord:dm:425678901234567890'
      responses:
        '200':
          description: A page of conversations.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - properties:
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/Conversation'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /v1/projects/{project_id}/channels/{channel_id}/conversations/{conversation_id}:
    parameters:
      - $ref: '#/components/parameters/ProjectId'
      - $ref: '#/components/parameters/ChannelId'
      - $ref: '#/components/parameters/ConversationId'
    get:
      tags: [Channels]
      summary: Get a conversation
      description: >
        Where the conversation points: the address it belongs to, the route (or
        sentinel) whose action opened it, and the runtime session it maps 1:1
        to. The messages are not here — read them with
        [`GET /v1/projects/{project_id}/channels/{channel_id}/conversations/{conversation_id}/messages`](/docs/api/channels/list-channel-conversation-messages).
      operationId: getChannelConversation
      responses:
        '200':
          description: The conversation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Conversation'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      tags: [Channels]
      summary: Delete a conversation
      description: >
        Removes the conversation and the runtime session it maps to. The
        address, its actor and its other conversations are left alone; the
        address's next message opens a fresh conversation. To erase the address
        itself, use
        [`DELETE /v1/projects/{project_id}/addresses/{identifier}`](/docs/api/addresses/delete-address).
      operationId: deleteChannelConversation
      responses:
        '204':
          description: Conversation deleted.
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
  /v1/projects/{project_id}/channels/{channel_id}/conversations/{conversation_id}/messages:
    parameters:
      - $ref: '#/components/parameters/ProjectId'
      - $ref: '#/components/parameters/ChannelId'
      - $ref: '#/components/parameters/ConversationId'
    get:
      tags: [Channels]
      summary: Read a conversation's transcript
      description: >
        The conversation's messages, oldest first. naturali stores no message
        bodies — the dialogue lives in the runtime session the conversation maps
        to, so this reads through to the runtime.
      operationId: listChannelConversationMessages
      parameters:
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: A page of messages.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - properties:
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/ConversationMessage'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '502':
          $ref: '#/components/responses/UpstreamUnavailable'
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: A naturali API key (nat_sk_…) or a session JWT.
    oauth2:
      type: oauth2
      description: >-
        A connected app's OAuth access token, issued by this API's authorization
        server (discovery: /.well-known/oauth-authorization-server). Its one scope
        carries every operation, confined to the projects the user chose when
        approving the app.
      flows:
        authorizationCode:
          authorizationUrl: https://api.naturali.ai/authorize
          tokenUrl: https://api.naturali.ai/token
          refreshUrl: https://api.naturali.ai/token
          scopes:
            mcp:access: Every operation this API serves, on the projects the grant covers.
  parameters:
    Limit:
      name: limit
      in: query
      required: false
      description: >-
        Results per page, 1 to 100 (default 50). Above 100 it is clamped; below 1
        or not an integer it is `400`.
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 50
    Cursor:
      name: cursor
      in: query
      required: false
      description: >-
        The previous page's `next_cursor`; omit it for the first page. A cursor
        this list did not issue is `400`.
      schema:
        type: string
    ProjectId:
      name: project_id
      in: path
      required: true
      description: Project public ID (proj_ prefix).
      schema:
        type: string
        example: proj_V1StGXR8Z5jdHi6B
    ChannelId:
      name: channel_id
      in: path
      required: true
      description: Channel public ID (chan_ prefix).
      schema:
        type: string
        example: chan_V1StGXR8Z5jdHi6B
    ConversationId:
      name: conversation_id
      in: path
      required: true
      description: Conversation public ID (conv_ prefix).
      schema:
        type: string
        example: conv_V1StGXR8Z5jdHi6B
  responses:
    Unauthorized:
      description: Missing or invalid credentials.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    BadRequest:
      description: The request was malformed or failed validation.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: >-
        The credential is scoped to a different project, or the caller's role in
        the project does not carry this action.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFound:
      description: The resource does not exist (existence is not leaked).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Conflict:
      description: The request conflicts with the resource's current state.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotImplemented:
      description: >
        The requested path is not enabled on this deployment (e.g. embedded
        signup, or a Discord or X channel, where it is not enabled).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    UpstreamUnavailable:
      description: >
        The upstream runtime, or Meta, could not complete the operation.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  schemas:
    Page:
      type: object
      description:
        One page of a list. Rows inserted or removed between two calls neither repeat nor skip
        a row on the next page.
      required:
        - data
        - next_cursor
      properties:
        data:
          type: array
          description: This page's items, in the list's order.
          items: {}
        next_cursor:
          type: string
          nullable: true
          description: Pass as `cursor` to fetch the next page; `null` on the last page.
    ErrorResponse:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          description: >-
            Structured error. Every error response uses this shape, so `code` can
            be read without first checking the type of `error`.
          required:
            - code
            - message
            - hint
          properties:
            code:
              type: string
              pattern: '^[A-Z][A-Z0-9_]*$'
              description: >-
                Machine-readable error code, UPPER_SNAKE whether naturali or the
                runtime raises it.
              example: FORBIDDEN
            message:
              type: string
              description: Human-readable explanation.
              example: Your role in this project does not carry this action.
            hint:
              type: string
              description: >-
                What to do about it, naming the routes of this API to call. For
                people and agents; it may change, so branch on `code`.
              example: >-
                Use a credential whose scope includes this action, or ask a
                project `admin` or `owner` to act; the caller's role or key
                excludes it.
            meta:
              type: object
              additionalProperties: true
              description: >-
                Structured context, such as the `resource` and `limit` of a
                `PLAN_LIMIT_REACHED`.
    Channel:
      type: object
      properties:
        id:
          type: string
          description: Public channel ID (chan_ prefix).
          example: chan_V1StGXR8Z5jdHi6B
        project_id:
          type: string
          description: "The owning project."
          example: proj_V1StGXR8Z5jdHi6B
        channel:
          type: string
          description: "The channel kind."
          enum: [whatsapp, discord, x]
          example: whatsapp
        status:
          type: string
          enum: [active, disabled]
          example: active
        credential_source:
          type: string
          enum: [byot, embedded_signup]
          description: How the credential was obtained.
          example: byot
        phone_number_id:
          type: string
          nullable: true
          description: WhatsApp phone number id; inbound webhooks route on this. Null for non-WhatsApp channels.
          example: '109999999999999'
        waba_id:
          type: string
          nullable: true
          description: WhatsApp Business Account id, when known.
          example: '104444444444444'
        display_phone_number:
          type: string
          nullable: true
          description: >
            The number as Meta displays it, read when the number was linked by
            embedded signup. Null for other channels and other credential sources.
          example: '+55 11 90000-0001'
        verified_name:
          type: string
          nullable: true
          description: >
            The business name Meta shows for the number, when known; null on the
            same terms as `display_phone_number`.
          example: Acme Suporte
        application_id:
          type: string
          nullable: true
          description: >
            Discord application id — the tenant's app, one channel per app. The
            gateway worker holds one connection per channel. Null for
            non-Discord channels.
          example: '1290000000000000000'
        modes:
          $ref: '#/components/schemas/DiscordModes'
        bot_user_id:
          type: string
          nullable: true
          description: X. The bot account's user id. Absent for other kinds.
          example: '2120530761568624641'
        username:
          type: string
          nullable: true
          description: X. The bot account's handle, without `@`. Absent for other kinds.
          example: acmebot
        chat_key_version:
          type: string
          nullable: true
          description: >
            X. The version of the bot's registered chat encryption key. Absent
            for other kinds.
          example: '1794500630168'
        default:
          $ref: '#/components/schemas/ChannelAction'
        max_context_messages:
          type: integer
          nullable: true
          description: >
            The most recent messages each conversation's session sends the
            model, taking precedence over the agent's own
            `max_context_messages`. Null defers to the agent.
          example: 20
        has_credential:
          type: boolean
          description: Whether an access token is on file (its value is never returned).
          example: true
        gateway_error:
          type: object
          nullable: true
          description: >
            Why Discord refused this channel's gateway connection, when it did:
            the worker stops retrying, so the channel stays silent until a
            `PATCH` changes `bot_token`, `modes` or `status`, which clears it.
            Null when there is none, and for non-Discord channels.
          properties:
            code:
              type: string
              enum: [invalid_bot_token, disallowed_intents, gateway_rejected]
              description: >
                `INVALID_BOT_TOKEN` — the token was reset or revoked.
                `disallowed_intents` — `mention_threads` needs the privileged
                Message Content intent enabled on the Discord application.
            close_code:
              type: integer
              description: The gateway close code Discord sent.
              example: 4004
            at:
              type: string
              format: date-time
          required: [code, close_code, at]
        created_at:
          type: string
          format: date-time
          example: '2026-07-23T00:00:00.000Z'
        updated_at:
          type: string
          format: date-time
          example: '2026-07-23T00:00:00.000Z'
      required:
        - id
        - project_id
        - channel
        - status
        - credential_source
        - phone_number_id
        - waba_id
        - application_id
        - modes
        - default
        - has_credential
        - gateway_error
        - created_at
        - updated_at
    ChannelCreate:
      type: object
      description: >
        Connect a channel. The required fields depend on `channel`:

        * **whatsapp** — `phone_number_id`, plus a credential by
          `credential_source`: `byot` (default) requires `access_token`;
          `embedded_signup` requires `code` and `waba_id`.

        * **discord** — `application_id` and `bot_token` (write-only), plus
          the optional `modes` opting into the gateway flows. Discord runs over
          the Gateway, so the bot token is kept in naturali's encrypted store
          (the worker must present it to authenticate its WebSocket) rather than
          as a secret on the runtime; a deployment that does not enable Discord
          channels returns `501`.

        * **x** — `bot_token`, `consumer_key` and `consumer_secret`
          (write-only); naturali provisions the webhook, the subscription and
          the bot's chat key. Optional `chat_private_keys` with
          `chat_key_version` keep a key already registered.

        No credential value is ever returned. `default` is required
        — connecting a channel without saying
        what it does when nothing else matches is the misconfiguration, so it
        is caught here rather than discovered as silence in production.
      required:
        - default
      properties:
        idempotency_key:
          type: string
          maxLength: 255
          description: >-
            Deduplication key, unique within your account, that makes a retry of
            an ambiguous failure safe. The first request under a key performs the
            write and answers `201`; any later request carrying the same key
            answers `200` with that same result, so a timeout you cannot
            interpret can simply be retried.


            The key is claimed for as long as the record exists and never
            silently expires. Reusing one with a different request body is
            `409 IDEMPOTENCY_KEY_REUSED` — a key names one request, so changing
            the body and keeping the key is a bug rather than a retry. A retry
            that arrives while the original is still in flight is
            `409 IDEMPOTENCY_REQUEST_IN_PROGRESS`.
          example: signup-2026-09-18-acct-42
        default:
          allOf:
            - $ref: '#/components/schemas/ChannelActionInput'
            - required: [action]
        max_context_messages:
          type: integer
          nullable: true
          minimum: 1
          description: >
            The most recent messages each conversation's session sends the
            model, taking precedence over the agent's own
            `max_context_messages`. An open conversation picks a change up on
            its next message. Null defers to the agent.
          example: 20
        channel:
          type: string
          enum: [whatsapp, discord, x]
          default: whatsapp
          example: whatsapp
        phone_number_id:
          type: string
          description: Required for `whatsapp`.
          example: '109999999999999'
        credential_source:
          type: string
          enum: [byot, embedded_signup]
          default: byot
          example: byot
        access_token:
          type: string
          description: >
            Write-only. Required for `byot`. The WhatsApp access token from your
            own Meta app. Accepted on write, never returned.
          example: EAAG...ZDZD
        code:
          type: string
          description: >
            Required for `embedded_signup`. The short-lived authorization code
            from the Meta popup; naturali exchanges it for the access token
            server-side. Never stored or returned. A code Meta rejects
            (malformed, expired or already used) is `400 INVALID_SIGNUP_CODE`.
          example: AQD...abc
        pin:
          type: string
          description: >
            Optional (`embedded_signup` only). The two-step verification PIN
            used if naturali registers the number, which it does only when the
            number is not yet registered for sending. Needed only when the number
            already has one; otherwise naturali generates a PIN and does not keep
            it. Never stored or returned.
          example: '123456'
        waba_id:
          type: string
          description: >
            Required for `embedded_signup`. Optional for `byot`, used only when
            Meta does not report the WABA that owns the number.
          example: '104444444444444'
        application_id:
          type: string
          description: Required for `discord`. The Discord application id.
          example: '1290000000000000000'
        bot_token:
          type: string
          description: >
            Write-only. Required for `discord` and `x`. The bot token, sealed in
            naturali's encrypted store. Accepted on write, never returned.
          example: 'MT2...bot-token'
        modes:
          $ref: '#/components/schemas/DiscordModes'
        consumer_key:
          type: string
          description: >
            Write-only. Required for `x`. The consumer key (API key) of the X
            app that issued the bot. Accepted on write, never returned.
          example: 'xvz1evFS4wEEPTGEFPHBog'
        consumer_secret:
          type: string
          description: >
            Write-only. Required for `x`. The app's consumer secret; X signs
            webhook deliveries with it. Accepted on write, never returned.
          example: 'L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg'
        chat_private_keys:
          type: string
          description: >
            Write-only. Optional for `x`, with `chat_key_version`: the bot's
            exported chat private keys (base64), to keep a key already
            registered instead of registering a new one.
          example: '9eobNZOs...BX+g=='
        chat_key_version:
          type: string
          description: Optional for `x`, with `chat_private_keys`. The registered key's version.
          example: '1794500630168'
    WhatsAppSignupLink:
      type: object
      required:
        - url
        - expires_at
      properties:
        url:
          type: string
          format: uri
          description: The Meta dialog to open. Treat it as a credential.
          example: https://www.facebook.com/v25.0/dialog/oauth?client_id=1234567890
        expires_at:
          type: string
          format: date-time
          example: '2026-10-08T12:30:00Z'
    WhatsAppSignupComplete:
      type: object
      required:
        - pending
        - phone_number_id
      properties:
        pending:
          type: string
          description: The opaque value the result page received.
          example: djE6…
        phone_number_id:
          type: string
          description: One of the numbers the result page listed.
          example: '109999999999999'
    ChannelUpdate:
      type: object
      description: >
        At least one field is required. For WhatsApp, `access_token` rotates the
        write-only credential; for Discord, `bot_token` rotates the sealed bot
        token (checked with Discord as on connect) and `modes` turns the gateway
        flows on or off; for X, `bot_token` rotates the sealed token of the
        same bot. `default` replaces
        the channel's default action whole when present. The worker picks
        either change up on its next poll and reconnects.
      properties:
        default:
          allOf:
            - $ref: '#/components/schemas/ChannelActionInput'
            - required: [action]
        max_context_messages:
          type: integer
          nullable: true
          minimum: 1
          description: >
            The most recent messages each conversation's session sends the
            model, taking precedence over the agent's own
            `max_context_messages`. An open conversation picks a change up on
            its next message. Null defers to the agent.
          example: 20
        access_token:
          type: string
          description: WhatsApp. Write-only. Replaces the stored credential.
          example: EAAG...ZDZD
        waba_id:
          type: string
          example: '104444444444444'
        credential_source:
          type: string
          enum: [byot, embedded_signup]
          example: embedded_signup
        bot_token:
          type: string
          description: Discord or X. Write-only. Rotates the sealed bot token.
          example: 'MT2...bot-token'
        modes:
          $ref: '#/components/schemas/DiscordModes'
        status:
          type: string
          enum: [active, disabled]
          example: disabled
    DiscordModes:
      type: object
      nullable: true
      description: >
        Which Discord Gateway flows this channel serves; null for non-Discord
        channels. At least one must be enabled.

        * `dms` — the bot converses 1:1 in direct messages (the WhatsApp shape).
          Needs only the non-privileged `DIRECT_MESSAGES` intent.

        * `mention_threads` — an @mention in a server opens a thread, and the
          whole thread is one conversation. Reading the follow-up messages in
          the thread needs the **privileged** `MESSAGE_CONTENT` intent, which
          you enable on your own Discord app (Discord requires bot verification
          past ~100 servers), so it is off unless you ask for it.
      properties:
        dms:
          type: boolean
          default: true
          example: true
        mention_threads:
          type: boolean
          default: false
          example: false
    ChannelAction:
      type: object
      description: >
        What an inbound message resolves to — a channel's `default`, a route,
        or an address's own action, one shape on all three. For a Discord
        channel, `config.discord.allowed_role_ids` / `allowed_user_ids`
        restrict who may invoke the agent in a server — either list admits,
        empty or absent lists mean everyone, decided before the agent is
        invoked so an unlisted member costs nothing.
      properties:
        action:
          type: string
          nullable: true
          enum: [agent, oneshot, message, silence, null]
          example: agent
          description: >
            What an inbound message becomes; `null` only on an address with no
            action of its own, which the route table then decides.


            `agent` is a dialogue: the identity behind the message gets a
            session, and every later message on it continues the same one.
            `oneshot` runs the agent once and keeps nothing — no address, no
            actor, no session, no conversation — so each message is answered on
            its own. Choose it for work that is filed rather than discussed;
            choose `agent` when the answer depends on what came before.


            `message` delivers fixed text without running an agent, and
            `silence` answers nothing.
        agent_id:
          type: string
          nullable: true
          description: The agent that answers, when `action` is `agent` or `oneshot`.
          example: agent_V1StGXR8Z5jdHi6B
        text:
          type: string
          nullable: true
          description: The fixed text delivered, when `action` is `message`.
          example: 'Subscribe at https://example.com/pricing'
        repeat:
          description: >
            How often a `message` fires: `every` (default), `once`, or
            `{ after_seconds }`. Null unless `action` is `message`.
          oneOf:
            - type: string
              enum: [every, once]
            - type: object
              nullable: true
              required: [after_seconds]
              properties:
                after_seconds:
                  type: integer
                  minimum: 1
          example: every
        language:
          type: string
          nullable: true
          description: Preferred reply language; null lets the agent decide.
          example: en-US
        config:
          type: object
          nullable: true
          additionalProperties: true
          description: >
            Conversation config bag — media handling, persona overrides, the
            Discord allowlist, and how a `oneshot` answers.


            `discord.reply` picks the delivery: `react` (the default) adds
            `discord.reaction` — `\u2705` unless named — to the message that
            triggered the run, `mention` answers beside it addressing whoever
            asked, `react_or_mention` reacts when the agent writes nothing and
            answers like `mention` when it writes a line, `thread` opens a
            thread and answers inside it, and `none` delivers nothing at all.
            A run that fails delivers nothing in every mode, so a reaction
            always means the work was done; there is no failure marker.


            A mention with nothing else in it is ignored unless the action
            says otherwise, for any action. `discord.use_replied_message:
            true` takes the text of the message it replies to, so replying to
            a message with only the mention files that message.
            `discord.empty_mention_text` answers any other bare mention with
            that fixed text, addressing the sender, without running the agent.


            `discord.forward_user_id: true` hands the sender's Discord user id
            to the agent's tools as the `discord_user_id` tool context, which
            a tool's `headers` read as `{{context:discord_user_id}}`. It is
            the id Discord reported for the message's author, never text the
            model wrote, so a tool can act for whoever sent it. Off unless
            set, because tool context reaches every tool the agent has.


            Read only for `oneshot`. A conversational `agent` in a guild *is*
            its thread — that is what its session is keyed on — so it always
            opens one.
          example:
            media:
              audio: transcribe
            discord:
              allowed_role_ids: ['1290000000000000042']
      required:
        - action
        - agent_id
        - text
        - repeat
        - language
        - config
    ChannelActionInput:
      type: object
      description: >
        `agent_id` is required when `action` is `agent` or `oneshot`, `text`
        when it is `message`; `repeat` is only valid alongside
        `action: message`.
      properties:
        action:
          type: string
          nullable: true
          enum: [agent, oneshot, message, silence, null]
          example: agent
          description: >
            What an inbound message becomes; `null` clears an address's own
            action, and is refused for a channel default or a route.


            `agent` is a dialogue: the identity behind the message gets a
            session, and every later message on it continues the same one.
            `oneshot` runs the agent once and keeps nothing — no address, no
            actor, no session, no conversation — so each message is answered on
            its own. Choose it for work that is filed rather than discussed;
            choose `agent` when the answer depends on what came before.


            `message` delivers fixed text without running an agent, and
            `silence` answers nothing.
        agent_id:
          type: string
          example: agent_V1StGXR8Z5jdHi6B
        text:
          type: string
          example: 'Subscribe at https://example.com/pricing'
        repeat:
          oneOf:
            - type: string
              enum: [every, once]
            - type: object
              required: [after_seconds]
              properties:
                after_seconds:
                  type: integer
                  minimum: 1
          example: every
        language:
          type: string
          example: en-US
        config:
          type: object
          nullable: true
          additionalProperties: true
          description: >
            Conversation config bag — media handling, persona overrides, the
            Discord allowlist, and how a `oneshot` answers.


            `discord.reply` picks the delivery: `react` (the default) adds
            `discord.reaction` — `\u2705` unless named — to the message that
            triggered the run, `mention` answers beside it addressing whoever
            asked, `react_or_mention` reacts when the agent writes nothing and
            answers like `mention` when it writes a line, `thread` opens a
            thread and answers inside it, and `none` delivers nothing at all.
            A run that fails delivers nothing in every mode, so a reaction
            always means the work was done; there is no failure marker.


            A mention with nothing else in it is ignored unless the action
            says otherwise, for any action. `discord.use_replied_message:
            true` takes the text of the message it replies to, so replying to
            a message with only the mention files that message.
            `discord.empty_mention_text` answers any other bare mention with
            that fixed text, addressing the sender, without running the agent.


            `discord.forward_user_id: true` hands the sender's Discord user id
            to the agent's tools as the `discord_user_id` tool context, which
            a tool's `headers` read as `{{context:discord_user_id}}`. It is
            the id Discord reported for the message's author, never text the
            model wrote, so a tool can act for whoever sent it. Off unless
            set, because tool context reaches every tool the agent has.


            Read only for `oneshot`. A conversational `agent` in a guild *is*
            its thread — that is what its session is keyed on — so it always
            opens one.
    Conversation:
      type: object
      description: >
        An address's dialogue on a channel — naturali-native, keyed by
        (channel, address) so the same identifier never opens two
        conversations, and mapped 1:1 to the runtime session that carries the
        message history.
      required:
        [
          id,
          project_id,
          channel_id,
          address_id,
          route_id,
          identifier,
          actor_id,
          session_id,
          created_at,
          updated_at,
        ]
      properties:
        id:
          type: string
          example: conv_V1StGXR8Z5jdHi6B
        project_id:
          type: string
          example: proj_V1StGXR8Z5jdHi6B
        channel_id:
          type: string
          example: chan_V1StGXR8Z5jdHi6B
        address_id:
          type: string
          description: >
            The address the dialogue arrived at — the continuity key.
          example: addr_V1StGXR8Z5jdHi6B
        route_id:
          type: string
          description: >
            The route this conversation's action came from — a real route id,
            or one of the two sentinels for "the address's own action" /
            "the channel default". A message
            resolving to a different action opens a new conversation rather
            than re-pointing this one.
          example: route_V1StGXR8Z5jdHi6B
        identifier:
          type: string
          nullable: true
          description: >
            The prefixed, self-describing channel identifier (`whatsapp:dm:…`,
            `discord:dm:…`, `discord:thread:…`). Read through from the address
            above.
          example: 'whatsapp:dm:425678901234567890'
        actor_id:
          type: string
          nullable: true
          description: >
            The runtime actor the address speaks as. Null when the address has
            not needed one yet.
          example: actor_V1StGXR8Z5jdHi6B
        session_id:
          type: string
          description: The runtime session this conversation maps 1:1 to.
          example: sess_V1StGXR8Z5jdHi6B
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    ConversationMessage:
      type: object
      description: One message in the conversation's transcript, as the runtime records it.
      properties:
        id:
          type: string
          nullable: true
          description: The message's id — the document holding its text.
        role:
          type: string
          nullable: true
          enum: [user, assistant, system, null]
          example: user
        content:
          type: string
          nullable: true
          example: como isso difere de uma orquestração?
        position:
          type: integer
          nullable: true
          description: Zero-based position in the conversation.
          example: 0
        actor_id:
          type: string
          nullable: true
          description: The actor who authored the message, when set.
        agent_id:
          type: string
          nullable: true
          description: The agent that produced the message, for assistant turns.
        metadata:
          type: object
          nullable: true
          additionalProperties: true
        provider_message_id:
          type: string
          nullable: true
          description: >
            The channel provider's id for an inbound message — the
            `provider_message_id` its `messages.received` event carried. Null
            for a reply.
          example: wamid.HBgLNTUxMTk4
