openapi: 3.1.0
info:
  title: PagerMail API
  version: 0.5.0
  description: |
    Agent-native communication infrastructure API.
    Authenticated endpoints are served under `/api`. Hosted dashboard sessions use
    Clerk session cookies on the same origin, while programmatic API clients use
    API keys unless a path is explicitly marked as public.

    Self-serve onboarding is live through one audited provisioner behind an
    unauthenticated agent REST door and a Clerk-authenticated human door.
    `GET /signup` returns `204` while the production door and provisioner are
    ready. Deployments with `SIGNUP_ENABLED=false` omit `/signup`,
    `/signup/verify`, `/signup/resend`, and `/signup/human` behind the canonical HTTP 404 route
    contract. The signed Clerk identity-sync webhook remains available to keep
    existing identity records current.

    This spec covers the **canonical public API surface**. Unknown `/api/*`
    method/path combinations return HTTP 404 with the `RouteNotFoundError`
    schema and never fall through to the dashboard shell.
  contact:
    name: PagerMail

servers:
  - url: https://api.pager.ai/api
    description: Production
  - url: http://localhost:3100/api
    description: Local development

security:
  - ApiKeyAuth: []

components:
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: API key in format `Bearer pm_live_...`
    AgentKeyAuth:
      type: http
      scheme: bearer
      description: Agent-bound API key in format `Bearer pm_agent_...`
    ClerkSessionAuth:
      type: apiKey
      in: cookie
      name: __session
      description: Same-origin Clerk production session used by the hosted dashboard.
  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
        code:
          type: string
          description: Stable machine-readable code when the error class defines one.
        resource_id:
          type: string
          format: uuid
          description: Committed resource associated with a recoverable idempotency state, when known.

    AgentScopeForbiddenError:
      type: object
      additionalProperties: false
      required: [error, code, required_scopes]
      properties:
        error:
          type: string
          const: Agent key lacks required scope
        code:
          type: string
          const: AGENT_SCOPE_FORBIDDEN
        required_scopes:
          type: array
          minItems: 1
          maxItems: 2
          uniqueItems: true
          items:
            type: string
            enum: [mail:read, mail:send]

    InternalServerError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Internal server error
        code:
          type: string
          const: INTERNAL_SERVER_ERROR

    IdempotencyReplayIntegrityError:
      type: object
      additionalProperties: false
      required: [error, code]
      description: |
        A completed send-class idempotency record stores a content-free
        `outbound-reference-v1` skeleton and digest. Replay rebuilds the
        response from immutable acceptance records; if any source is missing,
        foreign or altered the replay fails closed with no content, the key
        stays completed and nothing is re-executed.
      properties:
        error:
          type: string
          const: The stored idempotent result could not be verified
        code:
          type: string
          const: IDEMPOTENCY_REPLAY_INTEGRITY

    OriginalMimeIntegrityError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Stored original MIME failed integrity verification
        code:
          type: string
          const: ORIGINAL_MIME_INTEGRITY_ERROR

    ServiceUnavailableError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Realtime service unavailable
        code:
          type: string
          const: SERVICE_UNAVAILABLE

    WebhookEgressPausedError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Customer webhook egress is paused
        code:
          type: string
          const: WEBHOOK_EGRESS_PAUSED

    UserSendsPausedError:
      type: object
      additionalProperties: false
      required: [error, code]
      description: The operator has paused new user sends. Nothing was sent; retrying the same request cannot succeed until the pause is lifted.
      properties:
        error:
          type: string
          const: Sending is paused; try again later
        code:
          type: string
          const: USER_SENDS_PAUSED

    RecipientCapExceededError:
      type: object
      additionalProperties: false
      required: [error, code, limit]
      description: The message has more external recipients than the organization's per-message cap. Nothing was sent; retrying the same request cannot succeed.
      properties:
        error:
          type: string
        code:
          type: string
          const: RECIPIENT_CAP_EXCEEDED
        limit:
          type: integer
          minimum: 1
          maximum: 20

    WebhookApplicationNotFoundError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Webhook application not found
        code:
          type: string
          const: WEBHOOK_APPLICATION_NOT_FOUND

    IdempotencyError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error: { type: string }
        code:
          type: string
          enum:
            - INVALID_IDEMPOTENCY_KEY
            - IDEMPOTENCY_CONFLICT
            - IDEMPOTENCY_IN_PROGRESS
        resource_id:
          type: string
          format: uuid

    RouteNotFoundError:
      type: object
      additionalProperties: false
      required: [name, code, message, fix, docs]
      properties:
        name:
          type: string
          const: RouteNotFoundError
        code:
          type: string
          const: route_not_found
        message:
          type: string
          const: The requested API route does not exist.
        fix:
          type: string
          const: Check the HTTP method and path against the API reference.
        docs:
          type: string
          const: /docs

    ValidationError:
      type: object
      required: [error, details]
      properties:
        error:
          type: string
        details:
          type: array
          items:
            type: object
            properties:
              field:
                type: string
              message:
                type: string

    MalformedJsonError:
      type: object
      additionalProperties: false
      required: [error]
      properties:
        error:
          type: string
          const: Invalid JSON in request body

    JsonBodyTooLargeError:
      type: object
      additionalProperties: false
      required: [error]
      properties:
        error:
          type: string
          const: Request body exceeds 1048576 bytes

    AgentSignupRequest:
      type: object
      additionalProperties: false
      required: [human_email, agent_name, username]
      properties:
        human_email:
          type: string
          minLength: 1
          maxLength: 1024
          description: |
            Opaque human-owner address candidate. Eligibility is evaluated
            behind the uniform response boundary; structurally valid blocked
            and already-known values deliberately receive the same response.
        agent_name:
          type: string
          minLength: 3
          maxLength: 30
          pattern: "^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])$"
          description: |
            3–30 lowercase ASCII letters or digits, with hyphens allowed only internally (no leading or trailing hyphen).
        username:
          type: string
          minLength: 3
          maxLength: 30
          pattern: "^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])$"
          description: |
            Requested local part for `username@in.pagermail.ai`. 3–30 lowercase ASCII letters or digits, with hyphens allowed only internally (no leading or trailing hyphen).

    AgentSignupChallengeResponse:
      type: object
      additionalProperties: false
      required: [verification_handle, status, message]
      properties:
        verification_handle:
          type: string
          minLength: 32
          maxLength: 512
          description: |
            Opaque, short-lived verification handle. It is not a credential and
            conveys no identity, dispatch, eligibility, or challenge-state result.
        status:
          type: string
          const: accepted
        message:
          type: string
          const: Request accepted. If eligible, check the address for a verification code.

    AgentSignupProvisionalResponse:
      type: object
      additionalProperties: false
      required: [verification_handle, status, agent_key, address, message]
      properties:
        verification_handle:
          type: string
          pattern: "^pm_signup_[A-Za-z0-9_-]{43}$"
          description: Opaque handle used to upgrade this same provisional agent after OTP proof.
        status:
          type: string
          const: provisional
        agent_key:
          type: string
          pattern: "^pm_agent_[A-Za-z0-9_-]{43}$"
          description: |
            Read-only credential for the newly created trust-zero agent. Until
            verification it has exactly `mail:read`; every send is denied. Its
            inbox can accept at most five storage attempts and 20 MiB of
            reserved input/raw bytes. PagerMail's OTP email uses this persisted
            inbox address as Reply-To so the human can reply directly with the
            code. Expired provisional agents are also blocked from new inbound
            storage.
        address:
          type: string
          format: email
          description: The provisional agent's PagerMail inbox address.
        message:
          type: string
          const: "Provisional agent created. Store agent_key and verification_handle NOW — this start response is shown exactly once. Until verification, agent_key is read-only and cannot send mail. PagerMail's verification email asks the human to reply directly with the code to your provisional inbox. Next: use agent_key to list your inbox, read that reply, then POST the code with verification_handle to /api/signup/verify if a code was issued. If no code arrives or it expires, wait 60 seconds and POST the same verification_handle and human_email to /api/signup/resend with this agent_key."

    SignupUsernameUnavailableError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Username unavailable
        code:
          type: string
          const: SIGNUP_USERNAME_UNAVAILABLE

    SignupVerifyRequest:
      type: object
      additionalProperties: false
      required: [verification_handle, otp]
      properties:
        verification_handle:
          type: string
          minLength: 32
          maxLength: 512
        otp:
          type: string
          pattern: "^[0-9]{6}$"

    SignupVerifiedResponse:
      type: object
      additionalProperties: false
      required: [status, agent_key, address, instructions]
      properties:
        status:
          type: string
          const: verified
        agent_key:
          type: string
          pattern: "^pm_agent_[A-Za-z0-9_-]{43}$"
          description: |
            With challenge-first signup, this is the single credential minted
            after proof. With provisional-first signup, this is the same
            handle-derived credential returned at start; verification restores
            its exact `mail:read` and `mail:send` scopes without creating or
            rotating a key. The successful call consumes the proof handle in
            either mode.
        address:
          type: string
          format: email
          description: The verified agent's new PagerMail inbox address.
        instructions:
          type: string
          const: "Store agent_key securely. You can now authenticate with it to list inboxes (GET /api/inboxes), read messages (GET /api/inboxes/{inboxId}/messages), and send mail (POST /api/messages/send)."
          description: Immediate authenticated next steps for the verified agent.

    SignupVerificationFailedError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Signup verification failed
        code:
          type: string
          const: SIGNUP_VERIFICATION_FAILED

    SignupResendRequest:
      type: object
      additionalProperties: false
      required: [verification_handle, human_email]
      properties:
        verification_handle:
          type: string
          pattern: "^pm_signup_[A-Za-z0-9_-]{43}$"
          description: The unchanged handle returned with this provisional agent.
        human_email:
          type: string
          minLength: 1
          maxLength: 1024
          description: |
            The same human-owner address supplied at start. If detached initial
            admission created no challenge, the first eligible resend binds this
            normalized address permanently.

    SignupOtpResentResponse:
      type: object
      additionalProperties: false
      required: [status, code, message]
      properties:
        status:
          type: string
          const: resent
        code:
          type: string
          const: SIGNUP_OTP_RESENT
        message:
          type: string
          const: "A new verification code was sent to your human owner. Ask them to reply directly to that email, read the newest code from your provisional inbox, then verify it with the same verification_handle at /api/signup/verify."

    SignupResendRateLimitedError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Verification code resend is rate limited
        code:
          type: string
          const: SIGNUP_RESEND_RATE_LIMITED
        retry_after_seconds:
          type: integer
          minimum: 1
          maximum: 86400
          description: Present only when the 60-second issue cooldown supplies a truthful retry interval.

    ApiRequestRateLimitedError:
      type: object
      additionalProperties: false
      required: [error]
      properties:
        error:
          type: string
          enum:
            - Too many requests, please try again later
            - Organization API rate limit exceeded
            - Agent API rate limit exceeded
          description: Request-level throttle that may run before the resend handler.

    SignupNotResendableError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: This provisional signup cannot resend a verification code
        code:
          type: string
          const: SIGNUP_NOT_RESENDABLE

    SignupResendAgentKeyRequiredError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: A provisional agent key is required
        code:
          type: string
          const: SIGNUP_RESEND_AGENT_KEY_REQUIRED

    SignupResendDeliveryUnavailableError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Verification code delivery is unavailable
        code:
          type: string
          const: SIGNUP_RESEND_DELIVERY_UNAVAILABLE

    SignupEmailNotVerifiedError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: A verified email address is required
        code:
          type: string
          const: SIGNUP_EMAIL_NOT_VERIFIED

    SignupIdentityConflictError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Identity cannot be linked
        code:
          type: string
          const: SIGNUP_IDENTITY_CONFLICT

    SignupIdentityRegistryUnavailableError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: Identity synchronization unavailable
        code:
          type: string
          const: SIGNUP_IDENTITY_REGISTRY_UNAVAILABLE

    ProvisionalSendRestrictedError:
      type: object
      additionalProperties: false
      required: [error, code]
      properties:
        error:
          type: string
          const: This provisional agent is not authorized for this recipient set
        code:
          type: string
          const: PROVISIONAL_SEND_RESTRICTED

    HumanSignupResponse:
      type: object
      additionalProperties: false
      required: [status, clerk_organization_id]
      properties:
        status:
          type: string
          const: ready
        clerk_organization_id:
          type: string
          minLength: 1

    PaginationCursorFields:
      type: object
      required: [next_page_token, has_more]
      properties:
        next_page_token:
          type: ["string", "null"]
        has_more:
          type: boolean

    Organization:
      type: object
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        slug: { type: string }
        status: { type: string }
        metadata:
          type: object
          additionalProperties: true
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    Workspace:
      type: object
      properties:
        id: { type: string, format: uuid }
        org_id: { type: string, format: uuid }
        slug: { type: string }
        name: { type: string }
        description:
          type: ["string", "null"]
        metadata:
          type: object
          additionalProperties: true
        status: { type: string }
        is_default: { type: boolean }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    Agent:
      type: object
      required:
        [id, org_id, workspace_id, name, type, capabilities, trust_score,
         status, metadata, created_at]
      properties:
        id: { type: string, format: uuid }
        org_id: { type: string, format: uuid }
        workspace_id: { type: string, format: uuid }
        name: { type: string }
        type: { type: string }
        capabilities:
          type: array
          items: {}
        trust_score: { type: integer }
        status: { type: string }
        metadata:
          type: object
          additionalProperties: true
        created_at: { type: string, format: date-time }

    Inbox:
      type: object
      required:
        [id, agent_id, org_id, workspace_id, email, address_kind, domain_id,
         local_part, display_name, features, status, created_at]
      properties:
        id: { type: string, format: uuid }
        agent_id: { type: string, format: uuid }
        org_id: { type: string, format: uuid }
        workspace_id: { type: string, format: uuid }
        email:
          type: string
          format: email
          description: |
            Reserved inbox identity: either a PagerMail platform address or a
            chosen local part on an organization-owned verified custom domain.
            Reserving a custom identity does not by itself enable inbound
            delivery or custom-domain sending.
        address_kind:
          type: string
          enum: [legacy_random, signup_username, custom_domain]
          description: Persisted provenance for the reserved inbox identity.
        domain_id:
          type: ["string", "null"]
          format: uuid
          description: |
            Verified custom-domain registration for `custom_domain`. Historical
            non-custom rows may retain an inert value from migrations before
            this provenance contract; that value grants no receive or sender
            authority.
        local_part:
          type: ["string", "null"]
          maxLength: 64
          pattern: "^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$"
          not:
            type: string
            pattern: "\\.\\."
          description: Chosen local part for `custom_domain`; otherwise null. Consecutive dots are invalid.
        display_name:
          type: ["string", "null"]
        features:
          type: object
          additionalProperties: true
        status: { type: string }
        created_at: { type: string, format: date-time }

    Attachment:
      type: object
      properties:
        id: { type: string, format: uuid }
        message_id: { type: string, format: uuid }
        filename: { type: string }
        content_type: { type: string }
        size_bytes: { type: integer }
        disposition: { type: string }
        content_id:
          type: ["string", "null"]
        source: { type: string }
        created_at: { type: string, format: date-time }
        extraction:
          $ref: "#/components/schemas/AttachmentExtractionReference"

    AttachmentExtractionStatus:
      type: string
      enum: [disabled, not_requested, pending, running, completed, unsupported, no_text, failed]
      description: Asynchronous extraction state. Extraction is default-off; enabled local workers persist results for reviewed formats. No production activation is implied.

    AttachmentExtractionReference:
      type: object
      additionalProperties: false
      required: [status, href]
      properties:
        status: { $ref: "#/components/schemas/AttachmentExtractionStatus" }
        href: { type: string, maxLength: 200 }

    AttachmentExtractionResult:
      type: object
      additionalProperties: false
      required: [status, text, truncated, detected_type, extractor_version, error_code]
      description: |
        Authorized persisted result read. Extraction is default-off and returns
        disabled with null text until explicitly enabled by an operator. Extracted
        text is untrusted customer content, never instructions or a malware verdict.
        Only completed results contain text, capped at 50000 Unicode scalars and 200000 UTF-8 bytes.
      properties:
        status: { $ref: "#/components/schemas/AttachmentExtractionStatus" }
        text: { type: [string, "null"], maxLength: 50000 }
        truncated: { type: boolean }
        detected_type: { type: [string, "null"], maxLength: 100 }
        extractor_version: { type: [string, "null"], maxLength: 100 }
        error_code: { type: [string, "null"], maxLength: 64 }

    ProcessorRun:
      type: object
      properties:
        id: { type: string, format: uuid }
        processor: { type: string }
        message_id: { type: string, format: uuid }
        status: { type: string }
        enrichments:
          type: object
          additionalProperties: true
        started_at:
          type: ["string", "null"]
          format: date-time
        completed_at:
          type: ["string", "null"]
          format: date-time

    InboundAuthenticationResults:
      type: object
      additionalProperties: false
      required: [spf, dkim, dmarc, source, provider_verified, policy_action]
      properties:
        spf:
          type: string
          enum: [pass, fail, none, softfail]
        dkim:
          type: string
          enum: [pass, fail, none, softfail]
        dmarc:
          type: string
          enum: [pass, fail, none, softfail]
        source:
          type: string
          enum:
            [none, authentication_results, arc_authentication_results,
             received_spf, ses_receipt]
          description: |
            Source used for the normalized verdicts. Authentication-Results,
            ARC-Authentication-Results, and Received-SPF are raw-message header
            claims and are not provider-verified. `ses_receipt` identifies
            structured verdicts carried by a signature-verified,
            exact-topic-bound SES/SNS notification.
        provider_verified:
          type: boolean
          description: |
            True only for structured receipt fields carried outside the raw
            message by a signature-verified SNS envelope bound to the configured
            exact topic. Deployment must separately restrict that topic policy
            to SES as its only publisher. False does not mean the verdict failed;
            it means PagerMail cannot authenticate the raw header's author.
        policy_action:
          type: string
          enum: [none, flag, quarantine]
          description: |
            Advisory action snapshotted during ingestion. In this slice,
            quarantine adds a label only: mail remains stored and readable,
            attachments remain downloadable, and no mail is rejected or dropped.

    Message:
      type: object
      required:
        [id, thread_id, inbox_id, message_id, from_addr, to_addrs, cc_addrs,
         reply_to, custom_headers, subject, body_text, body_html,
         extracted_text, extracted_html, structured_payload, labels,
         in_reply_to, references, route_type, sender_trust_tier_at_send, received_at]
      properties:
        id: { type: string, format: uuid }
        thread_id: { type: string, format: uuid }
        inbox_id: { type: string, format: uuid }
        message_id:
          type: ["string", "null"]
        from_addr: { type: string }
        to_addrs:
          type: array
          items: { type: string }
        cc_addrs:
          type: array
          items: { type: string }
        reply_to:
          type: ["string", "null"]
          format: email
        custom_headers:
          type: object
          description: Validated customer X-* headers.
          additionalProperties: { type: string }
        subject:
          type: ["string", "null"]
        body_text:
          type: ["string", "null"]
        body_html:
          type: ["string", "null"]
        extracted_text:
          type: ["string", "null"]
        extracted_html:
          type: ["string", "null"]
        structured_payload:
          type: ["object", "null"]
          additionalProperties: true
        labels:
          type: array
          items: { type: string }
        in_reply_to:
          type: ["string", "null"]
        references:
          type: ["array", "null"]
          items: { type: string }
        route_type:
          type: string
          description: |
            Current sends use `internal_same_org` or `external_email`. Historical
            rows may retain a retired value until additive data reconciliation is
            approved and complete.
        sender_trust_tier_at_send:
          type: ["string", "null"]
          enum: [new, verified, trusted, enterprise, null]
          description: |
            Immutable sending-agent tier captured when a send-class operation
            accepts the message. Null means no snapshot was recorded, including
            rows that predate migration 026 and unsent/inbound messages. Clients
            must preserve null as unknown and must not substitute the current tier.
        received_at: { type: string, format: date-time }

    EnrichedMessage:
      allOf:
        - $ref: "#/components/schemas/Message"
        - type: object
          required: [authentication_results]
          properties:
            authentication_results:
              $ref: "#/components/schemas/InboundAuthenticationResults"
            attachments:
              type: array
              items:
                $ref: "#/components/schemas/Attachment"
            processor_runs:
              type: array
              items:
                $ref: "#/components/schemas/ProcessorRun"

    Thread:
      type: object
      properties:
        id: { type: string, format: uuid }
        org_id: { type: string, format: uuid }
        workspace_id: { type: string, format: uuid }
        subject:
          type: ["string", "null"]
        preview:
          type: ["string", "null"]
        created_at: { type: string, format: date-time }
        last_message_at: { type: string, format: date-time }

    ThreadWithMessages:
      allOf:
        - $ref: "#/components/schemas/Thread"
        - type: object
          properties:
            messages:
              type: array
              items:
                $ref: "#/components/schemas/Message"

    ThreadContextMessage:
      type: object
      additionalProperties: false
      required: [id, from_addr, subject, snippet, received_at]
      properties:
        id:
          type: string
          format: uuid
        from_addr:
          type: string
          description: Sender address recorded on the message.
        subject:
          type: ["string", "null"]
        snippet:
          type: string
          maxLength: 200
          description: At most the first 200 characters of the message's text body.
        received_at:
          type: string
          format: date-time

    ThreadContext:
      type: object
      additionalProperties: false
      required: [thread_id, context_summary, last_n_messages, fetch_reference]
      properties:
        thread_id:
          type: string
          format: uuid
        context_summary:
          type: string
          description: |
            Deterministic, extractive structural digest over the full non-trash message set
            visible through the caller's organization, workspace, and agent inbox grant. Its
            exact fields are the subject of the message ordered last by `received_at` and then
            `id` (`(no subject)` when null), the full visible non-trash message count,
            lexicographically sorted distinct sender (`from_addr`) addresses, and the inclusive
            UTC calendar-date span from minimum to maximum `received_at`. The format is
            `Subject '<subject>' · N message(s) · participant1, participant2 · YYYY-MM-DD→YYYY-MM-DD`,
            with singular `message` only when N is 1. This is not an AI or abstractive
            summary and does not claim to interpret message contents.
          example: "Subject 'Invoice #42' · 4 messages · alice@x.com, bob@y.com · 2026-08-02→2026-08-11"
        last_n_messages:
          type: array
          minItems: 1
          maxItems: 20
          description: |
            The most recent bounded non-trash message window, ordered by `received_at` and then
            `id`, ascending (oldest to newest) within that window. Only messages visible through
            the caller's organization, workspace, and agent inbox grant are included.
          items:
            $ref: "#/components/schemas/ThreadContextMessage"
        fetch_reference:
          type: string
          format: uri
          description: Absolute URL for fetching the caller-accessible thread resource.

    Delivery:
      type: object
      required:
        [id, message_id, recipient, route_type, idempotency_key, route_reason,
         outbound_dispatch_id, recipient_role, status, provider, provider_id,
         error, bounce_type, complaint_type, attempt_count, max_attempts,
         next_attempt_at, last_attempt_at, processing_started_at,
         delivery_state, accepted_at, delivered_at, created_at]
      properties:
        id: { type: string, format: uuid }
        message_id: { type: string, format: uuid }
        recipient: { type: string }
        route_type: { type: string }
        route_reason:
          type: ["string", "null"]
        recipient_role:
          type: string
          description: Public delivery resources represent visible To or Cc recipients only.
          enum: [to, cc]
        outbound_dispatch_id:
          type: ["string", "null"]
          format: uuid
        idempotency_key:
          type: ["string", "null"]
        status:
          type: string
          description: Legacy queue compatibility status. Use delivery_state for provider truth.
        delivery_state:
          type: string
          description: Honest delivery projection; provider acceptance is distinct from confirmed delivery.
          enum: [queued, processing, accepted, deferred, delivered, bounced, failed, rejected, complained]
        provider:
          type: ["string", "null"]
        provider_id:
          type: ["string", "null"]
        error:
          type: ["string", "null"]
        bounce_type:
          type: ["string", "null"]
        complaint_type:
          type: ["string", "null"]
        attempt_count:
          type: integer
          minimum: 0
        max_attempts:
          type: integer
          minimum: 1
        next_attempt_at:
          type: string
          format: date-time
        last_attempt_at:
          type: ["string", "null"]
          format: date-time
        processing_started_at:
          type: ["string", "null"]
          format: date-time
        accepted_at:
          type: ["string", "null"]
          format: date-time
          description: Time the external provider accepted the dispatch; not proof of delivery.
        delivered_at:
          type: ["string", "null"]
          format: date-time
          description: Time supported by a committed internal delivery or true provider delivered fact.
        created_at: { type: string, format: date-time }

    AgentListResponse:
      allOf:
        - $ref: "#/components/schemas/PaginationCursorFields"
        - type: object
          required: [items]
          properties:
            items:
              type: array
              items: { $ref: "#/components/schemas/Agent" }

    InboxListResponse:
      allOf:
        - $ref: "#/components/schemas/PaginationCursorFields"
        - type: object
          required: [items]
          properties:
            items:
              type: array
              items: { $ref: "#/components/schemas/Inbox" }

    MessageListResponse:
      allOf:
        - $ref: "#/components/schemas/PaginationCursorFields"
        - type: object
          required: [items]
          properties:
            items:
              type: array
              items: { $ref: "#/components/schemas/Message" }

    ThreadListResponse:
      allOf:
        - $ref: "#/components/schemas/PaginationCursorFields"
        - type: object
          required: [items]
          properties:
            items:
              type: array
              items: { $ref: "#/components/schemas/Thread" }

    DeliveryListResponse:
      allOf:
        - $ref: "#/components/schemas/PaginationCursorFields"
        - type: object
          required: [items]
          properties:
            items:
              type: array
              items: { $ref: "#/components/schemas/Delivery" }

    ApiKey:
      type: object
      properties:
        id: { type: string, format: uuid }
        workspace_id:
          type: ["string", "null"]
          format: uuid
        key_prefix: { type: string }
        name: { type: string }
        scopes:
          type: array
          items: { type: string }
        status: { type: string, enum: [active, revoked] }
        last_used_at:
          type: ["string", "null"]
          format: date-time
        created_at: { type: string, format: date-time }

    AgentKeyScope:
      type: string
      enum: [mail:read, mail:send]

    AgentInboxScope:
      type: object
      additionalProperties: false
      required: [mode, inbox_ids]
      properties:
        mode:
          type: string
          enum: [all, selected]
        inbox_ids:
          type: array
          items: { type: string, format: uuid }

    AgentApiKey:
      type: object
      required:
        [id, org_id, workspace_id, agent_id, key_prefix, name, scopes,
         inbox_scope, status, expires_at, last_used_at, created_at, revoked_at]
      properties:
        id: { type: string, format: uuid }
        org_id: { type: string, format: uuid }
        workspace_id: { type: string, format: uuid }
        agent_id: { type: string, format: uuid }
        key_prefix: { type: string, pattern: "^pm_agent_[A-Za-z0-9_-]{8}$" }
        name: { type: string, minLength: 1, maxLength: 255 }
        scopes:
          type: array
          minItems: 1
          maxItems: 2
          uniqueItems: true
          items:
            $ref: "#/components/schemas/AgentKeyScope"
        inbox_scope:
          $ref: "#/components/schemas/AgentInboxScope"
        status:
          type: string
          enum: [active, expired, revoked]
        expires_at: { type: string, format: date-time }
        last_used_at:
          type: [string, "null"]
          format: date-time
        created_at: { type: string, format: date-time }
        revoked_at:
          type: [string, "null"]
          format: date-time

    AgentApiKeyCreateResponse:
      allOf:
        - $ref: "#/components/schemas/AgentApiKey"
        - type: object
          required: [key, prefix, warning]
          properties:
            key:
              type: string
              pattern: "^pm_agent_[A-Za-z0-9_-]{43}$"
            prefix:
              type: string
              pattern: "^pm_agent_[A-Za-z0-9_-]{8}$"
            warning: { type: string }

    OrganizationSession:
      type: object
      required: [auth_type, org_id, api_key_id, workspace_id, actor, workspaces, organization]
      properties:
        auth_type:
          type: string
          enum: [api_key, clerk_session]
        org_id: { type: string, format: uuid }
        api_key_id:
          type: ["string", "null"]
          format: uuid
        api_key_scopes:
          type: array
          items: { type: string }
        workspace_id:
          type: ["string", "null"]
          format: uuid
        actor:
          type: object
          properties:
            type:
              type: string
              enum: [api_key, clerk_user]
            api_key_id:
              type: ["string", "null"]
              format: uuid
            clerk_user_id:
              type: ["string", "null"]
            clerk_organization_id:
              type: ["string", "null"]
            clerk_organization_role:
              type: ["string", "null"]
        workspaces:
          type: array
          items:
            $ref: "#/components/schemas/Workspace"
        organization:
          $ref: "#/components/schemas/Organization"

    AgentKeySession:
      type: object
      additionalProperties: false
      required:
        [auth_type, org_id, agent_key_id, agent_id, workspace_id, scopes,
         inbox_scope]
      properties:
        auth_type:
          type: string
          const: agent_key
        org_id: { type: string, format: uuid }
        agent_key_id: { type: string, format: uuid }
        agent_id: { type: string, format: uuid }
        workspace_id: { type: string, format: uuid }
        scopes:
          type: array
          minItems: 1
          maxItems: 2
          uniqueItems: true
          items:
            $ref: "#/components/schemas/AgentKeyScope"
        inbox_scope:
          type: object
          additionalProperties: false
          required: [mode]
          properties:
            mode:
              type: string
              enum: [all, selected]
            inbox_ids:
              type: array
              minItems: 1
              items: { type: string, format: uuid }

    Session:
      oneOf:
        - $ref: "#/components/schemas/OrganizationSession"
        - $ref: "#/components/schemas/AgentKeySession"

    SendResponse:
      type: object
      required: [message, deliveries, routing, status]
      properties:
        message:
          $ref: "#/components/schemas/Message"
        attachments:
          type: array
          items:
            $ref: "#/components/schemas/Attachment"
        deliveries:
          type: array
          description: Delivery records for visible To and Cc recipients; Bcc deliveries are omitted.
          items:
            $ref: "#/components/schemas/Delivery"
        routing:
          type: array
          description: Routing outcomes for visible To and Cc recipients; Bcc outcomes are omitted.
          items:
            type: object
            required: [recipient, route_type, status]
            properties:
              recipient: { type: string }
              route_type:
                type: string
                enum: [internal_same_org, external_email]
              status:
                type: string
                enum: [queued, failed]
              provider: { type: string }
              error: { type: string }
        status:
          type: string
          enum: [queued]

    IngestResult:
      type: object
      properties:
        thread_id: { type: string, format: uuid }
        message_id: { type: string, format: uuid }
        inbox_id: { type: string, format: uuid }
        created: { type: boolean }

    InboundMimeAcceptance:
      type: object
      additionalProperties: false
      required: [accepted, status, quarantine_id, message_id]
      properties:
        accepted:
          type: boolean
          const: true
        status:
          type: string
          enum: [pending_parse, processed]
        quarantine_id: { type: string, format: uuid }
        message_id:
          type: ["string", "null"]
          format: uuid

    InboundMimeQuarantine:
      type: object
      additionalProperties: false
      required:
        - id
        - inbox_id
        - envelope_recipient
        - provider_message_id
        - raw_size_bytes
        - raw_sha256
        - error_code
        - error_message
        - attempt_count
        - first_seen_at
        - last_seen_at
      properties:
        id: { type: string, format: uuid }
        inbox_id: { type: string, format: uuid }
        envelope_recipient: { type: string, format: email }
        provider_message_id: { type: string }
        raw_size_bytes: { type: integer, minimum: 1 }
        raw_sha256:
          type: string
          pattern: "^[0-9a-f]{64}$"
        error_code: { type: string }
        error_message:
          type: ["string", "null"]
        attempt_count: { type: integer, minimum: 1 }
        first_seen_at: { type: string, format: date-time }
        last_seen_at: { type: string, format: date-time }

    Domain:
      type: object
      description: |
        An organization-scoped domain ownership claim. Names use IDNA ASCII,
        lowercase, and no trailing root dot (canonicalization version 1).
        Other organizations may hold pending claims for the same name. Fresh
        generation-bound TXT proof atomically replaces any previous verified
        owner. Ownership alone does not enable email or increase agent trust.
      properties:
        id: { type: string, format: uuid }
        org_id: { type: string, format: uuid }
        domain: { type: string }
        canonicalization_version: { type: integer, const: 1 }
        spf_verified: { type: boolean }
        dkim_verified: { type: boolean }
        dmarc_verified: { type: boolean }
        verification_token: { type: string }
        status:
          type: string
          const: pending
          description: Legacy mail-readiness field; remains pending while provider setup is unsupported.
        ownership:
          type: object
          required: [status, generation, verified_at, evidence_version, challenge_issued_at, challenge_expires_at]
          properties:
            status: { type: string, enum: [pending, verified, superseded, revoked] }
            generation: { type: string, pattern: "^[1-9][0-9]*$" }
            verified_at: { type: [string, "null"], format: date-time }
            evidence_version: { type: string, enum: [none, legacy_unproven, dns_txt_v1, dns_authoritative_txt_v1] }
            challenge_issued_at: { type: string, format: date-time }
            challenge_expires_at: { type: string, format: date-time }
        provider_readiness:
          type: object
          required: [status, reason]
          properties:
            status: { type: string, const: unsupported }
            reason: { type: string, const: provider_configuration_not_issued }
        created_at: { type: string, format: date-time }

    DomainDnsRecord:
      type: object
      required: [type, name, value]
      properties:
        type: { type: string, const: TXT }
        name: { type: string }
        value: { type: string }

    DomainWithDns:
      allOf:
        - $ref: "#/components/schemas/Domain"
        - type: object
          properties:
            dns_records:
              type: object
              required: [verification, spf, dkim, dmarc, provider_records]
              properties:
                verification:
                  $ref: "#/components/schemas/DomainDnsRecord"
                spf: { type: "null" }
                dkim: { type: "null" }
                dmarc: { type: "null" }
                provider_records: { type: array, maxItems: 0, items: { type: object } }
              description: Only the ownership TXT is issued. Provider DNS values are unavailable and must not be inferred from legacy fields.

    DomainVerificationResponse:
      allOf:
        - $ref: "#/components/schemas/DomainWithDns"
        - type: object
          properties:
            verification_result:
              type: object
              required: [domain, verification, spf, dkim, dmarc, fully_verified, reason]
              properties:
                domain: { type: string }
                verification: { type: boolean }
                spf: { type: boolean, const: false }
                dkim: { type: boolean, const: false }
                dmarc: { type: boolean, const: false }
                fully_verified: { type: boolean, const: false }
                reason:
                  type: string
                  enum: [ownership_verified, challenge_refreshed, challenge_changed, record_not_found, dns_unavailable, verification_busy, challenge_expiring]

    TrustProfile:
      type: object
      required: [agent_id, trust_score, tier, recent_events, stats, quota]
      properties:
        agent_id: { type: string, format: uuid }
        trust_score: { type: integer }
        tier: { type: string, enum: [new, verified, trusted, enterprise] }
        recent_events:
          type: array
          items:
            $ref: "#/components/schemas/TrustEvent"
        stats:
          $ref: "#/components/schemas/TrustStats"
        quota:
          $ref: "#/components/schemas/TrustQuota"

    TrustEvent:
      type: object
      required: [id, agent_id, event_type, delta, reason, metadata, created_at]
      properties:
        id: { type: string, format: uuid }
        agent_id: { type: string, format: uuid }
        event_type: { type: string }
        delta: { type: integer }
        reason:
          type: ["string", "null"]
        metadata:
          type: object
          additionalProperties: true
        created_at: { type: string, format: date-time }

    TrustStats:
      type: object
      required:
        [total_deliveries, total_bounces, total_complaints, bounce_rate,
         complaint_rate]
      properties:
        total_deliveries: { type: integer, minimum: 0 }
        total_bounces: { type: integer, minimum: 0 }
        total_complaints: { type: integer, minimum: 0 }
        bounce_rate: { type: number, minimum: 0, maximum: 1 }
        complaint_rate: { type: number, minimum: 0, maximum: 1 }

    TrustQuota:
      type: object
      required: [allowed, daily_limit, used_today, remaining]
      properties:
        allowed: { type: boolean }
        daily_limit:
          type: ["integer", "null"]
          minimum: 0
          description: Effective daily external-recipient send limit; null means unlimited.
        used_today: { type: integer, minimum: 0 }
        remaining:
          type: ["integer", "null"]
          minimum: 0
          description: Remaining sends in the current daily window; null means unlimited.

    DeliveryTimelineEvent:
      type: object
      additionalProperties: false
      required: [id, delivery_id, event_type, payload, created_at]
      properties:
        id: { type: string, format: uuid }
        delivery_id: { type: string, format: uuid }
        event_type: { type: string }
        payload:
          type: object
          additionalProperties: true
        created_at: { type: string, format: date-time }

    DeliveryTimelineResponse:
      type: object
      additionalProperties: false
      required: [delivery, events]
      properties:
        delivery: { $ref: "#/components/schemas/Delivery" }
        events:
          type: array
          items: { $ref: "#/components/schemas/DeliveryTimelineEvent" }

    DeliveryExplanationFact:
      type: object
      additionalProperties: false
      required: [kind, name, recorded_at, attributes]
      properties:
        kind:
          type: string
          enum: [timeline_event, delivery_snapshot]
        name: { type: string }
        recorded_at: { type: string, format: date-time }
        attributes:
          type: object
          additionalProperties: true

    DeliveryExplanationResponse:
      type: object
      additionalProperties: false
      required: [delivery, steps, facts, explanation]
      properties:
        delivery: { $ref: "#/components/schemas/Delivery" }
        steps:
          type: array
          items: { type: string }
        facts:
          type: array
          items: { $ref: "#/components/schemas/DeliveryExplanationFact" }
        explanation: { type: string }

    SearchResult:
      type: object
      additionalProperties: false
      required: [id, thread_id, subject, from_addr, snippet, received_at, rank]
      properties:
        id: { type: string, format: uuid }
        thread_id: { type: string, format: uuid }
        subject:
          type: ["string", "null"]
        from_addr: { type: string }
        snippet:
          type: ["string", "null"]
        received_at: { type: string, format: date-time }
        rank: { type: number }

    SearchResponse:
      type: object
      additionalProperties: false
      required: [query, count, results, next_page_token, has_more]
      properties:
        query:
          type: string
          description: The caller-supplied full-text query echoed for this page.
        count:
          type: integer
          minimum: 0
          description: Number of results in this page, not a total across all pages.
        results:
          type: array
          items: { $ref: "#/components/schemas/SearchResult" }
        next_page_token:
          type: ["string", "null"]
          description: Opaque cursor for the next page, or null on the final page.
        has_more:
          type: boolean
          description: Whether another page is available after this one.

    CapabilitiesResponse:
      type: object
      additionalProperties: false
      required: [delivery_confirmation]
      properties:
        delivery_confirmation:
          type: object
          additionalProperties: false
          required: [enabled]
          properties:
            enabled:
              type: boolean
              description: True when this environment consumes provider feedback capable of confirming recipient delivery.

    WebhookSubscription:
      type: object
      required: [id, org_id, url, events, status, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        org_id: { type: string, format: uuid }
        url: { type: string, format: uri }
        events:
          type: array
          minItems: 1
          maxItems: 5
          uniqueItems: true
          items:
            type: string
            enum: [message.sent, message.received, message.delivered, message.bounced, message.complained]
        status: { type: string, enum: [active, paused, disabled] }
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time

    WebhookSubscriptionUpdate:
      allOf:
        - $ref: "#/components/schemas/WebhookSubscription"
        - type: object
          required: [sync_state]
          properties:
            sync_state:
              type: string
              enum: [synced, pending, parked]
              description: The committed row's provider-sync state; `pending` rows are retried by the worker with backoff. The worker parks a row after a terminal provider answer, and `parked` rows are not retried until a PATCH supplies `url` again.

    CreatedWebhookSubscription:
      allOf:
        - $ref: "#/components/schemas/WebhookSubscription"
        - type: object
          required: [signing_secret]
          properties:
            signing_secret:
              type: string
              pattern: "^whsec_"
              description: Svix-owned signing secret. Returned once and never stored by PagerMail or included in list responses.

    CustomerWebhookEvent:
      type: object
      additionalProperties: false
      required: [event_type, org_id, workspace_id, inbox_id, message_id, thread_id, occurred_at]
      description: Thin customer-webhook payload. Mail content, subject, body, attachments, and participant addresses are never included.
      properties:
        event_type:
          type: string
          enum: [message.sent, message.received, message.delivered, message.bounced, message.complained]
        org_id: { type: string, format: uuid }
        workspace_id: { type: string, format: uuid }
        inbox_id: { type: string, format: uuid }
        message_id: { type: string, format: uuid }
        thread_id: { type: string, format: uuid }
        occurred_at: { type: string, format: date-time }

    WebhookAttempt:
      type: object
      additionalProperties: false
      required: [id, event_id, status, response_status_code, timestamp, trigger_type]
      description: One provider delivery attempt. Request and response bodies, headers, provider URLs, and provider error details are never included.
      properties:
        id: { type: string }
        event_id:
          type: string
          nullable: true
          description: The PagerMail domain event id, when the provider still retains the message.
        status:
          type: string
          enum: [success, pending, fail, sending, canceled]
        response_status_code: { type: integer }
        timestamp: { type: string, format: date-time }
        trigger_type:
          type: integer
          enum: [0, 1]
          description: "0 = scheduled delivery, 1 = manual replay."

    WebhookAttemptPage:
      type: object
      additionalProperties: false
      required: [data, next_iterator]
      properties:
        data:
          type: array
          items:
            $ref: "#/components/schemas/WebhookAttempt"
        next_iterator:
          type: string
          nullable: true
          description: Opaque iterator for the next page; `null` means no further pages.

    WebhookRecoverTask:
      type: object
      additionalProperties: false
      required: [id, status, task, updated_at]
      description: Safe fields of the provider's background recovery task.
      properties:
        id: { type: string }
        status: { type: string, enum: [running, finished, failed] }
        task: { type: string }
        updated_at: { type: string, format: date-time }

    WebhookEvent:
      allOf:
        - $ref: "#/components/schemas/CustomerWebhookEvent"
        - type: object
          required: [id]
          properties:
            id:
              type: string
              format: uuid
              description: PagerMail domain event id.

    WebhookEventPage:
      type: object
      additionalProperties: false
      required: [data, next_cursor, caught_up]
      properties:
        data:
          type: array
          items:
            $ref: "#/components/schemas/WebhookEvent"
        next_cursor:
          type: string
          nullable: true
          description: Opaque signed cursor bound to the organization, principal, and filters; echoes the request cursor when the page examined nothing.
        caught_up:
          type: boolean
          description: True once a page examined fewer than its visible-row budget; stop polling while it is true and resume later from `next_cursor`.

    WebhookPortalLink:
      type: object
      additionalProperties: false
      required: [url]
      properties:
        url:
          type: string
          format: uri
          description: Short-lived, organization-bound Svix App Portal URL. It can view endpoints, the signing secret and delivery attempts, and resend deliveries; it cannot manage endpoints.

    MetricEntry:
      type: object
      properties:
        timestamp: { type: string, format: date-time }
        count: { type: integer }

    MetricsResponse:
      type: object
      additionalProperties:
        type: array
        items:
          $ref: "#/components/schemas/MetricEntry"

    PlanUsageMetric:
      type: object
      additionalProperties: false
      required: [used, limit]
      properties:
        used: { type: integer, minimum: 0 }
        limit:
          type: [integer, "null"]
          minimum: 0
          description: The plan cap. null means the plan has no cap.

    PlanUsage:
      type: object
      additionalProperties: false
      required: [plan, inboxes, domains, sends, sends_window, limits_enforced]
      properties:
        plan:
          type: string
          enum: [grace, free, developer, startup, enterprise]
        inboxes:
          allOf:
            - $ref: "#/components/schemas/PlanUsageMetric"
          description: Active inboxes in the organization.
        domains:
          allOf:
            - $ref: "#/components/schemas/PlanUsageMetric"
          description: Custom domain claims in the organization that are pending or verified.
        sends:
          allOf:
            - $ref: "#/components/schemas/PlanUsageMetric"
          description: External-email sends counted in sends_window.
        sends_window:
          type: object
          additionalProperties: false
          required: [start, end]
          properties:
            start: { type: string, format: date-time, description: Start of the current UTC calendar month. }
            end: { type: string, format: date-time, description: Start of the next UTC calendar month. }
        limits_enforced:
          type: boolean
          description: When false, a plan cap is shown but does not yet refuse requests.

    DatabasePoolStats:
      type: object
      additionalProperties: false
      required: [max, total, idle, checked_out, waiting, connection_timeout_ms]
      properties:
        max: { type: integer, minimum: 0 }
        total: { type: integer, minimum: 0 }
        idle: { type: integer, minimum: 0 }
        checked_out: { type: integer, minimum: 0 }
        waiting: { type: integer, minimum: 0 }
        connection_timeout_ms: { type: integer, minimum: 0 }

    OpsHealthSummary:
      type: object
      additionalProperties: false
      required:
        - queued_deliveries
        - stale_processing_deliveries
        - failed_deliveries_last_hour
        - bounced_deliveries_last_day
        - complained_deliveries_last_day
        - failed_processor_runs_last_hour
        - terminal_processor_runs
        - legacy_running_processor_runs
        - recent_webhook_failures_last_hour
        - webhook_outbox_pending_count
        - webhook_outbox_oldest_pending_age_seconds
        - inbound_quarantine_unresolved_count
        - inbound_quarantine_oldest_unresolved_age_seconds
        - inbound_quarantine_legacy_parked_count
        - inbound_quarantine_terminal_failure_count
        - unavailable_fields
      properties:
        queued_deliveries: { type: [integer, "null"], minimum: 0 }
        stale_processing_deliveries: { type: [integer, "null"], minimum: 0 }
        failed_deliveries_last_hour: { type: [integer, "null"], minimum: 0 }
        bounced_deliveries_last_day: { type: [integer, "null"], minimum: 0 }
        complained_deliveries_last_day: { type: [integer, "null"], minimum: 0 }
        failed_processor_runs_last_hour: { type: [integer, "null"], minimum: 0 }
        terminal_processor_runs: { type: [integer, "null"], minimum: 0 }
        legacy_running_processor_runs: { type: [integer, "null"], minimum: 0 }
        inbound_quarantine_legacy_parked_count: { type: [integer, "null"], minimum: 0 }
        inbound_quarantine_terminal_failure_count: { type: [integer, "null"], minimum: 0 }
        recent_webhook_failures_last_hour: { type: [integer, "null"], minimum: 0 }
        webhook_outbox_pending_count:
          type: [integer, "null"]
          minimum: 0
          description: Pending customer webhook rows for the requested organization/workspace scope, or null when this field is unavailable.
        webhook_outbox_oldest_pending_age_seconds:
          type: [number, "null"]
          minimum: 0
          description: Age of the oldest scoped pending customer webhook row. Null means empty unless this field appears in unavailable_fields.
        inbound_quarantine_unresolved_count:
          type: [integer, "null"]
          minimum: 0
          description: Unresolved inbound MIME quarantine rows for the requested organization/workspace scope, or null when unavailable.
        inbound_quarantine_oldest_unresolved_age_seconds:
          type: [number, "null"]
          minimum: 0
          description: Age of the oldest scoped unresolved inbound MIME quarantine row. Null means empty unless this field appears in unavailable_fields.
        unavailable_fields:
          type: array
          description: Fields whose database query or result validation failed. Their values are null; other fields remain usable.
          uniqueItems: true
          items:
            type: string
            enum:
              - queued_deliveries
              - stale_processing_deliveries
              - failed_deliveries_last_hour
              - bounced_deliveries_last_day
              - complained_deliveries_last_day
              - failed_processor_runs_last_hour
              - terminal_processor_runs
              - legacy_running_processor_runs
              - recent_webhook_failures_last_hour
              - webhook_outbox_pending_count
              - webhook_outbox_oldest_pending_age_seconds
              - inbound_quarantine_unresolved_count
              - inbound_quarantine_oldest_unresolved_age_seconds
              - inbound_quarantine_legacy_parked_count
              - inbound_quarantine_terminal_failure_count

    ReadinessResponse:
      type: object
      required: [status]
      properties:
        status:
          type: string
          enum: [ready, not_ready]

    RealtimeReadyEvent:
      type: object
      required:
        [schema_version, workspace_id, inbox_id, thread_id, event_types, cursor, head_cursor]
      properties:
        schema_version: { type: integer, const: 1 }
        workspace_id: { type: [string, "null"], format: uuid }
        inbox_id: { type: [string, "null"], format: uuid }
        thread_id: { type: [string, "null"], format: uuid }
        event_types:
          type: array
          items:
            type: string
            enum: [message.received, delivery.updated, processor.completed]
        cursor: { type: string, pattern: "^[A-Za-z0-9_-]{1,128}:[0-9]+$" }
        head_cursor: { type: string, pattern: "^[A-Za-z0-9_-]{1,128}:[0-9]+$" }

    RealtimeResetRequiredEvent:
      type: object
      required:
        [schema_version, reason, message, requested_cursor, head_cursor, oldest_replayable_cursor]
      properties:
        schema_version: { type: integer, const: 1 }
        reason:
          type: string
          enum: [foreign_epoch, cursor_ahead, cursor_too_old, subscriber_overflow]
        message: { type: string }
        requested_cursor:
          type: [string, "null"]
        head_cursor: { type: string, pattern: "^[A-Za-z0-9_-]{1,128}:[0-9]+$" }
        oldest_replayable_cursor:
          type: string
          pattern: "^[A-Za-z0-9_-]{1,128}:[0-9]+$"

    RealtimeDeliveryUpdatedPayload:
      type: object
      required:
        [status, delivery_state, accepted_at, delivered_at, provider, provider_id, timeline_event]
      additionalProperties: false
      properties:
        status: { type: string }
        delivery_state:
          type: string
          enum: [queued, processing, accepted, deferred, delivered, bounced, failed, rejected, complained]
        accepted_at: { type: [string, "null"], format: date-time }
        delivered_at: { type: [string, "null"], format: date-time }
        provider: { type: [string, "null"] }
        provider_id: { type: [string, "null"] }
        timeline_event:
          oneOf:
            - type: "null"
            - type: object
              additionalProperties: false
              required: [event_type, created_at]
              properties:
                event_type: { type: string }
                created_at: { type: string, format: date-time }

    RealtimePublishedEvent:
      type: object
      required:
        [schema_version, id, event_type, occurred_at, org_id, workspace_id,
         inbox_id, thread_id, message_id, delivery_id, processor, payload]
      properties:
        schema_version: { type: integer, const: 1 }
        id: { type: string, pattern: "^[A-Za-z0-9_-]{1,128}:[0-9]+$" }
        event_type:
          type: string
          enum: [message.received, delivery.updated, processor.completed]
        occurred_at: { type: string, format: date-time }
        org_id: { type: string }
        workspace_id: { type: string, format: uuid }
        inbox_id: { type: [string, "null"], format: uuid }
        thread_id: { type: [string, "null"], format: uuid }
        message_id: { type: [string, "null"], format: uuid }
        delivery_id: { type: [string, "null"], format: uuid }
        processor: { type: [string, "null"] }
        payload:
          type: object
          description: |
            Event-specific minimal payload. For `delivery.updated`, this is the
            `RealtimeDeliveryUpdatedPayload`; arbitrary provider errors and
            timeline payload bodies are excluded.
          additionalProperties: true

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: |
        This replay contract applies only to send, reply, reply-all, forward,
        and draft-send. Once a request commits successfully, reusing its key
        with the same canonical request returns the original response. Reusing
        it with a different request returns 409 `IDEMPOTENCY_CONFLICT`; an
        identical request still being completed returns 409
        `IDEMPOTENCY_IN_PROGRESS`. Invalid keys return 400
        `INVALID_IDEMPOTENCY_KEY`. Authorization 403 denials are never stored as
        completed replay responses. An unlinked reservation is abandoned so a
        later request re-evaluates policy; if a resource has already committed,
        its pending reservation remains linked for the recovery path. The
        stored result is a content-free reference rebuilt from immutable
        acceptance records; a replay whose records fail verification returns
        500 `IDEMPOTENCY_REPLAY_INTEGRITY` without content or re-execution.
        Requests without this header have no replay guarantee. The stored `expires_at`
        timestamp does not release the key's identity or permit reuse for a new
        send. No destructive expiry cleanup is enabled; a future retention or
        tombstone policy requires separate approval.
      schema:
        type: string
        minLength: 1
        maxLength: 200
        pattern: "^[A-Za-z0-9._:-]+$"

paths:
  /signup:
    get:
      summary: Check whether self-serve signup is currently available
      operationId: getSignupAvailability
      tags: [Signup]
      security: []
      description: |
        Returns `204` only when `SIGNUP_ENABLED=true` and the isolated signup
        provisioner reports ready within its bounded health check. A provisioner
        outage returns `503` without degrading the main API's `/admissionz`; a
        disabled signup surface remains absent behind the canonical `404` route
        contract.
      responses:
        "204":
          description: Signup is enabled and its provisioner is ready
        "404":
          description: Signup is disabled and the route is not exposed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RouteNotFoundError"
        "503":
          description: Signup is enabled but its isolated provisioner is unavailable
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      summary: Start agent signup
      operationId: startAgentSignup
      tags: [Signup]
      security: []
      description: |
        The fail-closed provisional-first strategy has two closed outcomes.
        With `SIGNUP_PROVISIONAL_FIRST=false` (the default), this is the released
        challenge-first path: it reserves no durable tenant and returns the exact
        neutral `202` challenge envelope. With the provisioner-only flag enabled,
        the username atomically creates a trust-zero agent, inbox, and read-only
        credential and returns `201`; OTP proof later upgrades that same agent
        and restores send capability on the same key.

        After the username passes syntax, reserved-name, occupancy, and
        quarantine checks, every human-email fact receives the same bytes within
        the selected mode. Fresh, historical, current-owner, invalid, blocked,
        deferred-email-budget-exhausted, throttled, undeliverable, and
        dispatch-failed values do not alter the synchronous mode response. The
        separate daily provisional-mint capacity is not a human-email fact;
        exhaustion creates no principal and uses the neutral `202` path. The
        response never states that mail was sent. A private-hop timeout or
        mismatched echoed handle also stays on that neutral path and returns no
        credential.

        A source-IP admission throttle runs before the database-backed username
        lookup. Like email and global-send controls, it remains inside the
        mode-specific uniform boundary rather than returning an
        identity-distinguishing `429`. OTP dispatch is best-effort deferred work,
        not a durable outbox. In provisional mode, an invalid, blocked, or
        over-budget email leaves the agent block-all until the bounded reaper
        tombstones it; no arbitrary outbound recipient becomes available.

        Username syntax failures depend on the username alone and return `400`.
        A reserved, occupied, or deletion-quarantined username returns the same
        `409 SIGNUP_USERNAME_UNAVAILABLE` regardless of the supplied email.
        Pending legacy challenge rows do not reserve public usernames. In
        provisional mode the username itself is reserved by the created inbox;
        repeating it returns the same `409` and never rotates the credential.

        This route is present only while `SIGNUP_ENABLED=true`. Production
        signup is live and currently serves the provisional-first outcome;
        `GET /signup` is the runtime availability probe. A deployment with the
        interactive flag disabled returns the canonical `404` instead.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentSignupRequest"
      responses:
        "201":
          description: Provisional agent, inbox, and read-only credential created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentSignupProvisionalResponse"
        "202":
          description: Exact legacy neutral challenge response, also used for an ambiguous private hop or exhausted daily provisional capacity
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentSignupChallengeResponse"
        "400":
          description: Request shape or name syntax failed validation
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ValidationError"
        "404":
          description: Signup is disabled and the route is not exposed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RouteNotFoundError"
        "409":
          description: Requested username is reserved, active, or quarantined after deletion
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupUsernameUnavailableError"
        "500":
          description: Internal server failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /signup/verify:
    post:
      summary: Verify an agent-door signup
      operationId: verifyAgentSignup
      tags: [Signup]
      security: []
      description: |
        Proves the opaque handle and six-digit code. For the default
        challenge-first path, one transaction creates the born-claimed
        organization, workspace, New-tier agent, key, and inbox. For a
        provisional handle, the transaction adds only the owner identity and
        reservation, restores exact `mail:read` and `mail:send` scopes on the
        already-locked key, marks the existing agent verified, and returns that
        same handle-derived key and address without creating or rotating any
        public tenant row. The successful call consumes the proof handle; every replay
        has the closed `invalid_handle` outcome. Production codes expire after
        15 minutes;
        five incorrect attempts invalidate a challenge.

        Fake handles, wrong codes, expired or invalidated challenges, and
        dispatch-failed challenges all return the same public `400` status and
        byte-identical `SIGNUP_VERIFICATION_FAILED` body. The API exposes no
        challenge-state oracle. A verified first-to-complete username collision
        may return the username-only `409`.

        This route also returns the canonical `404` while
        `SIGNUP_ENABLED=false`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SignupVerifyRequest"
      responses:
        "200":
          description: Agent verified at the New trust tier; mail:send is restored on the same key and provisional restrictions are lifted
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupVerifiedResponse"
        "400":
          description: Invalid request shape or uniform verification failure
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/ValidationError"
                  - $ref: "#/components/schemas/SignupVerificationFailedError"
        "404":
          description: Signup is disabled and the route is not exposed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RouteNotFoundError"
        "409":
          description: Requested username became occupied, or the verified identity conflicts with an existing boundary
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/SignupUsernameUnavailableError"
                  - $ref: "#/components/schemas/SignupIdentityConflictError"
        "503":
          description: Clerk identity registry freshness cannot be established
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupIdentityRegistryUnavailableError"

  /signup/resend:
    post:
      summary: Resend a provisional agent's verification code
      operationId: resendAgentSignupOtp
      tags: [Signup]
      security:
        - AgentKeyAuth: []
      description: |
        Authenticated recovery for an already-created provisional agent. The
        caller must use that provisional agent's original active read-only key
        with `mail:read`, and must supply the unchanged verification handle and
        human-owner email. Organization keys and Clerk sessions are not
        accepted. Resend never rotates or reissues the key or handle and never
        extends the provisional agent's original 15-minute lifetime. Every OTP
        email uses the database-authoritative provisional inbox as Reply-To and
        asks the human to reply directly with the code.

        A successful response is returned only after the provider accepts the
        newest code and that accepted delivery is durably finalized against the
        still-current issue. Attempts are cumulative across reissues. Every
        actual reissue consumes the existing per-email, per-key, and shared send
        budgets; a 60-second issue cooldown prevents duplicate sends. Failed,
        unknown, expired, or stale-pending delivery may be retried after that
        cooldown while the provisional remains live.

        `SIGNUP_PROVISIONAL_FIRST=false` affects only new starts; this recovery
        route remains available to drain existing provisionals. Turning
        `SIGNUP_ENABLED=false` removes this route behind the canonical `404`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SignupResendRequest"
      responses:
        "202":
          description: A new OTP was provider-accepted and durably finalized for this provisional
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupOtpResentResponse"
        "400":
          description: Invalid strict request shape or malformed JSON
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/ValidationError"
                  - $ref: "#/components/schemas/MalformedJsonError"
        "401":
          description: Missing, invalid, expired, or reaped/revoked agent key
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Credential is not an agent key or lacks mail:read
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/SignupResendAgentKeyRequiredError"
                  - $ref: "#/components/schemas/Error"
        "404":
          description: Signup is disabled and the route is not exposed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RouteNotFoundError"
        "409":
          description: Provisional state, original binding, or the production cap of five cumulative failed attempts across original and replacement challenges forbids resend
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupNotResendableError"
        "413":
          description: JSON request body exceeds the API byte limit
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/JsonBodyTooLargeError"
        "429":
          description: |
            The typed resend outcome means the issue cooldown or a per-key,
            per-email, or shared send budget was reached. Global, organization,
            or agent request middleware may instead throttle the request before
            the resend handler and return the code-less API throttle variant.
          headers:
            Retry-After:
              description: Whole seconds before retry, when supplied by the applicable limiter
              schema:
                type: integer
                minimum: 1
                maximum: 86400
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/SignupResendRateLimitedError"
                  - $ref: "#/components/schemas/ApiRequestRateLimitedError"
        "503":
          description: Provider delivery, durable finalization, the private provisioner, or shared Clerk-session identity reconciliation is unavailable
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/SignupResendDeliveryUnavailableError"
                  - $ref: "#/components/schemas/SignupIdentityRegistryUnavailableError"

  /signup/human:
    post:
      summary: Reconcile a Clerk identity into PagerMail
      operationId: reconcileHumanSignup
      tags: [Signup]
      security:
        - ClerkSessionAuth: []
      description: |
        Login-time reconciliation for a hosted Clerk session. PagerMail reads the
        authoritative Clerk user ID, every verified alias, membership, and
        invitation on the server; caller-supplied identity fields are forbidden.
        Each server-observed complete identity set is reserved atomically in
        PostgreSQL under the one-organization-per-Clerk-identity rule. A fresh
        identity receives a born-claimed organization and workspace. Known
        identities reconcile to their existing boundary. Detected stale or
        conflicting registry state fails closed. Webhook, login-time, and
        periodic reconciliation provide bounded consistency; they cannot make
        out-of-band Clerk mutations linearizable with PostgreSQL.

        This route also returns the canonical `404` while
        `SIGNUP_ENABLED=false`.
      responses:
        "200":
          description: The Clerk user has a linked PagerMail organization
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/HumanSignupResponse"
        "401":
          description: A Clerk session is missing or an Authorization header was supplied
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Clerk has not verified the user's email address
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupEmailNotVerifiedError"
        "404":
          description: Signup is disabled and the route is not exposed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RouteNotFoundError"
        "409":
          description: The complete Clerk identity set conflicts with an existing boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupIdentityConflictError"
        "503":
          description: Clerk identity registry freshness cannot be established
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupIdentityRegistryUnavailableError"

  /webhooks/clerk:
    post:
      summary: Synchronize Clerk identity state
      operationId: synchronizeClerkIdentityWebhook
      tags: [Signup]
      security: []
      description: |
        Receives signed Clerk events for users, all verified aliases,
        organization memberships, and invitations. Authentication is the Clerk
        Svix signature carried by `svix-id`, `svix-timestamp`, and
        `svix-signature`; no PagerMail Bearer credential is accepted. The event
        is acknowledged only after the provisioner commits the registry update.
        The signature is checked against the exact raw request bytes before JSON
        parsing. Responses never echo Clerk user, alias, membership, or
        invitation data.
      parameters:
        - name: svix-id
          in: header
          required: true
          schema: { type: string }
        - name: svix-timestamp
          in: header
          required: true
          schema: { type: string }
        - name: svix-signature
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: Signed Clerk event; its identity fields are never echoed.
              additionalProperties: true
      responses:
        "204":
          description: Identity registry update committed
        "400":
          description: Malformed Clerk event
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ValidationError" }
        "401":
          description: Missing or invalid Svix signature
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "413":
          description: Webhook body exceeds the fixed request-size limit
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: Identity synchronization provisioner is unavailable
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SignupIdentityRegistryUnavailableError" }

  /capabilities:
    get:
      summary: Get environment capability signals
      operationId: getCapabilities
      tags: [Capabilities]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      description: |
        Returns provider-neutral environment features. `delivery_confirmation.enabled`
        is true when PagerMail is configured to consume provider feedback capable
        of confirming recipient delivery. It does not promise that every provider
        or individual delivery will produce a confirmation.
      responses:
        "200":
          description: Environment capabilities
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CapabilitiesResponse"
        "403":
          description: The credential lacks `capabilities:read` or agent `mail:read`
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /session:
    get:
      summary: Get authenticated session context
      operationId: getSession
      tags: [Session]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
        - ClerkSessionAuth: []
      description: |
        Returns the effective authenticated boundary. For Clerk sessions, the
        server reconciles the authoritative user ID, all verified aliases,
        memberships, and invitations before resolving the organization. Unknown
        or stale identity-registry state fails closed with `503`; browser-supplied
        identity fields are never accepted.
      responses:
        "200":
          description: Session details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Session"
        "401":
          description: Missing, expired, revoked, or otherwise invalid credential
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          description: Principal or organization rate limit exceeded
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "503":
          description: Clerk identity registry freshness cannot be established
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SignupIdentityRegistryUnavailableError"

  /api-keys:
    get:
      summary: List API keys
      operationId: listApiKeys
      tags: [API Keys]
      parameters:
        - name: workspace_id
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: API keys for the authenticated org
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/ApiKey"
    post:
      summary: Create an API key
      operationId: createApiKey
      tags: [API Keys]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string, maxLength: 255 }
                scopes:
                  type: array
                  items: { type: string }
                workspace_id: { type: string, format: uuid }
      responses:
        "201":
          description: API key created
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  key: { type: string }
                  prefix: { type: string }
                  scopes:
                    type: array
                    items: { type: string }
                  workspace_id:
                    type: ["string", "null"]
                    format: uuid
                  warning: { type: string }
        "400":
          description: Validation error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ValidationError"
        "403":
          description: Scope or workspace violation
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /api-keys/{id}:
    delete:
      summary: Revoke an API key
      operationId: revokeApiKey
      tags: [API Keys]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: API key revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  revoked: { type: boolean }

  /workspaces:
    get:
      summary: List accessible workspaces
      operationId: listWorkspaces
      tags: [Workspaces]
      responses:
        "200":
          description: Workspaces visible to the API key
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/Workspace"
    post:
      summary: Create a workspace
      operationId: createWorkspace
      tags: [Workspaces]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string, maxLength: 255 }
                slug: { type: string, maxLength: 63 }
                description: { type: string, maxLength: 1000 }
                metadata:
                  type: object
                  additionalProperties: true
      responses:
        "201":
          description: Workspace created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Workspace"
        "403":
          description: Workspace-scoped keys cannot create workspaces
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /workspaces/{id}:
    get:
      summary: Get a workspace
      operationId: getWorkspace
      tags: [Workspaces]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Workspace details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Workspace"
        "404":
          description: Workspace not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    patch:
      summary: Update a workspace
      operationId: updateWorkspace
      tags: [Workspaces]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string, maxLength: 255 }
                slug: { type: string, maxLength: 63 }
                description:
                  type: ["string", "null"]
                  maxLength: 1000
                metadata:
                  type: object
                  additionalProperties: true
                status: { type: string, maxLength: 50 }
      responses:
        "200":
          description: Workspace updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Workspace"
        "403":
          description: Workspace-scoped keys cannot modify workspaces
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Workspace not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /agents:
    get:
      summary: List agents
      operationId: listAgents
      tags: [Agents]
      parameters:
        - name: page_token
          in: query
          schema: { type: string }
        - name: page_size
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
        - name: workspace_id
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Paginated agent list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentListResponse"
    post:
      summary: Create an agent
      description: The authenticated session or API key supplies the organization identity.
      operationId: createAgent
      tags: [Agents]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                workspace_id: { type: string, format: uuid }
                name: { type: string, maxLength: 255 }
                type: { type: string, maxLength: 100 }
                capabilities:
                  type: array
                  items: {}
                metadata:
                  type: object
                  additionalProperties: true
      responses:
        "201":
          description: Agent created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Agent"
        "400":
          description: Validation or workspace selection error
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/ValidationError"
                  - $ref: "#/components/schemas/Error"
  /agents/{id}:
    get:
      summary: Get an agent
      operationId: getAgent
      tags: [Agents]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Agent details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Agent"
        "404":
          description: Agent not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /agents/{id}/api-keys:
    get:
      summary: List an agent's bound credentials
      description: Requires Clerk org:admin or an organization key with wildcard or legacy admin authority. Raw secrets are never listed.
      operationId: listAgentApiKeys
      tags: [Agent Credentials]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Agent credential metadata
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/AgentApiKey"
        "401":
          description: Missing or invalid credential
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: Organization-admin authority is required
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Agent not found in the caller's organization and workspace boundary
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: Credential-management rate limit exceeded
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Create an agent-bound credential
      description: Returns the raw pm_agent_ secret exactly once and is intentionally not idempotency-replayable.
      operationId: createAgentApiKey
      tags: [Agent Credentials]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [name, scopes]
              properties:
                name: { type: string, minLength: 1, maxLength: 255 }
                scopes:
                  type: array
                  minItems: 1
                  maxItems: 2
                  uniqueItems: true
                  items:
                    $ref: "#/components/schemas/AgentKeyScope"
                inbox_ids:
                  type: array
                  minItems: 1
                  uniqueItems: true
                  items: { type: string, format: uuid }
                  description: Omit for all current and future active inboxes owned by this agent in its workspace.
                expires_at:
                  type: string
                  format: date-time
                  description: Defaults to 90 days and cannot exceed 365 days after creation.
      responses:
        "201":
          description: Agent credential created; store the returned raw key now
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentApiKeyCreateResponse"
        "400":
          description: Invalid name, scope set, inbox list, or expiry policy
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "401":
          description: Missing or invalid credential
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: Organization-admin authority is required
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Agent or selected inbox not found in the effective boundary
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: Agent or workspace lifecycle changed during issuance
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: Credential-management rate limit exceeded
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /agents/{id}/api-keys/{key_id}:
    delete:
      summary: Revoke an agent-bound credential
      description: Revocation is idempotent for an existing credential and returns its original revoked_at timestamp.
      operationId: revokeAgentApiKey
      tags: [Agent Credentials]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: key_id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Credential revoked, or an existing revocation replayed
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [revoked, revoked_at]
                properties:
                  revoked: { type: boolean, const: true }
                  revoked_at: { type: string, format: date-time }
        "401":
          description: Missing or invalid credential
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: Organization-admin authority is required
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Agent or credential not found in the effective boundary
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: Credential-management rate limit exceeded
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /inboxes:
    get:
      summary: List inboxes
      operationId: listInboxes
      tags: [Inboxes]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: page_token
          in: query
          schema: { type: string }
        - name: page_size
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
        - name: workspace_id
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Paginated inbox list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InboxListResponse"
    post:
      summary: Create an inbox
      description: |
        The authenticated principal supplies the organization identity. Omit
        both `domain_id` and `local_part` to allocate a cryptographically random
        address at the configured PagerMail platform inbox domain. Custom-domain
        inbox creation is disabled. Supplying both custom fields returns
        `409 CUSTOM_DOMAIN_UNAVAILABLE` after authorization and validation.

        Selecting a custom-domain identity requires either a Clerk
        organization admin or an unpinned, organization-wide API key authorized
        for both `inboxes:write` and `domains:write`. Agent keys, Clerk
        organization members, and workspace-pinned API keys cannot reserve this
        organization-wide namespace. Generated platform-address creation keeps
        the existing `inboxes:write` boundary.

        Existing custom-domain identity records remain reserved for migration
        compatibility. Ownership verification does not configure provider
        ingress or outbound signing. Custom-domain sending and receiving remain
        disabled until those prerequisites are implemented and reviewed.
      operationId: createInbox
      tags: [Inboxes]
      security:
        - ApiKeyAuth: []
        - ClerkSessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - title: PagerMail platform inbox
                  type: object
                  description: Omit both custom-domain identity fields.
                  required: [agent_id]
                  properties:
                    agent_id: { type: string, format: uuid }
                    workspace_id: { type: string, format: uuid }
                    display_name: { type: string, maxLength: 255 }
                    features:
                      type: object
                      additionalProperties: true
                    domain_id: false
                    local_part: false
                  not:
                    anyOf:
                      - required: [domain_id]
                      - required: [local_part]
                - title: Custom-domain inbox identity (disabled)
                  type: object
                  description: Legacy request shape retained for compatibility; currently returns 409 CUSTOM_DOMAIN_UNAVAILABLE. Both identity fields are required together.
                  required: [agent_id, domain_id, local_part]
                  properties:
                    agent_id: { type: string, format: uuid }
                    workspace_id: { type: string, format: uuid }
                    display_name: { type: string, maxLength: 255 }
                    features:
                      type: object
                      additionalProperties: true
                    domain_id:
                      type: string
                      format: uuid
                      description: Verified custom domain owned by the authenticated organization.
                    local_part:
                      type: string
                      maxLength: 64
                      pattern: "^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$"
                      not:
                        pattern: "\\.\\."
                      description: |
                        Exact lowercase local part to reserve. Consecutive dots
                        are invalid. PagerMail does not trim whitespace or
                        normalize case; non-conforming input is rejected. The
                        materialized `local_part@domain` address may not exceed
                        254 bytes.
      responses:
        "201":
          description: Inbox created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Inbox"
        "400":
          description: Validation or workspace selection error
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/ValidationError"
                  - $ref: "#/components/schemas/Error"
        "403":
          description: Custom-domain identity selection requires a Clerk organization admin or an unpinned organization-wide API key authorized for both inboxes:write and domains:write
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Active agent or workspace not found in the authenticated organization
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Custom-domain inbox creation is disabled (CUSTOM_DOMAIN_UNAVAILABLE)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "503":
          description: A unique platform inbox address could not be allocated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /inboxes/{id}:
    get:
      summary: Get an inbox
      operationId: getInbox
      tags: [Inboxes]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Inbox details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Inbox"
        "404":
          description: Inbox not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    put:
      summary: Update an inbox
      operationId: updateInbox
      tags: [Inboxes]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                display_name: { type: string, maxLength: 255 }
                features:
                  type: object
                  additionalProperties: true
      responses:
        "200":
          description: Inbox updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Inbox"
        "404":
          description: Inbox not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    delete:
      summary: Soft-delete an inbox
      operationId: deleteInbox
      tags: [Inboxes]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Inbox deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted: { type: boolean }
        "404":
          description: Inbox not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /inboxes/{id}/messages:
    get:
      summary: List messages for an inbox
      operationId: listInboxMessages
      tags: [Inboxes, Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: label
          in: query
          description: Trash is excluded by default; use `trash` to request trashed messages.
          schema: { type: string }
        - name: page_token
          in: query
          schema: { type: string }
        - name: page_size
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
      responses:
        "200":
          description: Paginated message list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageListResponse"

  /inboxes/{id}/threads:
    get:
      summary: List threads for an inbox
      operationId: listInboxThreads
      tags: [Inboxes, Threads]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: label
          in: query
          description: Trash is excluded by default; use `trash` to request trashed threads.
          schema: { type: string }
        - name: page_token
          in: query
          schema: { type: string }
        - name: page_size
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
      responses:
        "200":
          description: Paginated thread list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ThreadListResponse"

  /inboxes/{inboxId}/drafts:
    get:
      summary: List drafts for an inbox
      description: |
        Ordered by immutable draft creation time (`received_at`); edits do not
        reorder the list and no `updated_at` is exposed. Agent keys require
        `mail:read` and see drafts only in an active inbox owned by the
        authenticated agent and included in the key's effective inbox grant.
      operationId: listDrafts
      tags: [Drafts]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: inboxId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: page_token
          in: query
          schema: { type: string }
        - name: page_size
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
        - name: label
          in: query
          description: Trash is excluded by default; use `trash` to request trashed drafts.
          schema: { type: string }
      responses:
        "200":
          description: Paginated draft list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MessageListResponse"
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Inbox is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected draft-list failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"
    post:
      summary: Create a draft
      description: |
        JSON-only draft creation. Attachments and reply/forward source
        derivation are not supported. Agent keys require `mail:send`; the
        target inbox must be owned by the authenticated agent and included in
        the key's effective inbox grant. A referenced thread must contain at
        least one message visible through that same effective grant.
      operationId: createDraft
      tags: [Drafts]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: inboxId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                to:
                  description: Bare email address or addresses; display-name mailbox wrappers are rejected.
                  oneOf:
                    - type: string
                      format: email
                      maxLength: 254
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                cc:
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                bcc:
                  description: Envelope-only; never returned on Message resources or emitted as a header. Sending currently requires EMAIL_PROVIDER_MODE=cloudflare; other adapters reject before persistence.
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                reply_to: { type: string, format: email, maxLength: 254 }
                headers:
                  type: object
                  description: Reviewed X-* headers only, excluding X-PagerMail-*; 8 KiB aggregate and 998-octet per-field caps.
                  propertyNames: { pattern: "^X-" }
                  additionalProperties: { type: string }
                subject: { type: string }
                body_text: { type: string }
                body_html: { type: string }
                thread_id: { type: string, format: uuid }
      responses:
        "201":
          description: Draft created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Message"
        "403":
          description: Agent key lacks `mail:send`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Inbox or referenced thread is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected draft-creation failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /drafts/{draftId}:
    put:
      summary: Update a draft
      description: |
        JSON-only update. Omit `reply_to` to preserve it; the current contract
        does not support clearing it with null or an empty value. Agent keys
        require both `mail:read` and `mail:send`; the draft must belong to an
        active inbox in the key's effective grant.
      operationId: updateDraft
      tags: [Drafts]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: draftId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                to:
                  description: Bare email address or addresses; display-name mailbox wrappers are rejected.
                  oneOf:
                    - type: string
                      format: email
                      maxLength: 254
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                cc:
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                bcc:
                  description: Envelope-only and omitted from Message, delivery, and routing responses.
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                reply_to: { type: string, format: email, maxLength: 254 }
                headers:
                  type: object
                  additionalProperties: { type: string }
                subject: { type: string }
                body_text: { type: string }
                body_html: { type: string }
      responses:
        "200":
          description: Draft updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Message"
        "403":
          description: Agent key lacks `mail:read` or `mail:send`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Draft is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "400":
          description: The message is not a draft (no draft label and no accepted or received facts)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: |
            The message is not an editable draft. Eligibility is structural,
            never a label: accepted, received, internal-copy and ambiguous
            messages are refused and never mutated.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected draft-update failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"
    delete:
      summary: Delete a draft
      operationId: deleteDraft
      tags: [Drafts]
      parameters:
        - name: draftId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Draft deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted: { type: boolean }
        "400":
          description: The message is not a draft (no draft label and no accepted or received facts)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: |
            The message is not an editable draft. Eligibility is structural,
            never a label: accepted, received, internal-copy and ambiguous
            messages are refused and never mutated.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Draft is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected draft-deletion failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /drafts/{draftId}/send:
    post:
      summary: Send a draft
      description: |
        A trashed draft is currently sendable and retains its trash label.
        Trash is a list-visibility state, not a send prohibition. Agent keys
        require both `mail:read` and `mail:send`, and the draft must belong to
        an active inbox in the key's effective grant. Draft send uses the same
        `routeMessage` choke point and provisional-recipient policy as direct
        send, including recovery retries.
      operationId: sendDraft
      tags: [Drafts, Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: draftId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: "#/components/parameters/IdempotencyKey"
      responses:
        "202":
          description: Draft queued for delivery
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SendResponse"
        "400":
          description: Invalid idempotency key or draft send request
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyError"
                  - $ref: "#/components/schemas/Error"
        "403":
          description: Agent scope is insufficient or the sender is an unverified provisional agent
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
                  - $ref: "#/components/schemas/ProvisionalSendRestrictedError"
        "409":
          description: |
            Idempotency key conflict, an identical request still in progress,
            or a message that is not an editable draft ("Draft is no longer
            editable"). Accepted and received messages are never re-sent.
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/IdempotencyError"
                  - $ref: "#/components/schemas/Error"
        "404":
          description: Draft is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          description: Operator per-message external-recipient cap (RECIPIENT_CAP_EXCEEDED, not retryable), or a principal or organization rate limit
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/RecipientCapExceededError"
                  - $ref: "#/components/schemas/Error"
        "503":
          description: New user sends are paused by the operator (USER_SENDS_PAUSED, not retryable until lifted), sending is busy (SEND_BUSY, this attempt changed nothing; retry the same request, with the same Idempotency-Key, after Retry-After), or a dependency is unavailable
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/UserSendsPausedError"
                  - $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected draft-send failure, or a replay whose stored reference failed integrity verification
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyReplayIntegrityError"
                  - $ref: "#/components/schemas/InternalServerError"

  /threads/{id}/context:
    get:
      summary: Get bounded thread context
      description: |
        Returns a size-capped briefing derived only from non-trash messages visible through
        the caller's organization, workspace, and agent inbox grant.
        `context_summary` is a deterministic structural digest, not an AI or abstractive
        summary. `last_n_messages` contains the most recent bounded window in chronological
        order, with each text-body snippet capped at 200 characters. Use `fetch_reference`
        to fetch the broader caller-accessible thread resource when more history is needed.

        Organization API keys require `threads:read`; agent credentials require
        `mail:read` and are further limited to their effective inbox grant.
      operationId: getThreadContext
      tags: [Threads]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: n
          in: query
          required: false
          description: |
            Requested size of the recent-message window. Defaults to 3. Integer values
            below 1 are clamped to 1, and values above the hard server cap of 20 are
            clamped to 20.
          schema:
            type: integer
            minimum: 1
            maximum: 20
            default: 3
      responses:
        "200":
          description: Bounded structural thread context
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ThreadContext"
        "404":
          description: Thread not found or no non-trash messages are visible to the caller
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /threads/{id}:
    get:
      summary: Get a thread with messages
      operationId: getThread
      tags: [Threads]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: label
          in: query
          required: false
          description: Filter messages by label. Trashed messages are hidden unless `trash` is requested explicitly.
          schema: { type: string, maxLength: 64 }
      responses:
        "200":
          description: Thread details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ThreadWithMessages"
        "404":
          description: Thread not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /messages/send:
    post:
      summary: Send a message
      operationId: sendMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      description: |
        Production transport uses the verified `send.pagermail.ai` sending
        domain (including `verify@send.pagermail.ai` for signup codes).
        Eligible platform inbox identities remain at `@in.pagermail.ai`;
        PagerMail preserves that identity as Reply-To and carries RFC thread
        headers so replies return to the inbox. Filter and correlate on
        Reply-To and thread identity rather than assuming the visible From
        domain is the agent inbox domain.

        A reserved `custom_domain` inbox is not currently an eligible
        `from_inbox_id` and receives the same `404` as a missing sender inbox.
        Custom-domain sending remains disabled until DKIM keys can be
        provisioned and used to sign that domain's mail; PagerMail never falls
        back to an unsigned custom-domain From address.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from_inbox_id, to, subject]
              properties:
                from_inbox_id: { type: string, format: uuid }
                to:
                  description: Bare email address or addresses; display-name mailbox wrappers are rejected.
                  oneOf:
                    - type: string
                      format: email
                      maxLength: 254
                    - type: array
                      minItems: 1
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                cc:
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                bcc:
                  description: Envelope-only and omitted from Message, delivery, and routing responses.
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                reply_to: { type: string, format: email, maxLength: 254 }
                headers:
                  type: object
                  description: Reviewed X-* headers only, excluding X-PagerMail-*; 8 KiB serialized cap.
                  propertyNames: { pattern: "^X-" }
                  additionalProperties: { type: string }
                subject: { type: string, maxLength: 998 }
                body_text: { type: string }
                body_html: { type: string }
                structured_payload:
                  type: object
                  additionalProperties: true
                thread_id: { type: string, format: uuid }
          multipart/form-data:
            schema:
              type: object
              required: [payload]
              properties:
                payload:
                  type: string
                  description: JSON-encoded send payload
                attachments:
                  type: array
                  maxItems: 20
                  description: Repeated attachments file parts. Defaults are 5 files and 10 MiB aggregate; operator limits may be lower than the hard ceilings of 20 files and 25 MiB aggregate. Filenames use UTF-8, at most 255 bytes; content types at most 255 bytes. The JSON payload field is capped at 1 MiB. SDKs use native multipart boundaries.
                  items:
                    type: string
                    format: binary
      responses:
        "202":
          description: Message accepted and queued for routing
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SendResponse"
        "413":
          description: Attachment count, file size, aggregate bytes, or multipart wire size exceeds configured limits. The error code identifies the limit; uploaded bytes are never returned.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "400":
          description: Validation error
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/ValidationError"
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/IdempotencyError"
        "403":
          description: Agent scope is insufficient or the sender is an unverified provisional agent
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
                  - $ref: "#/components/schemas/ProvisionalSendRestrictedError"
        "409":
          description: Idempotency key conflict or an identical request still in progress
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IdempotencyError" }
        "404":
          description: Sender inbox is missing, outside the effective boundary, or not yet an eligible outbound identity
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: Operator per-message external-recipient cap (RECIPIENT_CAP_EXCEEDED, not retryable), or a principal or organization rate limit
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/RecipientCapExceededError"
                  - $ref: "#/components/schemas/Error"
        "503":
          description: New user sends are paused by the operator (USER_SENDS_PAUSED, not retryable until lifted), sending is busy (SEND_BUSY, this attempt changed nothing; retry the same request, with the same Idempotency-Key, after Retry-After), or a dependency is unavailable
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/UserSendsPausedError"
                  - $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected message-send failure, or a replay whose stored reference failed integrity verification
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyReplayIntegrityError"
                  - $ref: "#/components/schemas/InternalServerError"

  /messages/{id}:
    get:
      summary: Get an enriched message
      operationId: getMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Message with attachments and processor runs
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/EnrichedMessage"
        "404":
          description: Message not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected message-read failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/attachments/{attachmentId}:
    get:
      summary: Download an attachment
      operationId: downloadAttachment
      tags: [Attachments]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: attachmentId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Attachment binary
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        "404":
          description: Message or attachment not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected attachment-download failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/attachments/{attachmentId}/extraction:
    get:
      summary: Read attachment extraction availability or result
      operationId: getAttachmentExtraction
      tags: [Attachments]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      description: |
        Requires messages:read for organization keys or mail:read for agent keys,
        and access to the exact source message and inbox in the effective tenant,
        workspace, and agent boundary. Missing or inaccessible sources return 404.
        Does not fetch, parse, or enqueue an attachment. Disabled extraction returns
        disabled with EXTRACTION_DISABLED, null text, and no extractor version.
        An enabled reviewed worker persists asynchronous results. No historical backfill is performed.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: attachmentId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Extraction availability or persisted result, with private no-store caching
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttachmentExtractionResult" }
        "400":
          description: Invalid resource identifier
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "401":
          description: Authentication required
        "403":
          description: Credential lacks the required read scope
        "404":
          description: Attachment is absent or outside the effective authorization boundary
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "500":
          description: Unexpected extraction-read failure
          content:
            application/json:
              schema: { $ref: "#/components/schemas/InternalServerError" }

  /messages/{id}/labels:
    patch:
      summary: Add or remove labels
      description: |
        Agent keys require `mail:read`. The message must belong to an active
        inbox owned by the authenticated agent and included in the key's
        effective inbox grant; out-of-grant identifiers return the same `404`
        as nonexistent messages.
      operationId: updateMessageLabels
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                add:
                  type: array
                  items: { type: string }
                remove:
                  type: array
                  items: { type: string }
      responses:
        "200":
          description: Message labels updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Message"
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Message is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected message-label update failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/reply:
    post:
      summary: Reply to a message
      operationId: replyToMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from_inbox_id]
              properties:
                from_inbox_id: { type: string, format: uuid }
                cc:
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                bcc:
                  description: Envelope-only and omitted from Message, delivery, and routing responses.
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                reply_to: { type: string, format: email, maxLength: 254 }
                headers:
                  type: object
                  additionalProperties: { type: string }
                body_text: { type: string }
                body_html: { type: string }
      responses:
        "202":
          description: Reply queued
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SendResponse"
        "400":
          description: Invalid idempotency key or reply request
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyError"
                  - $ref: "#/components/schemas/Error"
        "403":
          description: Agent scope is insufficient or the sender is an unverified provisional agent
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
                  - $ref: "#/components/schemas/ProvisionalSendRestrictedError"
        "409":
          description: Idempotency key conflict or an identical request still in progress
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IdempotencyError" }
        "429":
          description: Operator per-message external-recipient cap (RECIPIENT_CAP_EXCEEDED, not retryable), or a principal or organization rate limit
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/RecipientCapExceededError"
                  - $ref: "#/components/schemas/Error"
        "503":
          description: New user sends are paused by the operator (USER_SENDS_PAUSED, not retryable until lifted), sending is busy (SEND_BUSY, this attempt changed nothing; retry the same request, with the same Idempotency-Key, after Retry-After), or a dependency is unavailable
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/UserSendsPausedError"
                  - $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected reply failure, or a replay whose stored reference failed integrity verification
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyReplayIntegrityError"
                  - $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/reply-all:
    post:
      summary: Reply-all to a message
      operationId: replyAllToMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from_inbox_id]
              properties:
                from_inbox_id: { type: string, format: uuid }
                cc:
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                bcc:
                  description: Envelope-only and omitted from Message, delivery, and routing responses.
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                reply_to: { type: string, format: email, maxLength: 254 }
                headers:
                  type: object
                  additionalProperties: { type: string }
                body_text: { type: string }
                body_html: { type: string }
      responses:
        "202":
          description: Reply-all queued
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SendResponse"
        "400":
          description: Invalid idempotency key or reply-all request
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyError"
                  - $ref: "#/components/schemas/Error"
        "403":
          description: Agent scope is insufficient or the sender is an unverified provisional agent
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
                  - $ref: "#/components/schemas/ProvisionalSendRestrictedError"
        "409":
          description: Idempotency key conflict or an identical request still in progress
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IdempotencyError" }
        "429":
          description: Operator per-message external-recipient cap (RECIPIENT_CAP_EXCEEDED, not retryable), or a principal or organization rate limit
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/RecipientCapExceededError"
                  - $ref: "#/components/schemas/Error"
        "503":
          description: New user sends are paused by the operator (USER_SENDS_PAUSED, not retryable until lifted), sending is busy (SEND_BUSY, this attempt changed nothing; retry the same request, with the same Idempotency-Key, after Retry-After), or a dependency is unavailable
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/UserSendsPausedError"
                  - $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected reply-all failure, or a replay whose stored reference failed integrity verification
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyReplayIntegrityError"
                  - $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/forward:
    post:
      summary: Forward a message
      operationId: forwardMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from_inbox_id, to]
              properties:
                from_inbox_id: { type: string, format: uuid }
                to:
                  description: Bare email address or addresses; display-name mailbox wrappers are rejected.
                  oneOf:
                    - type: string
                      format: email
                      maxLength: 254
                    - type: array
                      minItems: 1
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                cc:
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                bcc:
                  description: Envelope-only and omitted from Message, delivery, and routing responses.
                  oneOf:
                    - { type: string, format: email, maxLength: 254 }
                    - type: array
                      maxItems: 20
                      items: { type: string, format: email, maxLength: 254 }
                reply_to: { type: string, format: email, maxLength: 254 }
                headers:
                  type: object
                  additionalProperties: { type: string }
                body_text: { type: string }
                body_html: { type: string }
      responses:
        "202":
          description: Forward queued
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SendResponse"
        "400":
          description: Invalid idempotency key or forward request
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyError"
                  - $ref: "#/components/schemas/Error"
        "403":
          description: Agent scope is insufficient or the sender is an unverified provisional agent
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
                  - $ref: "#/components/schemas/ProvisionalSendRestrictedError"
        "409":
          description: Idempotency key conflict or an identical request still in progress
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IdempotencyError" }
        "429":
          description: Operator per-message external-recipient cap (RECIPIENT_CAP_EXCEEDED, not retryable), or a principal or organization rate limit
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/RecipientCapExceededError"
                  - $ref: "#/components/schemas/Error"
        "503":
          description: New user sends are paused by the operator (USER_SENDS_PAUSED, not retryable until lifted), sending is busy (SEND_BUSY, this attempt changed nothing; retry the same request, with the same Idempotency-Key, after Retry-After), or a dependency is unavailable
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/UserSendsPausedError"
                  - $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected forward failure, or a replay whose stored reference failed integrity verification
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/IdempotencyReplayIntegrityError"
                  - $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/raw:
    get:
      summary: Download the byte-identical original inbound MIME
      operationId: getRawMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Hash-verified original MIME bytes
          content:
            message/rfc822:
              schema:
                type: string
                format: binary
        "409":
          description: Original MIME is unavailable for a legacy, internal, or outbound message
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Message not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Stored original MIME integrity failure or unexpected retrieval failure
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/OriginalMimeIntegrityError"
                  - $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/process:
    post:
      summary: Run the OTP processor
      description: |
        Agent keys require `mail:read`; the message must belong to an active
        inbox in the key's effective inbox grant.
      operationId: processMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Processor run result
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ProcessorRun"
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Message is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected OTP-processor failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/pipeline:
    post:
      summary: Run the full processor pipeline
      description: |
        Agent keys require `mail:read`; the message must belong to an active
        inbox in the key's effective inbox grant.
      operationId: runMessagePipeline
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Pipeline result
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Message is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected processor-pipeline failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/spam:
    post:
      summary: Mark a message as spam
      description: Agent keys require `mail:read` and may mutate only messages in their effective inbox grant.
      operationId: markMessageSpam
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Message updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Message"
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Message is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected spam-label update failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/not-spam:
    post:
      summary: Remove the spam label
      description: Agent keys require `mail:read` and may mutate only messages in their effective inbox grant.
      operationId: markMessageNotSpam
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Message updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Message"
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Message is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected spam-label removal failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/trash:
    post:
      summary: Move a message to trash
      description: Agent keys require `mail:read` and may mutate only messages in their effective inbox grant.
      operationId: trashMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Message updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Message"
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Message is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected trash operation failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /messages/{id}/untrash:
    post:
      summary: Remove the trash label
      description: Agent keys require `mail:read` and may mutate only messages in their effective inbox grant.
      operationId: untrashMessage
      tags: [Messages]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Message updated
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Message"
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Message is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected untrash operation failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /deliveries:
    get:
      summary: List deliveries
      operationId: listDeliveries
      tags: [Deliveries]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      description: |
        Cursor-paginated deliveries inside the authenticated organization and
        optional workspace. Agent credentials are additionally restricted to
        their owning agent, workspace, active inboxes, and inbox grant. Public
        pages include visible To/Cc deliveries only; Bcc rows never enter the
        pagination window.
      parameters:
        - name: page_token
          in: query
          schema: { type: string }
        - name: page_size
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
        - name: workspace_id
          in: query
          schema: { type: string, format: uuid }
        - name: inbox_id
          in: query
          schema: { type: string, format: uuid }
        - name: state
          in: query
          description: Filter the honest delivery projection, not the legacy queue status.
          schema:
            type: string
            enum: [queued, processing, accepted, deferred, delivered, bounced, failed, rejected, complained]
      responses:
        "200":
          description: Paginated visible delivery list
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DeliveryListResponse"
        "400":
          description: Invalid cursor, filter, or identifier
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: Workspace or credential scope mismatch
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Workspace not found
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /deliveries/{id}:
    get:
      summary: Get a delivery
      operationId: getDelivery
      tags: [Deliveries]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Delivery details
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Delivery"
        "404":
          description: Delivery not found or the delivery is for a Bcc recipient
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /deliveries/{id}/timeline:
    get:
      summary: Get delivery timeline
      operationId: getDeliveryTimeline
      tags: [Deliveries]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Delivery plus ordered timeline events
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DeliveryTimelineResponse"
        "404":
          description: Delivery not found or the delivery is for a Bcc recipient
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /deliveries/{id}/explain:
    get:
      summary: Explain delivery behavior
      operationId: explainDelivery
      tags: [Deliveries]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Human-readable explanation plus ordered machine-readable facts
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DeliveryExplanationResponse"
        "404":
          description: Delivery not found or the delivery is for a Bcc recipient
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /search:
    get:
      summary: Search messages
      description: |
        English full-text search over message subject and plain-text body with optional exact
        sender, To-recipient, date, label, inbox, and workspace filters. Filters
        are combined with the required `q` query using AND. Results are ordered
        by `received_at` descending and then `id` descending; relevance rank is
        informational and does not affect cursor order.

        Agent keys require `mail:read`. Authorization to the authenticated
        agent's active inboxes, workspace, and effective inbox grant is applied
        in the database before filtering and pagination. An inbox filter only
        intersects that boundary and can never widen it. To-recipient filtering
        never examines Cc or Bcc recipients.

        When following `next_page_token`, clients must repeat `q` and every
        filter unchanged because the opaque token identifies only a position in
        the newest-first ordering.
      operationId: searchMessages
      tags: [Search]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: q
          in: query
          required: true
          description: English PostgreSQL full-text query over subject and plain-text body; attachment contents and OCR output are not indexed.
          schema: { type: string, minLength: 1, maxLength: 500 }
        - name: from
          in: query
          description: Exact sender address. Alias of `sender`; provide only one.
          schema: { type: string, minLength: 1, maxLength: 254 }
        - name: sender
          in: query
          description: Exact sender address. Alias of `from`; provide only one.
          schema: { type: string, minLength: 1, maxLength: 254 }
        - name: to
          in: query
          description: Exact To-recipient address. Alias of `recipient`; Cc and Bcc are never searched. Provide only one alias.
          schema: { type: string, minLength: 1, maxLength: 254 }
        - name: recipient
          in: query
          description: Exact To-recipient address. Alias of `to`; Cc and Bcc are never searched. Provide only one alias.
          schema: { type: string, minLength: 1, maxLength: 254 }
        - name: after
          in: query
          description: Inclusive `received_at` lower bound. Date-only values mean midnight UTC; timestamps require an offset of at most ±15:59 and at most six fractional-second digits.
          schema:
            oneOf:
              - { type: string, format: date }
              - { type: string, format: date-time }
        - name: before
          in: query
          description: Exclusive `received_at` upper bound, later than `after`. Date-only values mean midnight UTC; timestamps require an offset of at most ±15:59 and at most six fractional-second digits.
          schema:
            oneOf:
              - { type: string, format: date }
              - { type: string, format: date-time }
        - name: label
          in: query
          description: Exact label. Trash is excluded by default; `label=trash` searches trashed messages.
          schema: { type: string, maxLength: 100 }
        - name: inbox_id
          in: query
          description: Inbox UUID intersected with the caller's authorization boundary. Alias of `inbox`; provide only one.
          schema: { type: string, format: uuid }
        - name: inbox
          in: query
          description: Inbox UUID intersected with the caller's authorization boundary. Alias of `inbox_id`; provide only one.
          schema: { type: string, format: uuid }
        - name: workspace_id
          in: query
          description: Authorized workspace UUID to search within.
          schema: { type: string, format: uuid }
        - name: page_token
          in: query
          description: Opaque cursor returned by the preceding search page. Repeat all search filters unchanged.
          schema: { type: string, minLength: 1, maxLength: 512 }
        - name: page_size
          in: query
          description: Results per page. Alias of deprecated `limit`; provide only one.
          schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
        - name: limit
          in: query
          deprecated: true
          description: Deprecated alias of `page_size`; provide only one.
          schema: { type: integer, minimum: 1, maximum: 100 }
      responses:
        "200":
          description: Newest-first page of authorization-scoped search results
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SearchResponse"
        "400":
          description: Invalid query, filter, alias combination, date range, or pagination input
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Agent key lacks `mail:read`
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Requested workspace not found within the authenticated boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /domains:
    post:
      summary: Create a domain ownership claim
      description: |
        The authenticated organization supplies the claim boundary. Requires a
        Clerk organization admin or an organization-wide key with domains:write.
        Workspace-pinned and agent keys are denied before DNS or database work.
        Unicode names are normalized to canonical IDNA ASCII. Creating a pending
        claim does not prevent another organization from claiming or verifying
        the name. No provider mail configuration is issued.
      operationId: createDomain
      tags: [Domains]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [domain]
              properties:
                domain: { type: string }
      responses:
        "201":
          description: Pending claim with its ownership TXT challenge
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DomainWithDns"
        "400":
          description: Invalid domain input
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ValidationError"
        "409":
          description: This organization already has a claim for the canonical domain
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected domain-registration failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /domains/{id}:
    get:
      summary: Get a domain
      operationId: getDomain
      tags: [Domains]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Domain details with DNS record hints
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DomainWithDns"
        "500":
          description: Unexpected domain-read failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /domains/{id}/verify:
    post:
      summary: Verify domain ownership
      description: |
        Requires the same organization administration and domains:write authority
        as creation. Checks the exact current ownership TXT challenge. A fresh
        proof atomically transfers verified ownership from any previous claim;
        a stale or consumed generation cannot transfer it back. Challenges last
        24 hours and are consumed after successful proof. Checking an expired or
        consumed challenge first returns a new TXT value with challenge_refreshed;
        publish that value and check again. DNS unavailability leaves ownership
        unchanged. This operation never configures email or grants agent trust.
      operationId: verifyDomain
      tags: [Domains]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Updated domain plus verification result
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DomainVerificationResponse"
        "500":
          description: Unexpected domain-verification failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /domains/org/{orgId}:
    get:
      summary: List domains for an organization
      operationId: listDomainsByOrg
      tags: [Domains]
      parameters:
        - name: orgId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Domain list
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/DomainWithDns"
        "500":
          description: Unexpected domain-list failure
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /trust/{agentId}:
    get:
      summary: Get an agent trust profile
      operationId: getTrustProfile
      tags: [Trust]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      parameters:
        - name: agentId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Trust profile
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TrustProfile"

  /trust/{agentId}/recalculate:
    post:
      summary: Recalculate an agent trust score
      operationId: recalculateTrustScore
      tags: [Trust]
      parameters:
        - name: agentId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Recalculated trust score
          content:
            application/json:
              schema:
                type: object
                properties:
                  agent_id: { type: string, format: uuid }
                  trust_score: { type: integer }

  /webhooks:
    get:
      summary: List webhook subscriptions
      operationId: listWebhooks
      tags: [Webhooks]
      security:
        - ApiKeyAuth: []
      responses:
        "200":
          description: Webhook subscriptions for the authenticated org
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/WebhookSubscription"
        "403":
          description: Agent keys and workspace-pinned API keys are forbidden
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Webhook administration failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      summary: Create a webhook subscription
      operationId: createWebhook
      tags: [Webhooks]
      description: |
        Lazily ensures one Svix application for the authenticated organization,
        creates one Svix endpoint for this subscription, and returns Svix's
        signing secret once. PagerMail does not store that secret. The operation
        is organization-key-only; agent keys and workspace-pinned API keys are denied.
      security:
        - ApiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                org_id:
                  type: string
                  format: uuid
                  description: Legacy field; authenticated org is authoritative
                url:
                  type: string
                  format: uri
                  pattern: "^https://"
                  description: HTTPS endpoint URL. Credentials, fragments, malformed URLs, and other invalid endpoint shapes are rejected before Svix performs delivery.
                events:
                  type: array
                  minItems: 1
                  maxItems: 5
                  uniqueItems: true
                  description: Events to subscribe to. When omitted, the subscription receives all five events. An empty array is rejected.
                  default: [message.sent, message.received, message.delivered, message.bounced, message.complained]
                  items:
                    type: string
                    enum: [message.sent, message.received, message.delivered, message.bounced, message.complained]
      responses:
        "201":
          description: Webhook created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CreatedWebhookSubscription"
        "400":
          description: Invalid endpoint, event set, or subscription-capacity conflict
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Agent keys and workspace-pinned API keys are forbidden
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "503":
          description: Svix egress is paused because no API key is configured
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookEgressPausedError"
        "500":
          description: Webhook administration failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /webhooks/{id}:
    patch:
      summary: Update a webhook subscription
      operationId: updateWebhook
      tags: [Webhooks]
      description: |
        Updates the endpoint URL and/or the subscribed event types. The row
        update commits in one tenant transaction while the organization's
        subscription-mutation advisory key is held, and a URL change marks the
        row `pending` in that same transaction. The provider push happens after
        that commit, never inside it, and `sync_state` reports its outcome
        (`synced`, `pending` or `parked`): a retryable provider failure still
        answers `200`, and a worker converges pending rows with backoff. A
        terminal provider answer reverts the change and answers `404` (no such
        provider endpoint) or `409`, unless the row changed again or the worker
        took it over during the provider call: then nothing is reverted and the
        answer is `200` with the row as it now stands. While another operation
        is changing one of the organization's subscriptions, or the
        organization is recording an event, the answer is `409` (retry
        shortly). A lost commit acknowledgement is reconciled from the
        committed row. Returns the subscription without its signing secret.
        Organization-key-only; agent keys and workspace-pinned API keys are
        denied.
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              minProperties: 1
              additionalProperties: false
              properties:
                url:
                  type: string
                  format: uri
                  pattern: "^https://"
                  description: HTTPS endpoint URL. Credentials, fragments, malformed URLs, and other invalid endpoint shapes are rejected before Svix is called.
                events:
                  type: array
                  minItems: 1
                  maxItems: 5
                  uniqueItems: true
                  items:
                    type: string
                    enum: [message.sent, message.received, message.delivered, message.bounced, message.complained]
      responses:
        "200":
          description: Updated webhook subscription, with its provider-sync state
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookSubscriptionUpdate"
        "400":
          description: Invalid endpoint, empty body, or invalid event set
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Agent keys and workspace-pinned API keys are forbidden
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Webhook subscription not found, or the provider has no such endpoint (the change is reverted)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Webhook subscription is not active, another operation is changing one of the organization's subscriptions or the organization is recording an event (retry shortly), or the provider refused the change (the change is reverted)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "503":
          description: Svix egress is paused because no API key is configured
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookEgressPausedError"
        "500":
          description: Webhook administration failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    delete:
      summary: Delete a webhook subscription
      operationId: deleteWebhook
      tags: [Webhooks]
      description: Deletes the Svix endpoint and its PagerMail subscription. Organization-key-only; agent keys and workspace-pinned API keys are denied. If Svix egress is paused, PagerMail immediately revokes and hides the local subscription, then the bounded worker removes the provider endpoint after the key returns.
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Webhook deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted: { type: boolean }
        "403":
          description: Agent keys and workspace-pinned API keys are forbidden
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Webhook subscription not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Webhook administration failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /webhooks/{id}/replay:
    post:
      summary: Recover failed deliveries for a webhook
      operationId: replayWebhook
      tags: [Webhooks]
      description: |
        Asks Svix to resend every failed message since `since` to this endpoint.
        Pager accepts `since` up to 14 days back (a Pager product limit; the
        provider's recover payload documents no window) and never in the future;
        anything else is a `400` and Svix is not called. Only the provider
        background task's safe fields are returned. Organization-key-only; agent
        keys and workspace-pinned API keys are denied. When Svix egress is
        paused the request answers `503`.
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [since]
              properties:
                since:
                  type: string
                  format: date-time
                  description: ISO-8601 timestamp, no more than 14 days before now and not in the future.
      responses:
        "202":
          description: Recovery task accepted
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookRecoverTask"
        "400":
          description: Missing, malformed, future, or older-than-14-days `since`
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Agent keys and workspace-pinned API keys are forbidden
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Webhook subscription not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Webhook subscription is not active
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "503":
          description: Svix egress is paused because no API key is configured
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookEgressPausedError"
        "500":
          description: Webhook administration failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /webhooks/{id}/attempts:
    get:
      summary: List delivery attempts for a webhook
      operationId: listWebhookAttempts
      tags: [Webhooks]
      description: |
        One page of Svix delivery attempts for this endpoint, mapped to `id`,
        `event_id`, `status`, `response_status_code`, `timestamp`, and
        `trigger_type` only. Request and response bodies, headers, provider URLs,
        and provider error details are never returned. `iterator` is opaque;
        pass `next_iterator` back to continue, and `null` means no further
        pages. Organization-key-only; agent keys and workspace-pinned API keys
        are denied. When Svix egress is paused the request answers `503`.
      security:
        - ApiKeyAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
        - name: iterator
          in: query
          required: false
          description: Opaque iterator from a previous page's `next_iterator`.
          schema:
            type: string
            minLength: 33
            maxLength: 33
            pattern: "^atmpt_[A-Za-z0-9]{27}$"
      responses:
        "200":
          description: Attempt page
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookAttemptPage"
        "400":
          description: Invalid limit or iterator
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Agent keys and workspace-pinned API keys are forbidden
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Webhook subscription not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Webhook subscription is not active
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "503":
          description: Svix egress is paused because no API key is configured
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookEgressPausedError"
        "500":
          description: Webhook administration failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /webhooks/portal:
    post:
      summary: Create a Svix App Portal link
      operationId: createWebhookPortalLink
      tags: [Webhooks]
      description: |
        Returns a short-lived link bound to the authenticated organization's
        Svix application. Portal capabilities are limited to delivery debugging
        (viewing endpoints, the signing secret and delivery attempts, and
        resending deliveries); endpoint creation, update, and deletion remain
        available only through PagerMail's subscription API. Organization-key-only; agent keys are denied.
      security:
        - ApiKeyAuth: []
      responses:
        "200":
          description: Short-lived Svix App Portal link
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookPortalLink"
        "403":
          description: Agent keys and non-admin credentials are forbidden
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: The organization has no Svix application because it has not created a subscription
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookApplicationNotFoundError"
        "503":
          description: Svix egress is paused because no API key is configured
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookEgressPausedError"
        "500":
          description: Svix App Portal link creation failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /webhooks/org/{orgId}:
    get:
      summary: List webhook subscriptions using the legacy org-scoped alias
      operationId: listWebhooksByOrg
      tags: [Webhooks]
      security:
        - ApiKeyAuth: []
      parameters:
        - name: orgId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Webhook subscriptions for the authenticated org
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/WebhookSubscription"
        "403":
          description: Agent keys, workspace-pinned API keys, and organization mismatches are forbidden
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Webhook administration failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /webhooks/ses:
    x-pagermail-service: worker
    post:
      summary: Receive SES delivery, bounce, and complaint notifications
      operationId: handleSesWebhook
      tags: [Webhooks]
      description: >-
        Signed SNS endpoint for outbound SES events, served by the separate worker
        process when its ses_feedback mode is enabled. Configure the SNS subscription
        with the worker origin; the API process returns 404 for this path.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
      responses:
        "200":
          description: Notification processed or ignored
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true

  /inbound-quarantine:
    get:
      summary: List unresolved inbound MIME quarantine records
      operationId: listInboundMimeQuarantine
      tags: [Inbound Quarantine]
      description: |
        Administrative surface for the authenticated organization. Requires a
        wildcard/admin API key or an `org:admin` Clerk session. A workspace-pinned
        API key can list records only for inboxes in that workspace; an unpinned
        key or Clerk organization admin can list across the organization. Raw
        object keys and raw message bytes are not exposed.
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
      responses:
        "200":
          description: Bounded unresolved quarantine list
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [items]
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/InboundMimeQuarantine"
        "400":
          description: Invalid quarantine list query parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Administrator access required
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /inbound-quarantine/{id}/reprocess:
    post:
      summary: Queue an inbound MIME quarantine record for reprocessing
      operationId: reprocessInboundMimeQuarantine
      tags: [Inbound Quarantine]
      description: |
        Administrative surface for the authenticated organization. Queues one
        unresolved record for the bounded trusted-MIME reprocess loop; parsing
        never runs inline with this request. A record already pending or under
        an active processing lease is a read-only no-op that returns its current
        state without touching `last_seen_at`. If `INGEST_MODE` is not
        `trusted_mime`, a newly queued record remains durable until that mode is
        enabled and the reprocessor is running. Workspace-pinned API keys can
        access only records belonging to inboxes in their pinned workspace.
        A record the virus scanner quarantined (`error_code` beginning
        `MALWARE_`) is never released: the request returns `409` with code
        `QUARANTINE_MALWARE_NOT_RELEASABLE` and the record is left untouched.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Record was already pending or actively processing; no state was changed
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [id, status, queued]
                properties:
                  id: { type: string, format: uuid }
                  status:
                    type: string
                    enum: [pending_parse, processing_parse]
                  queued:
                    type: boolean
                    const: false
        "202":
          description: Record newly queued for background reprocessing
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [id, status, queued]
                properties:
                  id: { type: string, format: uuid }
                  status:
                    type: string
                    const: pending_parse
                  queued:
                    type: boolean
                    const: true
        "400":
          description: Invalid quarantine identifier
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Administrator access required
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Unresolved quarantine record not found within the caller's organization and workspace grant
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Quarantined malware cannot be reprocessed (code `QUARANTINE_MALWARE_NOT_RELEASABLE`); the record is unchanged
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unable to inspect or queue inbound MIME reprocessing
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /metrics:
    get:
      summary: Get organization metrics
      operationId: getMetrics
      tags: [Metrics]
      parameters:
        - name: workspace_id
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Event counts grouped by type
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MetricsResponse"

  /metrics/health-summary:
    get:
      summary: Get tenant health summary
      description: |
        Returns organization/workspace-scoped delivery, webhook, processor, and
        inbound-quarantine signals. Service-wide provider backlog,
        replica-local worker state, and database-pool pressure are intentionally
        excluded. A failed field query returns that field as null and names it
        in unavailable_fields without discarding healthy fields.
      operationId: getHealthSummary
      tags: [Metrics]
      parameters:
        - name: workspace_id
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Tenant-scoped durable health counters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OpsHealthSummary"

  /metrics/inbox/{inboxId}:
    get:
      summary: Get per-inbox metrics
      operationId: getInboxMetrics
      tags: [Metrics]
      parameters:
        - name: inboxId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Event counts for one inbox
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MetricsResponse"

  /usage:
    get:
      summary: Get plan usage
      description: |
        Returns the organization's plan and its active inboxes, custom domain
        claims and external-email sends against the plan caps. Counts cover the
        whole organization. sends covers the current UTC calendar month
        (sends_window). A limit of null means no cap. While limits_enforced is
        false the caps are reported but do not refuse requests. Organization keys
        pinned to one workspace and agent keys are refused.
      operationId: getUsage
      tags: [Metrics]
      responses:
        "200":
          description: Plan usage
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PlanUsage"

  /events/stream:
    get:
      summary: Subscribe to realtime events
      operationId: streamEvents
      tags: [Realtime Events]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      description: |
        Bounded process-local G0 Server-Sent Events stream. Cursors are opaque
        `epoch:sequence` values partitioned by organization, optional workspace,
        and authorized message/delivery capability. Other organizations,
        workspaces, and unauthorized capabilities cannot advance a cursor or
        deliver events through it. Process-wide memory ceilings are shared, but
        one organization can evict only its own inactive scopes. If it has no
        reclaimable scope, its new subscription receives `503` or its publication
        advances only its own replay floor; this interim has no per-tenant
        fair-share guarantee. Org-wide scopes include every workspace
        in that organization. Restart, replica change, inactive-scope LRU
        eviction, replay pressure, cursor-ahead, or subscriber count/byte
        overflow produces an explicit `reset_required` event. Every control and
        data event carries literal `schema_version: 1`. This endpoint does not
        provide durable replay; clients must refetch authoritative REST state
        after reset.

        Limits are 256 replay events per scope, 1,024 scopes, 16,384 total
        replay entries, 16 MiB total replay data, and 512 events/1 MiB per
        subscriber queue. An organization can evict its own inactive scopes
        least-recently-used, and those scopes receive a fresh epoch if recreated;
        active or foreign-organization scope state is never evicted. A new
        subscription returns `503` when global capacity is full and that
        organization has no inactive scope it can reclaim.
        `delivery.updated` omits provider errors and arbitrary timeline bodies.

        Agent keys require `mail:read` and MUST provide one explicit `inbox_id`.
        That inbox must be active, owned by the authenticated agent, and present
        in the key's effective inbox grant. Agent-key cursor/replay state is
        partitioned by that exact inbox, so sibling-inbox activity neither
        advances the cursor nor enters live or replay frames. Agent-key streams
        periodically revalidate the credential and inbox boundary; committed
        revocation, expiry, suspension, workspace deactivation, or inbox
        deactivation closes the connection fail-closed. Workspace-wide and
        organization-wide streams remain organization-key-only.
      parameters:
        - name: workspace_id
          in: query
          schema: { type: string, format: uuid }
        - name: inbox_id
          in: query
          description: Required for agent keys; optional for organization keys.
          schema: { type: string, format: uuid }
        - name: thread_id
          in: query
          schema: { type: string, format: uuid }
        - name: event_types
          in: query
          schema:
            oneOf:
              - type: string
              - type: array
                items: { type: string }
        - name: cursor
          in: query
          description: Opaque process-local replay cursor
          schema:
            type: string
            maxLength: 160
            pattern: "^[A-Za-z0-9_-]{1,128}:[0-9]+$"
        - name: Last-Event-ID
          in: header
          description: Opaque process-local replay cursor from a prior event
          schema:
            type: string
            maxLength: 160
            pattern: "^[A-Za-z0-9_-]{1,128}:[0-9]+$"
      responses:
        "200":
          description: |
            Process-local stream. Begins with `ready`, or with
            `reset_required` followed by close when the cursor cannot be
            honored.
          content:
            text/event-stream:
              schema:
                type: string
              examples:
                readyAndMessage:
                  summary: Versioned ready control and message event
                  value: |
                    event: ready
                    data: {"schema_version":1,"workspace_id":"2d57f50c-e1ea-49c8-905f-e154610fb2b3","inbox_id":null,"thread_id":null,"event_types":["message.received"],"cursor":"OpaqueEpoch:0","head_cursor":"OpaqueEpoch:0"}

                    id: OpaqueEpoch:1
                    event: message.received
                    data: {"schema_version":1,"id":"OpaqueEpoch:1","event_type":"message.received","occurred_at":"2026-07-31T20:00:00.000Z","org_id":"org_1","workspace_id":"2d57f50c-e1ea-49c8-905f-e154610fb2b3","inbox_id":null,"thread_id":null,"message_id":null,"delivery_id":null,"processor":null,"payload":{}}
        "400":
          description: Invalid event type, filter, or cursor format
        "403":
          description: Credential lacks the required event, workspace, or `mail:read` scope
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: Agent-key inbox or thread is not in the caller's effective boundary
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Unexpected realtime subscription failure before the stream opens
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"
        "503":
          description: Realtime capacity is temporarily unavailable
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ServiceUnavailableError"

  /webhook-events:
    get:
      summary: Poll the customer webhook event flow
      operationId: listWebhookEvents
      tags: [Webhooks]
      security:
        - ApiKeyAuth: []
        - AgentKeyAuth: []
      description: |
        Cursor-paginated alternative to receiving webhooks, available without
        Svix. It admits the same principals as the realtime stream (Clerk
        members; organization keys with `messages:read` or `deliveries:read`;
        agent keys with `mail:read`). An organization key without
        `deliveries:read` never sees `message.delivered`, `message.bounced`, or
        `message.complained`, and one without `messages:read` never sees
        `message.received` or `message.sent`. A workspace-pinned key only sees
        its workspace, and an agent key only inboxes it can see; an explicit
        `workspace_id` outside the caller's reach is a `403` and an explicit
        `inbox_id` outside it is a `404`, not an empty page.

        Without a cursor the page starts at the first event in the caller's
        visible set, ordered by commit transaction and event id. A page examines
        at most 1,000 index rows: a full page resumes at its last returned row,
        otherwise the cursor advances past every row examined, so `caught_up`
        is `true` — and `next_cursor` then echoes the request cursor — only once
        nothing more is visible. Cursors are opaque and signed, binding the
        organization, principal, workspace pin, and filters; they have the shape
        `<hex>.<64 hex>` and at most 4,161 bytes, and a tampered, foreign,
        malformed or NUL-containing cursor is a `400`. Held messages appear only
        after they are released. This endpoint does not use Svix and keeps
        working while webhook egress is paused.
      parameters:
        - name: workspace_id
          in: query
          schema: { type: string, format: uuid }
        - name: inbox_id
          in: query
          schema: { type: string, format: uuid }
        - name: cursor
          in: query
          description: Opaque cursor from a previous page's `next_cursor`.
          schema:
            type: string
            maxLength: 4161
            pattern: "^[0-9a-f]{1,4096}\\.[0-9a-f]{64}$"
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
      responses:
        "200":
          description: Webhook event page
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookEventPage"
        "400":
          description: Invalid cursor, limit, or filter shape
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          description: Credential lacks the required scope, or the workspace_id filter is outside its reach
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/AgentScopeForbiddenError"
        "404":
          description: The inbox_id filter names an inbox the caller cannot see, or one that does not exist
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "500":
          description: Webhook event polling failed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerError"

  /ingest/email:
    x-pagermail-service: ingress
    post:
      summary: Ingest inbound email in JSON form
      operationId: ingestEmail
      tags: [Ingestion]
      description: |
        Served only by the isolated ingress service (never the API), and only
        when that service runs `PAGERMAIL_INGRESS_MODE=trusted_json`. Requests
        present one operator-issued per-integration `pmi_` credential via
        bearer auth or `X-PagerMail-Ingest-Token`; the database validates it
        and its provider/account/environment binding and canonical scope. Before message persistence, an active
        provisional inbox reserves one of five lifetime attempts and the
        bounded JSON input bytes against a 20 MiB lifetime ceiling. Expired,
        reaped, and exhausted provisional inboxes share the unavailable
        recipient response; verified and non-provisional inboxes are unchanged.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from, to, subject]
              properties:
                from: { type: string }
                to: { type: string }
                subject: { type: string, maxLength: 998 }
                body_text: { type: string }
                body_html: { type: string }
                message_id: { type: string }
      responses:
        "200":
          description: Existing message replayed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/IngestResult"
        "201":
          description: Message ingested
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/IngestResult"
        "404":
          description: Adapter is unmounted, recipient is unavailable, or provisional inbound admission is closed
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/RouteNotFoundError"
                  - $ref: "#/components/schemas/Error"

  /ingest/mime:
    x-pagermail-service: ingress
    post:
      summary: Ingest a raw MIME email
      operationId: ingestMime
      tags: [Ingestion]
      description: |
        Served only by the isolated ingress service (never the API), and only
        when that service runs `PAGERMAIL_INGRESS_MODE=trusted_mime`. Requests
        present one operator-issued per-integration `pmi_` credential via
        bearer auth or `X-PagerMail-Ingest-Token`. The authenticated integration must provide
        the SMTP envelope recipient and its stable provider receipt ID in
        headers; RFC `To` and `Message-ID` fields are content only.
        After authentication, header validation, and inbox lookup, PagerMail
        first reserves active provisional capacity, then streams the body in
        bounded chunks through an audit-visible staging
        object, enforcing 10 MiB and computing SHA-256 before finalizing the
        content-addressed original and recording `PENDING_PARSE`. Acceptance
        neither acquires background parser capacity nor uses the generic
        API/webhook request-count limiters. A separate 32-slot FIFO bounds
        active acceptance streams. Ordinary excess waits; a 256-request,
        nine-second waiting boundary returns `503` only when sustained load
        would otherwise retain socket state beyond the relay budget. A valid
        `Content-Length` is reserved and enforced exactly; a missing length
        reserves the full 10 MiB ceiling. Every delivery attempt consumes one
        of five lifetime provisional attempts and is not deduplicated for this
        storage bound. Total provisional reservations cannot exceed 20 MiB.
      security: []
      parameters:
        - in: header
          name: X-PagerMail-Envelope-Recipient
          required: true
          schema: { type: string, format: email, maxLength: 254 }
        - in: header
          name: X-PagerMail-Provider-Message-Id
          required: true
          schema: { type: string, minLength: 1, maxLength: 256 }
      requestBody:
        required: true
        content:
          application/octet-stream:
            schema:
              type: string
              format: binary
          message/rfc822:
            schema:
              type: string
              format: binary
      responses:
        "200":
          description: Previously processed provider receipt replayed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InboundMimeAcceptance"
        "202":
          description: Original bytes and pending-parse evidence durably accepted
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InboundMimeAcceptance"
        "400":
          description: Missing or invalid authority headers, or an empty MIME body
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          description: Missing, unknown, revoked, expired or binding-mismatched integration credential (uniform)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Trusted MIME mode is not selected, the recipient is unavailable, or provisional inbound admission is closed
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/RouteNotFoundError"
                  - $ref: "#/components/schemas/Error"
        "409":
          description: Provider receipt conflicts with retained evidence or an ambiguous pre-021 identity
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          description: Raw MIME body exceeds the 10 MiB acceptance limit
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "415":
          description: Unsupported raw MIME media type
        "503":
          description: Bounded trusted-MIME acceptance wait queue or deadline exhausted
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /ingest/ses:
    x-pagermail-service: ingress
    post:
      summary: Ingest an SES inbound SNS notification
      operationId: ingestSes
      tags: [Ingestion]
      description: |
        Served only by the isolated ingress service (never the API), and only
        when that service runs `PAGERMAIL_INGRESS_MODE=ses`. PagerMail verifies
        the SNS signature, topic and freshness; only then does the service
        present its operator-issued SES integration credential to the
        database. Caller-supplied ingest credentials are not accepted here. Before message or attachment persistence, an
        active provisional inbox reserves one of five lifetime attempts and
        the bounded notification-content bytes against a 20 MiB ceiling.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
      responses:
        "200":
          description: Subscription confirmed or existing message replayed
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true
        "201":
          description: SES email ingested
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/IngestResult"
        "404":
          description: Adapter is unmounted, recipient is unavailable, or provisional inbound admission is closed
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/RouteNotFoundError"
                  - $ref: "#/components/schemas/Error"

  # --- Root-level endpoints (outside /api) ---

  /livez:
    servers:
      - url: https://api.pager.ai
        description: Production (root)
      - url: http://localhost:3100
        description: Local development (root)
    get:
      summary: Process liveness
      operationId: getLiveness
      tags: [Health]
      security: []
      description: |
        Root-level dependency-free process probe (not under `/api`). A `200`
        response does not imply that dependencies are ready.
      responses:
        "200":
          description: HTTP process is alive
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status:
                    type: string
                    enum: [alive]
        "503":
          description: Not returned by application dependency checks; infrastructure may synthesize this response

  /admissionz:
    servers:
      - url: https://api.pager.ai
        description: Production (root)
      - url: http://localhost:3100
        description: Local development (root)
    get:
      summary: API authority and schema admission
      operationId: getAdmission
      tags: [Health]
      security: []
      description: |
        Bounded platform probe for PostgreSQL connectivity, the current migration
        manifest/catalog, API role and resolver authority, and process drain.
        Auxiliary DNS and object-store outages remain visible on `/readyz` and
        dependent routes; core routes can continue while admission is safe.
        The sanitized response contains only `ready` or `not_ready`.
      responses:
        "200":
          description: API admission is safe
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReadinessResponse"
        "503":
          description: Database, schema, authority or drain refuses admission
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReadinessResponse"

  /readyz:
    servers:
      - url: https://api.pager.ai
        description: Production (root)
      - url: http://localhost:3100
        description: Local development (root)
    get:
      summary: Dependency and configuration readiness
      operationId: getReadiness
      tags: [Health]
      security: []
      description: |
        Root-level full diagnostic probe (not under `/api`). Checks the current
        database migration manifest/catalog and API authority, object-store mode
        and availability, provider configuration, DNS observer, and drain state.
        The bounded S3-compatible check reads bucket metadata without writing
        objects. Provider configuration checks do not send mail. NATS is not a
        dependency. Production local storage and the console provider are not ready.
        The public response exposes only `ready` or `not_ready`. Probes are
        single-flighted and cached for one second. Railway and API request
        admission use `/admissionz`; auxiliary failure here does not refuse every
        core request. Dependent routes retain their own dependency errors.
      responses:
        "200":
          description: Instance is ready to receive traffic
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReadinessResponse"
        "503":
          description: A required dependency or configuration check failed; dependency details are not exposed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReadinessResponse"

  /identity-readyz:
    servers:
      - url: https://api.pager.ai
        description: Production (root)
      - url: http://localhost:3100
        description: Local development (root)
    get:
      summary: Clerk identity-boundary readiness
      operationId: getIdentityReadiness
      tags: [Health]
      security: []
      description: |
        Root-level dedicated identity probe (not under `/api`). It checks the
        continuous Clerk registry through the authenticated internal
        provisioner hop. A failure blocks Clerk login and signup but does not
        change `/readyz`, which remains the API-key and inbound-mail readiness
        signal. The response contains no provider or credential detail.
      responses:
        "200":
          description: Clerk identity synchronization is ready
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReadinessResponse"
        "503":
          description: The provisioner or Clerk identity registry is unavailable
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ReadinessResponse"

tags:
  - name: Signup
    description: Default-off agent and Clerk onboarding through one provisioner
  - name: Capabilities
    description: Provider-neutral environment capability discovery
  - name: Session
    description: Authenticated API key context
  - name: API Keys
    description: API key generation and management
  - name: Workspaces
    description: Workspace creation and access control
  - name: Agents
    description: Agent principals and identity
  - name: Inboxes
    description: Inbox endpoints owned by agents
  - name: Threads
    description: Thread retrieval and inbox thread listings
  - name: Messages
    description: Message retrieval, sending, labeling, and processor actions
  - name: Attachments
    description: Attachment download endpoints
  - name: Drafts
    description: Draft creation, updates, and sending
  - name: Deliveries
    description: Delivery inspection and debugging
  - name: Ingestion
    description: Inbound provider adapters served by the isolated ingress service, one mode per deployment
  - name: Inbound Quarantine
    description: Administrator-only inspection and reprocessing of retained inbound MIME
  - name: Search
    description: Full-text message search
  - name: Domains
    description: Domain registration and verification
  - name: Trust
    description: Agent trust scoring and events
  - name: Webhooks
    description: Webhook subscriptions and SES event intake
  - name: Metrics
    description: Message metrics and operational health summaries
  - name: Realtime Events
    description: Server-Sent Events subscription endpoint
  - name: Health
    description: Root-level liveness and readiness probes (no auth)
