openapi: 3.1.0
info:
  title: Anjal API
  version: "1.0.0"
  description: |
    Anjal is a multi-tenant email API for AI agents.

    Create inboxes on the default `@send.anjal.app` domain or your own custom
    domains, send and receive mail, manage drafts, subscribe to real-time
    events over WebSocket, and isolate resources across workspaces so your
    reseller customers can serve their own end-customers under a single
    billing relationship.

    Install the TypeScript SDK: `npm install anjal`
    ([npm](https://www.npmjs.com/package/anjal))

    MCP server for Claude Desktop / Cursor: `npx -y anjal-mcp`
    ([npm](https://www.npmjs.com/package/anjal-mcp))

    ## Authentication

    Every request is authenticated with the `X-API-Key` header (or
    `Authorization: Bearer <key>`). Four key prefixes, each with increasing
    scope:

    | Prefix   | Scope                                   | Use it for                              |
    |----------|-----------------------------------------|-----------------------------------------|
    | `sa_...` | Super admin                             | Tenant lifecycle (platform operator)    |
    | `tk_...` | Tenant master                           | Everything in your tenant across workspaces |
    | `wk_...` | Workspace master                        | One workspace only                      |
    | `ak_...` | Inbox (agent) scoped                    | One inbox — its messages, drafts, lists |

    ## Resource hierarchy

    ```
    Tenant (billing root)
    └── Workspace  (isolation container)
        ├── Inboxes
        │   ├── Messages / Threads / Attachments
        │   ├── Drafts
        │   └── Lists
        └── Domains
    ```

    ## Sending mail

    Mail is sent via `POST /v1/inboxes/{id}/send`. Replies go through
    `/reply/{messageId}`, reply-all through `/reply-all/{messageId}`, and
    forwards through `/forward/{messageId}`. The `From` header always uses
    the inbox's **primary alias** — add a custom-domain address with
    `POST /v1/inboxes/{id}/addresses` to change it.

    ### Safe retries (Idempotency-Key)

    Every send endpoint (`/send`, `/reply`, `/reply-all`, `/forward` and
    `POST /v1/inboxes/{id}/drafts/{did}/send`) accepts an `Idempotency-Key`
    header. Send a unique value (a UUID works) and retry freely: the first
    request sends and stores its response; a retry with the same key and the
    identical request returns that stored response with the header
    `Idempotent-Replayed: true` and sends nothing.

    | Situation | Result |
    |---|---|
    | Same key, different request (body, inbox or endpoint) | `409 IDEMPOTENCY_KEY_REUSED` |
    | Same key while the first request is still running | `409 IDEMPOTENCY_IN_PROGRESS` |
    | Header present but blank, or longer than 255 characters | `400 IDEMPOTENCY_KEY_INVALID` |
    | The first send failed (non-2xx) | The key is freed; retry with the same key |

    Keys are scoped to your account and expire after 24 hours.

    ### Labels, open tracking, scheduled send

    - **Labels**: pass `labels` (array, or a comma-separated string) on any
      send, reply, reply-all, forward or draft. Change them later with
      `PATCH /v1/inboxes/{id}/messages/{messageId}` or
      `PATCH /v1/inboxes/{id}/threads/{threadId}`, and filter lists with
      `?labels=a,b`. Labels are stored lowercase and deduplicated; at most 32
      per message, each at most 64 characters, no commas.
    - **Open tracking**: `trackOpens: true` on a send with an HTML body adds a
      1x1 pixel (the stored copy never contains it). The first open fires
      `message.opened`. Opens are a hint, not proof: Apple Mail Privacy
      Protection fetches images on delivery, and clients that block images
      never report an open.
    - **Scheduled send**: set `sendAt` on a draft and Anjal sends it at that
      time. See the Drafts endpoints.
    - **Delivery status**: sent messages carry `deliveryStatus`
      (`delivered`, `bounced`, `complained` or `rejected`; null until known)
      and `deliveredAt`.

    ## Receiving mail

    Inbound mail arrives via SMTP on the default domain or any verified
    custom domain. Subscribe to delivery events either by registering a
    webhook (`POST /v1/webhooks`) or by opening a WebSocket
    (`wss://anjal.app/v1/ws`) — useful for in-line 2FA flows where
    the agent doesn't have a public webhook receiver.

servers:
  - url: https://anjal.app
    description: Production

tags:
  - name: Workspaces
    description: Isolated containers under a tenant. Hand scoped keys to your resellers so their customers cannot see each other.
  - name: Inboxes
    description: Email mailboxes that can send, receive, and store threads.
  - name: Addresses
    description: Multiple accepted addresses per inbox. Add a custom-domain alias to change the outbound From without losing thread history.
  - name: Messages
    description: Send, reply, forward, list, and download messages.
  - name: Drafts
    description: Compose messages across multiple agent turns and send atomically.
  - name: Lists
    description: Named groups of recipient addresses per inbox.
  - name: Domains
    description: Bring your own sending domain. Returns DNS records, verification state, and a BIND zone file export.
  - name: Webhooks
    description: HTTP callbacks fired on every inbox event.
  - name: WebSocket
    description: Real-time event stream. The agentmail.to spec-compatible wire protocol.
  - name: Metrics
    description: Programmatic counters scoped by workspace or inbox.
  - name: Tenants
    description: Super-admin only — platform operator endpoints.
  - name: LinkedIn — Sessions
    description: |
      Login on behalf of the customer (email + password, with PIN or mobile-app
      verification challenge support), or import existing cookies. Cookies are
      AES-256-GCM encrypted at rest. Each session is tenant-scoped.
  - name: LinkedIn — Outreach
    description: |
      Profile lookup, connection requests, keyword post search. Each call is
      logged and counted against a per-session daily quota (LinkedIn rate-limits
      per account, not per IP).
  - name: LinkedIn — Signals
    description: |
      Deterministic real-time intent watchers. Every signal is a keyword
      plus a plain-English firing rule (e.g. "Flag as ready when the
      author is a founder complaining about cold email — skip vendors and
      agencies"). Two-pass classifier:

        1. Triage — text-only LLM scores each post 0–100; obvious rejects
           drop without paying any LinkedIn quota.
        2. Verify — survivors get a profile lookup (cached, multi-session
           routed) and the full classifier runs with the author's role +
           company as authoritative context. The firing rule decides
           engage/intent, the reason cites evidence from the post.

      Sessions auto-distribute — by default polling spreads across all
      healthy LinkedIn sessions for the tenant, multiplying daily
      throughput by the number of connected accounts. Pass a specific
      sessionId on the create body to pin instead.

      Optional HMAC-signed webhook delivery with automatic retries.
      Auditable end-to-end.
  - name: LinkedIn — Searches
    description: |
      Deterministic historical search across past-24h | past-week |
      past-month. Synchronous — returns the full hit list inline with the
      same structured output shape as signals (post + author +
      classification + cited reason). The plain-English firing rule
      filters to *exactly* what the buyer means; the keyword is a coarse
      pre-filter. Persisted server-side so the result set can be re-opened
      without spending another LinkedIn quota.

security:
  - apiKeyHeader: []

components:
  securitySchemes:
    apiKeyHeader:
      type: apiKey
      in: header
      name: X-API-Key
      description: |
        Any of `sa_`, `tk_`, `wk_`, `ak_`, or `mam_` keys. Scope is enforced
        per-endpoint — see individual operation descriptions.
  parameters:
    InboxId:
      name: id
      in: path
      required: true
      schema: { type: string, format: uuid }
      description: Inbox UUID
    WorkspaceId:
      name: id
      in: path
      required: true
      schema: { type: string, format: uuid }
      description: Workspace UUID
    MessageId:
      name: messageId
      in: path
      required: true
      schema: { type: string, format: uuid }
      description: Message UUID
    DraftId:
      name: did
      in: path
      required: true
      schema: { type: string, format: uuid }
      description: Draft UUID
    ListId:
      name: lid
      in: path
      required: true
      schema: { type: string, format: uuid }
      description: List UUID
    AttachmentId:
      name: aid
      in: path
      required: true
      schema: { type: string, format: uuid }
      description: Attachment UUID
    DomainName:
      name: domain
      in: path
      required: true
      schema: { type: string, example: "mail.example.com" }
      description: Fully-qualified domain name
    LimitQuery:
      name: limit
      in: query
      schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
    OffsetQuery:
      name: offset
      in: query
      schema: { type: integer, minimum: 0, default: 0 }
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      schema: { type: string, minLength: 1, maxLength: 255 }
      description: |
        Unique value for this send (e.g. a UUID). A retry with the same key and
        identical request returns the stored response (header
        `Idempotent-Replayed: true`) and sends nothing. Same key with a
        different request: 409 `IDEMPOTENCY_KEY_REUSED`. Same key while the
        first is still running: 409 `IDEMPOTENCY_IN_PROGRESS`. Blank: 400
        `IDEMPOTENCY_KEY_INVALID`. Keys are per account and expire after 24
        hours; a failed send (non-2xx) frees the key.
    LabelsQuery:
      name: labels
      in: query
      description: Comma-separated labels, e.g. `needs-review,billing`. Only results carrying every one are returned.
      schema: { type: string }
    IncludeSpamQuery:
      name: includeSpam
      in: query
      description: Spam is stored but left out by default. Pass `true` to include it (`include_spam` also works).
      schema: { type: boolean, default: false }
  responses:
    Unauthorized:
      description: Missing or invalid API key
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    NotFound:
      description: Resource not found
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    ValidationError:
      description: Request body failed schema validation
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    Conflict:
      description: Resource already exists
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    IdempotencyConflict:
      description: |
        `IDEMPOTENCY_KEY_REUSED` (the key was used for a different request) or
        `IDEMPOTENCY_IN_PROGRESS` (the first request with this key is still running).
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
  schemas:
    Labels:
      description: |
        Labels as an array or a comma-separated string. Stored lowercase and
        deduplicated; at most 32 labels of at most 64 characters, no commas.
      oneOf:
        - { type: array, maxItems: 32, items: { type: string, maxLength: 64 } }
        - { type: string }
      example: ["needs-review", "q4-campaign"]

    SendExtras:
      type: object
      properties:
        labels: { $ref: "#/components/schemas/Labels" }
        trackOpens:
          type: boolean
          default: false
          description: |
            Add a 1x1 open-tracking pixel (HTML body only; `track_opens` also
            works). The stored copy never contains it. The first open fires
            `message.opened`. A hint, not proof: Apple Mail Privacy Protection
            prefetches images and some clients block them.

    Error:
      type: object
      properties:
        error: { type: string }
        code: { type: string, example: "VALIDATION_ERROR" }
      required: [error]

    # ── LinkedIn signal webhook payloads ────────────────────────────
    # These are the JSON bodies POSTed to a signal's webhookUrl when
    # a match fires. Headers on every delivery:
    #   Content-Type: application/json
    #   User-Agent: MyAgentMail-Webhook/1.0
    #   X-MyAgentMail-Event: <signal.match | signal.engagement | signal.job_change | signal.connection_accepted | signal.message_received>
    #   X-MyAgentMail-Delivery-Id: <uuid>
    #   X-MyAgentMail-Match-Id: <uuid>
    #   X-MyAgentMail-Signature: v1=<hex>     # HMAC-SHA256 of the raw body using the signal's webhookSecret
    #
    # All five payload variants share these keys:
    #   type   — the X-MyAgentMail-Event value, also in body for non-header consumers
    #   signal — { id, name, ... }
    #   match  — { id, foundAt }
    LinkedInSignalWebhookPayload:
      oneOf:
        - $ref: "#/components/schemas/SignalKeywordMatch"
        - $ref: "#/components/schemas/SignalEngagementMatch"
        - $ref: "#/components/schemas/SignalJobChangeMatch"
        - $ref: "#/components/schemas/SignalConnectionAccepted"
        - $ref: "#/components/schemas/SignalMessageReceived"
      discriminator:
        propertyName: type
        mapping:
          signal.match:                "#/components/schemas/SignalKeywordMatch"
          signal.engagement:           "#/components/schemas/SignalEngagementMatch"
          signal.job_change:           "#/components/schemas/SignalJobChangeMatch"
          signal.connection_accepted:  "#/components/schemas/SignalConnectionAccepted"
          signal.message_received:     "#/components/schemas/SignalMessageReceived"

    SignalKeywordMatch:
      type: object
      description: |
        Fired by `kind=keyword` signals. The payload carries everything
        the keyword runner already had in memory at fire time so
        consumers don't need to re-scrape or re-enrich.

        **Field availability:**
        - `author.name|profileUrl|headline|title|companyName` —
          populated when the signal-runner's profile-cache lookup
          succeeded. `author.title` and `author.companyName` are
          parsed from the LinkedIn headline (e.g. "Founder @ Acme" →
          title="Founder", companyName="Acme").
        - `author.location` — populated when profile cache had it.
        - `author.followerCount` — reserved field, always null today.
          Intent is binary — a post from someone in active pain is
          valuable regardless of audience size. If your downstream
          pipeline has a real use case that needs this, tell us and
          we'll build the extractor; otherwise treat it as
          documented-for-future-expansion.
        - `post.publishedAt` — best-effort absolute timestamp parsed
          from LinkedIn's relative-time string ("2h"/"3d"/"1mo"),
          precise to the minute, may drift a few minutes vs. the
          true value. Use as a recency hint, not a forensic timestamp.
        - `post.engagement.{likes,comments,shares}` — reserved fields,
          always null today. Engagement count is a popularity signal,
          not an intent signal — a 0-like post from a frustrated
          founder is just as actionable as a 1000-like one. Same
          posture as followerCount: tell us if you actually need it
          and we'll build it.

        **Back-compat aliases** (will stay until at least 2026-Q3):
        `author.role` mirrors `author.title`; `author.company`
        mirrors `author.companyName`; `post.postedAt` mirrors
        `post.publishedAt`. New consumers should use the structured
        names.
      required: [type, signal, match, post, author, classification]
      properties:
        type:    { type: string, enum: [signal.match] }
        signal:
          type: object
          properties:
            id:    { type: string }
            name:  { type: string }
            query: { type: string }
        match:
          type: object
          properties:
            id:      { type: string }
            foundAt: { type: string, format: date-time }
        post:
          type: object
          properties:
            url:          { type: string, format: uri }
            excerpt:      { type: string }
            publishedAt:  { type: string, format: date-time, nullable: true, description: "Absolute ISO timestamp parsed from LinkedIn's relative-time string." }
            postedAt:     { type: string, format: date-time, nullable: true, description: "DEPRECATED alias of publishedAt; kept for back-compat." }
            engagement:
              type: object
              description: |
                Post-level engagement counts. Reserved fields — always
                null today. Not populated by design: engagement count
                is a popularity signal, not an intent signal. If you
                have a real use case that needs these, ask and we'll
                build the extractor.
              properties:
                likes:    { type: integer, nullable: true, description: "Always null. See parent description." }
                comments: { type: integer, nullable: true, description: "Always null. See parent description." }
                shares:   { type: integer, nullable: true, description: "Always null. See parent description." }
        author:
          type: object
          properties:
            name:          { type: string }
            profileUrl:    { type: string, format: uri }
            headline:      { type: string, nullable: true }
            title:         { type: string, nullable: true, description: "Parsed role from the LinkedIn headline." }
            companyName:   { type: string, nullable: true, description: "Parsed company from the LinkedIn headline." }
            location:      { type: string, nullable: true }
            followerCount: { type: integer, nullable: true, description: "Reserved field — always null today. Not populated by design: a post from someone in active pain is valuable regardless of audience size. Ask if you have a real use case." }
            role:          { type: string, nullable: true, description: "DEPRECATED alias of title." }
            company:       { type: string, nullable: true, description: "DEPRECATED alias of companyName." }
        classification:
          type: object
          properties:
            engage: { type: boolean }
            intent: { type: string, enum: [low, medium, high] }
            reason: { type: string }

    SignalEngagementMatch:
      type: object
      description: Fired by `kind=engagement` signals.
      required: [type, signal, match, target, post, engager, classification]
      properties:
        type:    { type: string, enum: [signal.engagement] }
        signal:
          type: object
          properties:
            id:   { type: string }
            name: { type: string }
            kind: { type: string, enum: [engagement] }
        match:
          type: object
          properties:
            id:      { type: string }
            foundAt: { type: string, format: date-time }
        target:
          type: object
          properties:
            kind:  { type: string, enum: [profile, company] }
            url:   { type: string, format: uri }
            label: { type: string, nullable: true }
        post:
          type: object
          properties:
            url:      { type: string, format: uri }
            excerpt:  { type: string }
            postedAt: { type: string, format: date-time, nullable: true }
        engager:
          type: object
          description: Same author-field shape as `SignalKeywordMatch.author` plus engagement-specific fields. `role`/`company` are deprecated aliases.
          properties:
            name:          { type: string }
            profileUrl:    { type: string, format: uri }
            headline:      { type: string, nullable: true }
            title:         { type: string, nullable: true }
            companyName:   { type: string, nullable: true }
            location:      { type: string, nullable: true }
            followerCount: { type: integer, nullable: true }
            role:          { type: string, nullable: true, description: "DEPRECATED alias of title." }
            company:       { type: string, nullable: true, description: "DEPRECATED alias of companyName." }
            action:        { type: string, enum: [commented, reacted] }
            commentText:   { type: string, nullable: true }
        classification: { $ref: "#/components/schemas/SignalKeywordMatch/properties/classification" }

    SignalJobChangeMatch:
      type: object
      description: Fired by `kind=job_change_watchlist` signals.
      required: [type, signal, match, person, change, classification]
      properties:
        type:   { type: string, enum: [signal.job_change] }
        signal:
          type: object
          properties:
            id:   { type: string }
            name: { type: string }
            kind: { type: string, enum: [job_change_watchlist] }
        match:
          type: object
          properties:
            id:      { type: string }
            foundAt: { type: string, format: date-time }
        person:
          type: object
          properties:
            name:          { type: string }
            profileUrl:    { type: string, format: uri }
            headline:      { type: string, nullable: true }
            location:      { type: string, nullable: true }
            followerCount: { type: integer, nullable: true }
        change:
          type: object
          properties:
            oldRole:    { type: string, nullable: true }
            oldCompany: { type: string, nullable: true }
            newRole:    { type: string }
            newCompany: { type: string }
        classification: { $ref: "#/components/schemas/SignalKeywordMatch/properties/classification" }

    SignalConnectionAccepted:
      type: object
      description: |
        Fired by `kind=connection_accepted` signals. No classification
        block — every new connection fires by definition. The
        `connection.attribution` field tells you whether this was an
        acceptance of an invitation YOU sent (`outbound` — looked up
        in linkedin_invitations_sent) or a cold inbound add (`inbound`).
        Customers' webhook handlers can branch on this.
      required: [type, signal, match, connection]
      properties:
        type:   { type: string, enum: [signal.connection_accepted] }
        signal:
          type: object
          properties:
            id:   { type: string }
            name: { type: string }
            kind: { type: string, enum: [connection_accepted] }
        match:
          type: object
          properties:
            id:      { type: string }
            foundAt: { type: string, format: date-time }
        connection:
          type: object
          properties:
            profileUrn:    { type: string, example: "urn:li:fsd_profile:ACoAAA..." }
            name:          { type: string }
            profileUrl:    { type: string, format: uri }
            headline:      { type: string, nullable: true }
            location:      { type: string, nullable: true }
            followerCount: { type: integer, nullable: true }
            connectedAt:   { type: string, format: date-time, nullable: true }
            attribution:   { type: string, enum: [outbound, inbound] }

    SignalMessageReceived:
      type: object
      description: |
        Fired by `kind=message_received` signals. The runner only fires
        on messages NOT sent by the viewer — your own outbound DMs are
        suppressed. When a new chat's first message comes from someone
        you previously sent an invitation to, the runner ALSO fans out
        to any `connection_accepted` signals on the same session
        (realtime acceptance shortcut).
      required: [type, signal, match, message, sender]
      properties:
        type:   { type: string, enum: [signal.message_received] }
        signal:
          type: object
          properties:
            id:   { type: string }
            name: { type: string }
            kind: { type: string, enum: [message_received] }
        match:
          type: object
          properties:
            id:      { type: string }
            foundAt: { type: string, format: date-time }
        message:
          type: object
          properties:
            messageUrn:   { type: string, example: "urn:li:msg_message:..." }
            text:         { type: string }
            deliveredAt:  { type: string, format: date-time, nullable: true }
        sender:
          type: object
          properties:
            name:          { type: string }
            profileUrl:    { type: string, format: uri }
            headline:      { type: string, nullable: true }
            location:      { type: string, nullable: true }
            followerCount: { type: integer, nullable: true }

    Workspace:
      type: object
      properties:
        id: { type: string, format: uuid }
        name: { type: string, example: "Recruiter Corp" }
        slug: { type: string, example: "recruiter-corp" }
        isDefault: { type: boolean }
        inboxCount: { type: integer }
        domainCount: { type: integer }
        createdAt: { type: string, format: date-time }
      required: [id, name, slug, isDefault]

    WorkspaceKey:
      type: object
      properties:
        id: { type: string, format: uuid }
        key:
          type: string
          description: Plain-text key — only returned on creation. Store it somewhere safe.
          example: "wk_REDACTED_EXAMPLE_KEY_DO_NOT_USE"
        prefix: { type: string, example: "wk_REDACT" }
        name: { type: string }
        workspaceId: { type: string, format: uuid }
        createdAt: { type: string, format: date-time }

    Inbox:
      type: object
      properties:
        id: { type: string, format: uuid }
        email:
          type: string
          description: Current primary outbound address — may be a custom-domain alias.
          example: "scout-abc123@delegated.cc"
        canonicalEmail:
          type: string
          description: Stable identity used for IMAP/SMTP auth. Never changes after creation.
          example: "scout-abc123-10deac42@send.anjal.app"
        username: { type: string }
        domain: { type: string }
        displayName: { type: string }
        workspaceId: { type: string, format: uuid }
        addresses:
          type: array
          items: { $ref: "#/components/schemas/InboxAddress" }
        imapPassword:
          type: string
          description: Only returned on creation and GET /inboxes/{id}. Stored plaintext so IMAP clients can log in.
        imap: { $ref: "#/components/schemas/ImapCreds" }
        smtp: { $ref: "#/components/schemas/SmtpCreds" }
        createdAt: { type: string, format: date-time }

    InboxAddress:
      type: object
      properties:
        address: { type: string, example: "scout-abc123@delegated.cc" }
        isPrimary: { type: boolean }

    ImapCreds:
      type: object
      properties:
        host: { type: string, example: "imap.anjal.app" }
        port: { type: integer, example: 993 }
        tls: { type: boolean }
        username: { type: string }
        password: { type: string }

    SmtpCreds:
      type: object
      properties:
        host: { type: string, example: "smtp.anjal.app" }
        port: { type: integer, example: 587 }
        starttls: { type: boolean }
        username: { type: string }
        password: { type: string }

    Message:
      type: object
      properties:
        id: { type: string, format: uuid }
        direction: { type: string, enum: [inbound, outbound] }
        from: { type: string }
        to: { type: string }
        subject: { type: string }
        plainBody: { type: string, nullable: true }
        htmlBody: { type: string, nullable: true }
        isRead: { type: boolean }
        threadId: { type: string, format: uuid, nullable: true }
        messageIdHeader: { type: string, nullable: true }
        inReplyTo: { type: string, nullable: true }
        receivedAt: { type: string, format: date-time }
        labels:
          type: array
          items: { type: string }
          description: Lowercase labels on this message.
        isSpam:
          type: boolean
          description: Flagged by the spam filter. Spam is left out of lists unless `includeSpam=true`.
        deliveryStatus:
          type: string
          nullable: true
          enum: [delivered, bounced, complained, rejected, null]
          description: |
            Outbound only. `delivered` means the recipient's mail server
            accepted it (not a guarantee of inbox placement). Null until known.
        deliveredAt:
          type: string
          format: date-time
          nullable: true
          description: When the recipient's mail server accepted the message (outbound only).
        firstOpenedAt:
          type: string
          format: date-time
          nullable: true
          description: |
            Time of the first open (outbound sends with `trackOpens: true`
            only). NULL until the first open. Opens are a hint, not proof:
            Apple Mail Privacy Protection fetches images on delivery, and
            clients that block images never report an open.
        lastOpenedAt:
          type: string
          format: date-time
          nullable: true
          description: Most recent open event. Updates on every open.
        openCount:
          type: integer
          default: 0
          description: Total opens. Subject to the same caveats as the timestamps.
        firstClickedAt:
          type: string
          format: date-time
          nullable: true
          description: |
            Timestamp of the first recipient link-click. Reliable signal of
            engagement (unlike opens, click events are not Apple-MPP-poisoned).
            NULL until the first click.
        lastClickedAt:
          type: string
          format: date-time
          nullable: true
        clickCount:
          type: integer
          default: 0
        attachments:
          type: array
          items: { $ref: "#/components/schemas/AttachmentMeta" }

    AttachmentMeta:
      type: object
      properties:
        id: { type: string, format: uuid }
        filename: { type: string }
        contentType: { type: string, example: "application/pdf" }
        sizeBytes: { type: integer }
        inline:
          type: boolean
          description: |
            Present and true when `htmlBody` embedded this attachment as an inline
            image and `?inlineImages=refs` replaced it with `attachment:<id>`.

    Thread:
      type: object
      properties:
        threadId: { type: string, format: uuid }
        subject: { type: string }
        messageCount: { type: integer }
        firstMessageAt: { type: string, format: date-time }
        lastMessageAt: { type: string, format: date-time }
        labels:
          type: array
          items: { type: string }
          description: Every label carried by any message in the thread.
        hasSpam:
          type: boolean
          description: Present (true) only when the thread contains spam, which happens with `includeSpam=true`.

    Draft:
      type: object
      properties:
        id: { type: string, format: uuid }
        inboxId: { type: string, format: uuid }
        to: { type: array, items: { type: string, format: email } }
        cc: { type: array, items: { type: string, format: email } }
        bcc: { type: array, items: { type: string, format: email } }
        subject: { type: string }
        plainBody: { type: string, nullable: true }
        htmlBody: { type: string, nullable: true }
        replyToMessageId: { type: string, format: uuid, nullable: true }
        labels:
          type: array
          items: { type: string }
          description: Applied to the message when the draft is sent.
        sendAt:
          type: string
          format: date-time
          nullable: true
          description: When Anjal will send this draft. Null if not scheduled.
        sendError:
          type: string
          nullable: true
          description: Why the last scheduled send failed. The draft is kept and `sendAt` is cleared.
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    DraftInput:
      type: object
      properties:
        to:
          oneOf:
            - { type: string, format: email }
            - { type: array, items: { type: string, format: email } }
        cc:
          oneOf:
            - { type: string, format: email }
            - { type: array, items: { type: string, format: email } }
        bcc:
          oneOf:
            - { type: string, format: email }
            - { type: array, items: { type: string, format: email } }
        subject: { type: string }
        plainBody: { type: string }
        htmlBody: { type: string }
        replyToMessageId: { type: string, format: uuid }
        labels: { $ref: "#/components/schemas/Labels" }
        sendAt:
          type: string
          format: date-time
          nullable: true
          description: |
            Schedule the send: ISO 8601 with an offset, e.g.
            `2026-10-01T09:00:00-04:00`. Must be in the future and at most 90
            days ahead. A scheduled draft needs at least one recipient and a
            body. On update, `null` cancels the schedule. Anjal checks for due
            drafts about every 20 seconds. If the send fails, the draft is
            kept, `sendError` is set, `sendAt` is cleared and
            `draft.send_failed` fires.
          example: "2026-10-01T09:00:00-04:00"

    WebhookEvent:
      type: string
      enum:
        - message.received
        - message.received.spam
        - message.sent
        - message.delivered
        - message.bounced
        - message.complained
        - message.rejected
        - message.opened
        - draft.send_failed
        - domain.verified
        - message.suspicious
        - message.quarantined
        - calendar.invite.received
        - calendar.invite.replied
        - calendar.invite.cancelled
        - calendar.invite.countered
        - account.suspended
        - account.payment_failed
        - account.subscription_ended
      description: |
        Payloads for the newer events:

        - `message.received.spam`: inbound mail the spam filter flagged. It is
          stored but does not fire `message.received`.
        - `message.sent`: includes `labels`.
        - `message.delivered`: `{ messageId, inboxId, recipients, timestamp, smtpResponse }`.
          The recipient's mail server accepted it; not a guarantee of inbox placement.
        - `message.rejected`: `{ messageId, inboxId, reason, recipients, timestamp }`.
          The provider refused to send it (e.g. a suppressed address).
        - `message.opened`: `{ messageId, inboxId, threadId, to, subject, openedAt, userAgent }`.
          First open of a send with `trackOpens: true`. A hint, not proof.
        - `draft.send_failed`: `{ draftId, inboxId, error, code }`. A scheduled
          draft could not be sent; it is kept with `sendError` set.
        - `domain.verified`: `{ domainId, domain, workspaceId, sharedWith, verifiedAt }`.
          Fired when `GET /v1/domains/{domain}/verify` first sees the domain verified.

    List:
      type: object
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        description: { type: string, nullable: true }
        entryCount: { type: integer }
        entries:
          type: array
          items: { $ref: "#/components/schemas/ListEntry" }
        createdAt: { type: string, format: date-time }

    ListEntry:
      type: object
      properties:
        id: { type: string, format: uuid }
        email: { type: string, format: email }
        displayName: { type: string, nullable: true }
        metadata: { type: object, additionalProperties: true, nullable: true }
        createdAt: { type: string, format: date-time }

    Domain:
      type: object
      properties:
        id: { type: string, format: uuid }
        domain: { type: string }
        status: { type: string, enum: [pending, verified, failed] }
        workspaceId: { type: string, format: uuid }
        dnsRecords:
          type: array
          items: { $ref: "#/components/schemas/DnsRecord" }
        sharedWith:
          type: string
          nullable: true
          enum: [google, microsoft, other, null]
          description: |
            Set when the domain's main mail stays at another provider (Google
            Workspace, Microsoft 365 or other) and Anjal mailboxes live
            alongside it. Null for a domain whose MX points at Anjal.
        routingSteps:
          type: array
          items: { type: string }
          description: |
            Present only for shared domains. Steps for the provider's admin
            console so it passes mail for addresses it doesn't know on to Anjal.
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    DnsRecord:
      type: object
      properties:
        type: { type: string, enum: [TXT, CNAME, MX, A] }
        name: { type: string }
        value: { type: string }
        priority: { type: integer, nullable: true }
        status: { type: string, enum: [pending, verified], nullable: true }
        note:
          type: string
          nullable: true
          description: |
            Extra instructions for this record. On a shared domain the SPF
            record is merged into your existing one, and the note says to
            replace the existing record (a domain must have only one SPF record).

    Webhook:
      type: object
      properties:
        id: { type: string, format: uuid }
        url: { type: string, format: uri }
        events:
          type: array
          items: { $ref: "#/components/schemas/WebhookEvent" }
        secret:
          type: string
          description: HMAC-SHA256 secret. Only returned on creation.
        isActive: { type: boolean }
        createdAt: { type: string, format: date-time }

    MetricsResponse:
      type: object
      properties:
        window:
          type: object
          properties:
            from: { type: string, format: date-time }
            to: { type: string, format: date-time }
        scope:
          type: object
          properties:
            tenantId: { type: string, format: uuid }
            workspaceId: { type: string, format: uuid, nullable: true }
            inboxId: { type: string, format: uuid, nullable: true }
        counts:
          type: object
          properties:
            sent: { type: integer }
            received: { type: integer }
            bounced: { type: integer }
        resources:
          type: object
          properties:
            inboxes: { type: integer }
            domains: { type: integer }

    LinkedInSignal:
      type: object
      required: [id, kind, name, cadence, filterMinIntent, intentDescription, enabled]
      properties:
        id:              { type: string }
        kind:
          type: string
          enum: [keyword, engagement, job_change_watchlist]
          description: |
            Acquisition strategy for this signal:
              - keyword: poll LinkedIn search for the saved query.
              - engagement: poll a tracked profile/company's recent posts and fire on engagers.
              - job_change_watchlist: poll a list of profiles weekly and fire on role/company changes.
        name:            { type: string }
        query:           { type: string, nullable: true, description: "Required for kind=keyword; null otherwise." }
        target:
          type: object
          nullable: true
          description: "Engagement signals only — the resolved actor target."
          properties:
            kind:  { type: string, enum: [profile, company] }
            url:   { type: string }
            urn:   { type: string, description: "Resolved urn:li:fsd_profile:* or urn:li:fsd_company:*." }
            label: { type: string, nullable: true }
        lastSeenPostUrn:
          type: string
          nullable: true
          description: "Engagement signals only — watermark of the most recent post processed. We only fire on engagers of posts newer than this."
        watchlistCount:
          type: integer
          nullable: true
          description: "Watchlist signals only — number of profiles being tracked."
        sessionId:
          type: string
          nullable: true
          description: |
            null = auto-distribute polling across all healthy LinkedIn
            sessions for this tenant (recommended). Specific id = pin
            the signal to that account so all polls come from it.
        cadence:         { type: string, enum: [daily, every_12h, every_6h, manual] }
        webhookUrl:      { type: string, nullable: true }
        webhookSecret:   { type: string, nullable: true, description: "Returned only on creation. Verify with HMAC-SHA256." }
        filterMinIntent: { type: string, enum: [low, medium, high] }
        intentDescription:
          type: string
          minLength: 1
          maxLength: 2000
          description: |
            Plain-English firing rule the LLM classifier uses as the
            authoritative definition of what should fire. Example: "Flag as
            ready when the author is a founder/operator complaining about
            cold email — skip vendors, agencies, and content marketers."
            The keyword is only a coarse pre-filter; this rule decides
            engage=true/false and the cited reason on every match.
        enabled:         { type: boolean }
        lastPolledAt:    { type: string, format: date-time, nullable: true }
        nextPollAt:      { type: string, format: date-time, nullable: true }
        lastError:       { type: string, nullable: true }
        lastErrorCode:   { type: string, nullable: true }
        lastErrorAt:     { type: string, format: date-time, nullable: true }
        matchesCount:    { type: integer }
        createdAt:       { type: string, format: date-time }
        updatedAt:       { type: string, format: date-time }

    LinkedInWatchlistEntry:
      type: object
      properties:
        id:            { type: string }
        profileUrl:    { type: string }
        profileSlug:   { type: string }
        fullName:      { type: string, nullable: true }
        lastRole:      { type: string, nullable: true }
        lastCompany:   { type: string, nullable: true }
        lastPolledAt:  { type: string, format: date-time, nullable: true }
        addedAt:       { type: string, format: date-time }

    LinkedInSignalMatch:
      type: object
      description: |
        Discriminated by `kind`. Engagement matches include `engagement.commentText` (verbatim);
        job-change matches include `jobChange.{old,new}{Role,Company}`. Keyword matches leave both null.
      properties:
        id:           { type: string }
        kind:
          type: string
          enum: [keyword, engagement, job_change]
        postUrl:      { type: string }
        postExcerpt:  { type: string }
        postPostedAt: { type: string, format: date-time, nullable: true }
        engagement:
          type: object
          nullable: true
          properties:
            action:      { type: string, enum: [commented, reacted] }
            commentText: { type: string, nullable: true }
        jobChange:
          type: object
          nullable: true
          properties:
            oldRole:    { type: string, nullable: true }
            oldCompany: { type: string, nullable: true }
            newRole:    { type: string, nullable: true }
            newCompany: { type: string, nullable: true }
        author:
          type: object
          properties:
            name:       { type: string }
            profileUrl: { type: string }
            headline:   { type: string, nullable: true, description: "From the verified LinkedIn profile lookup." }
            role:       { type: string, nullable: true, description: "Parsed current role (e.g. \"Founder & CEO\"). null when profile lookup was deferred." }
            company:    { type: string, nullable: true, description: "Parsed current company. null when profile lookup was deferred." }
        classification:
          type: object
          properties:
            engage: { type: boolean }
            intent: { type: string, enum: [low, medium, high] }
            reason: { type: string }
        triageScore:
          type: integer
          minimum: 0
          maximum: 100
          nullable: true
          description: "Pass-1 triage classifier score (0-100). Posts below the threshold are not persisted."
        pendingEnrichment:
          type: boolean
          description: "true when the post passed triage but the daily profile-lookup cap forced us to skip the full Pass-2 verification. Webhook delivery is held until the next poll fully verifies the match."
        foundAt: { type: string, format: date-time }

    LinkedInSearch:
      type: object
      required: [id, query, lookback, intentDescription, resultCount, createdAt]
      properties:
        id:           { type: string }
        sessionId:
          type: string
          nullable: true
          description: "The LinkedIn session that actually ran the search (the router's pick when the caller didn't pin)."
        query:        { type: string }
        lookback:     { type: string, enum: [past-24h, past-week, past-month] }
        minIntent:    { type: string, enum: [low, medium, high], nullable: true }
        intentDescription:
          type: string
          minLength: 1
          maxLength: 2000
          description: Plain-English firing rule used by the classifier (same semantics as on signals).
        resultCount:  { type: integer }
        tookMs:       { type: integer, nullable: true }
        errorCode:    { type: string, nullable: true, description: "Set on partial failure (e.g. LINKEDIN_RATE_LIMITED). Search row is still persisted." }
        errorMessage: { type: string, nullable: true }
        createdAt:    { type: string, format: date-time }

    LinkedInSearchResult:
      type: object
      properties:
        postUrl:     { type: string }
        postExcerpt: { type: string }
        postedAt:    { type: string, format: date-time, nullable: true }
        author:
          type: object
          properties:
            name:       { type: string }
            profileUrl: { type: string }
            headline:   { type: string, nullable: true }
            role:       { type: string, nullable: true }
            company:    { type: string, nullable: true }
        classification:
          type: object
          properties:
            engage: { type: boolean }
            intent: { type: string, enum: [low, medium, high] }
            reason: { type: string }
        triageScore: { type: integer, minimum: 0, maximum: 100, nullable: true }
        rank:        { type: integer, description: "Original position in LinkedIn's ranked result list (0 = top)." }

    LinkedInSessionUtilization:
      type: object
      properties:
        sessionId:        { type: string }
        label:            { type: string, nullable: true }
        status:           { type: string }
        rateLimitedUntil: { type: string, format: date-time, nullable: true }
        rateLimitReason:  { type: string, nullable: true }
        counts:
          type: object
          additionalProperties: { type: integer }
          description: "Action → count of calls in the trailing 24h. Keys: search_signal, search_history, profile_lookup, connection_request, send_message, post_like."
        remaining:
          type: object
          additionalProperties: { type: integer }
          description: "Action → remaining daily budget for this session."

    # ── Cadences ────────────────────────────────────────────────────
    Cadence:
      type: object
      properties:
        id:                  { type: string, format: uuid }
        name:                { type: string }
        description:         { type: string, nullable: true }
        enabled:             { type: boolean }
        businessHoursOnly:   { type: boolean }
        exitOnReply:         { type: boolean }
        exitOnUnsubscribe:   { type: boolean }
        dailySendCap:        { type: integer }
        webhookUrl:          { type: string, nullable: true }
        webhookSecret:       { type: string, nullable: true, description: "HMAC secret for X-MyAgentMail-Signature." }
        createdAt:           { type: string, format: date-time }
        updatedAt:           { type: string, format: date-time }
        steps:
          type: array
          items: { $ref: "#/components/schemas/CadenceStep" }
          nullable: true

    CadenceStepInput:
      type: object
      required: [kind, delayDays]
      properties:
        kind:
          type: string
          enum: [linkedin_connect, linkedin_message, email, wait]
        delayDays:
          type: number
          minimum: 0
          maximum: 365
          description: "Days after the previous step's completion. 0 = fire on enrollment for step 0; 0.25 = 6 hours."
        condition:
          type: string
          enum: [after_accept, no_reply_to_prev, never_replied]
          nullable: true
        draftStrategy:
          type: string
          enum: [static, webhook]
          default: static
          description: |
            How the runner gets the rendered content for this step.

            - `static`  — Use `staticBody` (+ `staticSubject` for email) as
                          the message verbatim, with `{{name}}`,
                          `{{first_name}}`, `{{email}}` token
                          substitution. Predictable; zero external deps.
            - `webhook` — At fire-time, the runner POSTs a
                          `cadence.step.draft.requested` event to the
                          cadence's `webhookUrl` and waits up to 30s for
                          a JSON response of
                          `{ body, subject?, skip?, defer? }`. The
                          customer's app brings the actual content with
                          its own business context, its own LLM if it
                          wants one, its own thread memory. Anjal never
                          generates copy on the customer's behalf.

            The legacy `"ai"` value was REMOVED 2026-05-19 — Anjal no
            longer drafts content server-side. New cadences passing
            `"ai"` get a `VALIDATION_ERROR` with a migration hint
            pointing here. Pre-existing rows with `"ai"` will surface
            `AI_STRATEGY_REMOVED` as the per-enrollment `lastError.code`
            when the runner tries to fire them — fix by updating the
            step to `static` (with `staticBody`) or `webhook` (with the
            cadence's `webhookUrl` set).
        staticSubject:
          type: string
          nullable: true
          description: "Email-only. The literal subject line for static-strategy email steps. Supports `{{name}}` / `{{first_name}}` / `{{email}}` tokens."
        staticBody:
          type: string
          nullable: true
          description: "The literal message body for static-strategy steps. Supports `{{name}}` / `{{first_name}}` / `{{email}}` tokens. Required when `draftStrategy: \"static\"`."
        promptHint:
          type: string
          nullable: true
          description: |
            Free-text hint for the step. Anjal does not read this — it's
            passed through verbatim in the `cadence.step.draft.requested`
            webhook payload (`step.promptHint`) so the customer's draft
            handler can use it as per-step context. Ignored by static
            strategy.
        notes:
          type: string
          nullable: true
          description: "Operator notes — not sent anywhere, just stored for the customer's reference."

    CadenceStep:
      allOf:
        - $ref: "#/components/schemas/CadenceStepInput"
        - type: object
          properties:
            id:         { type: string, format: uuid }
            cadenceId:  { type: string, format: uuid }
            stepIndex:  { type: integer }

    CadenceWebhookPayload:
      description: |
        POSTed to a cadence's `webhookUrl`. Five event types — four are
        fire-and-forget notifications (you don't need to respond
        meaningfully); one is a synchronous RPC.

        ## Fire-and-forget notifications (200 OK is fine)

        | Event | When |
        |---|---|
        | `cadence.step.fired` | A step just ran. `result.ok` says whether it succeeded. |
        | `cadence.lead.replied` | Lead replied (LinkedIn DM **or** email); enrollment transitioned to `state: replied`. `result.repliedVia ∈ {"linkedin_dm","email"}` tells you which channel. **Connection-request acceptance does not trigger this event** — that's a separate `signal.connection_accepted` webhook. `step` is `null` on this event (a reply isn't a step firing). |
        | `cadence.lead.completed` | All steps fired without a reply. |
        | `cadence.lead.exited` | Manual unenroll, bounce, or unrecoverable error. |

        ## Synchronous RPC

        | Event | When | Response expected |
        |---|---|---|
        | `cadence.step.draft.requested` | A step with `draftStrategy: "webhook"` is about to fire — Anjal needs the content. | HTTP 200 with `{ body, subject?, skip?, defer? }` within 30 seconds. |

        On a draft-request, Anjal blocks the runner waiting for your
        response. Three valid response shapes:

        ```json
        { "body": "Hey Jane — saw your post about cold outbound...", "subject": "Re: cold outbound" }
        ```
        Send this content. `subject` is required for email steps,
        ignored for LinkedIn. `body` is the literal message text — Anjal
        does NO interpretation, prompt-rendering, or LLM call on it.

        ```json
        { "skip": true, "reason": "lead unsubscribed in our CRM" }
        ```
        Skip this step. The enrollment advances to the next step.
        `reason` (string, max 280 chars) is stored on the step run for
        audit.

        ```json
        { "defer": { "untilSeconds": 3600 } }
        ```
        Reschedule. The runner sets `next_step_due_at = NOW() +
        untilSeconds` and re-fires the draft request on the next tick
        after that. Capped at 14 days (1209600 seconds).

        Any other response (HTTP 4xx/5xx, timeout, non-JSON, missing
        `body` field) fails the step with `DRAFT_WEBHOOK_FAILED`,
        defers 1h, retries.

        ## Common headers

        ```
        Content-Type: application/json
        X-MyAgentMail-Event: cadence.step.fired | cadence.step.draft.requested
                             | cadence.lead.replied | cadence.lead.completed
                             | cadence.lead.exited
        X-MyAgentMail-Signature: v1=<hex>     # HMAC-SHA256 of body using webhookSecret
        User-Agent: MyAgentMail-Webhook/1.0
        ```

        ## Draft-request payload (additional fields)

        Beyond the standard `cadence` / `enrollment` / `step` blocks,
        draft-request includes:

        - `enrollment.leadProfileUrn` — resolved by the runner from
                                        `leadLinkedinUrl` after the
                                        first LinkedIn step. Useful for
                                        looking up the lead in your CRM.
        - `enrollment.context`        — whatever JSON object you passed
                                        at enrollment time, returned
                                        verbatim.
        - `step.promptHint`           — the customer-authored prompt
                                        hint on the step. Anjal never
                                        reads this — it's a pass-through
                                        context channel for your handler.
        - `step.condition`            — `after_accept` / `no_reply_to_prev`
                                        / `never_replied` / null. Already
                                        evaluated to true by the time you
                                        receive the request (otherwise
                                        the runner would have skipped
                                        the step before drafting).
        - `requestedAt`               — ISO 8601 timestamp.

        ## Worked example — draft handler in 30 lines

        ```ts
        // POST /draft on your app's server
        export async function handleDraft(req: Request) {
          const event = await req.json();
          if (event.type !== "cadence.step.draft.requested") return new Response("", { status: 200 });

          // Look up lead in your own CRM
          const lead = await crm.findByExternalId(event.enrollment.leadExternalId);
          if (lead.unsubscribed) {
            return Response.json({ skip: true, reason: "lead unsubscribed in CRM" });
          }

          // Generate content with YOUR LLM + YOUR business context
          const message = await yourAgent.draft({
            stepKind:  event.step.kind,
            lead,
            promptHint: event.step.promptHint,
            priorThread: await fetchPriorThread(event.enrollment.id),
            yourProduct: yourProductCatalog,
          });

          return Response.json({ body: message.body, subject: message.subject });
        }
        ```
      type: object
      properties:
        type:
          type: string
          enum:
            - cadence.step.fired
            - cadence.step.draft.requested
            - cadence.lead.replied
            - cadence.lead.completed
            - cadence.lead.exited
        cadence:
          type: object
          properties:
            id:    { type: string }
            name:  { type: string }
        enrollment:
          type: object
          properties:
            id:                { type: string }
            leadExternalId:    { type: string }
            leadName:          { type: string, nullable: true }
            leadEmail:         { type: string, nullable: true }
            leadLinkedinUrl:   { type: string, nullable: true }
            currentStep:       { type: integer }
        step:
          nullable: true
          description: |
            Step context — present on `cadence.step.fired` and
            `cadence.step.draft.requested`. `null` on
            `cadence.lead.replied` (a reply isn't a step firing).
          type: object
          properties:
            index:  { type: integer }
            kind:   { type: string }
        result:
          type: object
          properties:
            ok:           { type: boolean }
            channelUrn:   { type: string, nullable: true, description: "Set on cadence.step.fired for successful LinkedIn sends — the conversationUrn." }
            error:        { type: string, nullable: true, description: "Set on cadence.step.fired when result.ok=false." }
            repliedVia:
              type: string
              nullable: true
              enum: [linkedin_dm, email]
              description: |
                Set on `cadence.lead.replied`. Tells you which channel
                detected the reply — `linkedin_dm` for an inbound
                LinkedIn message, `email` for an inbound SMTP message
                whose From address matched the enrollment's leadEmail.
        firedAt: { type: string, format: date-time }

paths:
  # ────────────────────────────────────────────────────────────────
  # WORKSPACES
  # ────────────────────────────────────────────────────────────────
  /v1/workspaces:
    post:
      tags: [Workspaces]
      summary: Create a workspace
      description: Requires a tenant master key (`tk_...`). Workspaces are isolation containers — inboxes and domains created in one cannot be seen from another.
      operationId: createWorkspace
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string, example: "Recruiter Corp" }
                slug: { type: string, example: "recruiter-corp" }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Workspace" }
        "400": { $ref: "#/components/responses/ValidationError" }
        "401": { $ref: "#/components/responses/Unauthorized" }
    get:
      tags: [Workspaces]
      summary: List workspaces
      operationId: listWorkspaces
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  workspaces:
                    type: array
                    items: { $ref: "#/components/schemas/Workspace" }

  /v1/workspaces/{id}:
    parameters: [ { $ref: "#/components/parameters/WorkspaceId" } ]
    get:
      tags: [Workspaces]
      summary: Get a workspace
      operationId: getWorkspace
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Workspace" }
        "404": { $ref: "#/components/responses/NotFound" }
    delete:
      tags: [Workspaces]
      summary: Delete a workspace
      description: Cascades to all inboxes, domains, and scoped keys. Cannot delete the tenant's default workspace.
      operationId: deleteWorkspace
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted: { type: boolean }
                  id: { type: string, format: uuid }

  /v1/workspaces/{id}/keys:
    parameters: [ { $ref: "#/components/parameters/WorkspaceId" } ]
    post:
      tags: [Workspaces]
      summary: Issue a workspace master key
      description: Returns a `wk_...` key scoped to this workspace. The key is only shown in the response body — store it securely.
      operationId: createWorkspaceKey
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkspaceKey" }
    get:
      tags: [Workspaces]
      summary: List workspace master keys
      operationId: listWorkspaceKeys
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  keys:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string, format: uuid }
                        prefix: { type: string }
                        name: { type: string }
                        createdAt: { type: string, format: date-time }

  /v1/workspaces/{id}/keys/{key_id}:
    parameters:
      - { $ref: "#/components/parameters/WorkspaceId" }
      - name: key_id
        in: path
        required: true
        schema: { type: string, format: uuid }
    delete:
      tags: [Workspaces]
      summary: Revoke a workspace master key
      operationId: revokeWorkspaceKey
      responses:
        "200":
          description: Revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  revoked: { type: boolean }
                  id: { type: string, format: uuid }

  # ────────────────────────────────────────────────────────────────
  # INBOXES
  # ────────────────────────────────────────────────────────────────
  /v1/inboxes:
    post:
      tags: [Inboxes]
      summary: Create an inbox (idempotent on requested username)
      description: |
        Requires tenant master or workspace master key.

        ## Username allocation
        - If `username` is set and your tenant **already** has an inbox at
          `username@domain`, returns that inbox (HTTP **200**, body
          contains `existed: true`). The call is idempotent — safe to
          retry.
        - Otherwise tries to create `username@domain`. If the global
          username is taken by another tenant, falls back to
          `username1`, `username2`, … through `username99`. The actual
          allocated username is in the response body.
        - Pass `?strict=true` to disable auto-fallback. With strict mode,
          a global collision returns HTTP **409** with the conflicting
          resource info instead of suffixing.

        IMAP/SMTP credentials — `apiKey` and `imapPassword` — are only
        returned on first creation, never on idempotent returns.
      operationId: createInbox
      parameters:
        - name: strict
          in: query
          description: |
            When `true`, the request fails with `409 USERNAME_TAKEN` if
            the requested `username@domain` is already taken by another
            tenant. When omitted (default), we auto-fallback to
            `username1`, `username2`, etc.
          schema: { type: boolean, default: false }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                username:
                  type: string
                  description: |
                    Lowercase alphanumeric + `.-_`. Auto-generated from
                    the tenant name if omitted. **No tenant-id suffix is
                    appended** — collisions are resolved via sequential
                    numeric fallback (e.g. `scout`, `scout1`, `scout2`).
                displayName: { type: string }
                domain: { type: string, description: "Defaults to anjal.app" }
                workspaceId:
                  type: string
                  format: uuid
                  description: (Tenant master only) target workspace. Defaults to the tenant's default workspace.
      responses:
        "200":
          description: |
            Idempotent return — your tenant already has an inbox at the
            requested `username@domain`. `existed: true` is set on the
            body. `apiKey` and `imapPassword` are NOT re-issued.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Inbox" }
        "201":
          description: Newly created. `apiKey` and `imapPassword` are returned once — store them now.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Inbox" }
        "403":
          description: Plan limit reached
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            `USERNAME_TAKEN` — only returned when `?strict=true` is set
            and `username@domain` is taken globally. Body includes
            `requestedUsername`, `attemptedUsername`, and `domain` for
            single-round-trip recovery. Default behavior auto-falls
            back without ever returning 409.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    get:
      tags: [Inboxes]
      summary: List inboxes
      operationId: listInboxes
      parameters:
        - name: workspace
          in: query
          description: Tenant master only — filter to a single workspace.
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  inboxes:
                    type: array
                    items: { $ref: "#/components/schemas/Inbox" }

  /v1/inboxes/{id}:
    parameters: [ { $ref: "#/components/parameters/InboxId" } ]
    get:
      tags: [Inboxes]
      summary: Get an inbox
      description: Returns the inbox detail including IMAP/SMTP credentials and the full address list.
      operationId: getInbox
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Inbox" }
        "404": { $ref: "#/components/responses/NotFound" }
    patch:
      tags: [Inboxes]
      summary: Update inbox display name or metadata
      description: Username, domain, and canonical identity are immutable. Use `POST /v1/inboxes/{id}/addresses` to change the outbound From.
      operationId: updateInbox
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                displayName: { type: string }
                metadata: { type: object, additionalProperties: true }
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  updated: { type: boolean }
                  id: { type: string, format: uuid }
    delete:
      tags: [Inboxes]
      summary: Delete an inbox
      description: Soft-deletes the inbox, hard-deletes its alias rows, and removes the Stalwart principal. Prior threads and messages are preserved but hidden from listings.
      operationId: deleteInbox
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted: { type: boolean }
                  id: { type: string, format: uuid }

  /v1/inboxes/{id}/addresses:
    parameters: [ { $ref: "#/components/parameters/InboxId" } ]
    post:
      tags: [Addresses]
      summary: Add an alias address
      description: |
        Attach another accepted address to this inbox. If `primary: true` (the default), it also becomes the outbound `From`. The domain must be either the default domain or a custom domain registered + verified to the same workspace.
      operationId: addInboxAddress
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email: { type: string, format: email, example: "scout-abc123@delegated.cc" }
                primary: { type: boolean, default: true }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  address: { type: string }
                  isPrimary: { type: boolean }
        "409": { $ref: "#/components/responses/Conflict" }

  /v1/inboxes/{id}/addresses/{address}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - name: address
        in: path
        required: true
        schema: { type: string }
        description: URL-encoded alias email
    delete:
      tags: [Addresses]
      summary: Remove an alias address
      description: Cannot remove the canonical (initial) address. If the removed alias was primary, the canonical address becomes primary again.
      operationId: removeInboxAddress
      responses:
        "200":
          description: Removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted: { type: boolean }
                  address: { type: string }

  # ────────────────────────────────────────────────────────────────
  # MESSAGES
  # ────────────────────────────────────────────────────────────────
  /v1/inboxes/{id}/send:
    parameters: [ { $ref: "#/components/parameters/InboxId" } ]
    post:
      tags: [Messages]
      summary: Send a message
      description: |
        Sends from this inbox. The `From` header is derived from the inbox's primary alias. Pass `verified: true` when you've validated the recipient domain out-of-band (e.g. via verify-email); otherwise, sends to an address that has never replied to this inbox are rejected as a deliverability safeguard.

        Pass an `Idempotency-Key` header so a retry never sends twice. `labels` tags the sent message; `trackOpens: true` adds an open-tracking pixel to the HTML body. The `message.sent` webhook payload includes `labels`.
      operationId: sendMessage
      parameters:
        - { $ref: "#/components/parameters/IdempotencyKey" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [to, subject]
              properties:
                to:
                  oneOf:
                    - { type: string, format: email }
                    - { type: array, items: { type: string, format: email } }
                cc:
                  description: Cc recipient(s) — subject to the same MX + verified + abuse gates as `to`.
                  oneOf:
                    - { type: string, format: email }
                    - { type: array, items: { type: string, format: email } }
                bcc:
                  description: Bcc recipient(s).
                  oneOf:
                    - { type: string, format: email }
                    - { type: array, items: { type: string, format: email } }
                subject: { type: string }
                plainBody: { type: string }
                htmlBody: { type: string }
                replyTo: { type: string, format: email }
                verified: { type: boolean, default: false }
                labels: { $ref: "#/components/schemas/Labels" }
                trackOpens:
                  type: boolean
                  default: false
                  description: Add an open-tracking pixel (HTML body only). See `SendExtras`.
      responses:
        "200":
          description: Sent
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  threadId: { type: string, format: uuid }
                  status: { type: string, example: "sent" }
                  messageId: { type: string }
        "403": { description: "Inbox paused or plan limit reached" }
        "400": { description: "Validation error, or IDEMPOTENCY_KEY_INVALID" }
        "409": { $ref: "#/components/responses/IdempotencyConflict" }
        "502": { description: "SMTP relay error" }

  /v1/inboxes/{id}/reply/{messageId}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/MessageId" }
    post:
      tags: [Messages]
      summary: Reply to a message
      description: Replies preserve the thread (In-Reply-To + References) and the original recipient.
      operationId: replyMessage
      parameters:
        - { $ref: "#/components/parameters/IdempotencyKey" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                plainBody: { type: string }
                htmlBody: { type: string }
                cc:
                  description: Extra Cc recipient(s) on top of the thread's original recipient.
                  oneOf:
                    - { type: string, format: email }
                    - { type: array, items: { type: string, format: email } }
                bcc:
                  description: Bcc recipient(s).
                  oneOf:
                    - { type: string, format: email }
                    - { type: array, items: { type: string, format: email } }
                labels: { $ref: "#/components/schemas/Labels" }
                trackOpens:
                  type: boolean
                  default: false
                  description: Add an open-tracking pixel (HTML body only). See `SendExtras`.
      responses:
        "200": { description: Sent }
        "400": { description: "Validation error, or IDEMPOTENCY_KEY_INVALID" }
        "409": { $ref: "#/components/responses/IdempotencyConflict" }

  /v1/inboxes/{id}/reply-all/{messageId}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/MessageId" }
    post:
      tags: [Messages]
      summary: Reply-all to a message
      description: Sends to the original sender plus every address in the original To list, with any of this inbox's own addresses filtered out.
      operationId: replyAllMessage
      parameters:
        - { $ref: "#/components/parameters/IdempotencyKey" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                plainBody: { type: string }
                htmlBody: { type: string }
                cc:
                  description: Extra Cc recipient(s) on top of the auto-derived reply-all recipients.
                  oneOf:
                    - { type: string, format: email }
                    - { type: array, items: { type: string, format: email } }
                bcc:
                  description: Bcc recipient(s).
                  oneOf:
                    - { type: string, format: email }
                    - { type: array, items: { type: string, format: email } }
                labels: { $ref: "#/components/schemas/Labels" }
                trackOpens:
                  type: boolean
                  default: false
                  description: Add an open-tracking pixel (HTML body only). See `SendExtras`.
      responses:
        "200": { description: Sent }
        "400": { description: "Validation error, or IDEMPOTENCY_KEY_INVALID" }
        "409": { $ref: "#/components/responses/IdempotencyConflict" }

  /v1/inboxes/{id}/forward/{messageId}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/MessageId" }
    post:
      tags: [Messages]
      summary: Forward a message
      description: Prepends a "Forwarded message" header block and sends the combined body.
      operationId: forwardMessage
      parameters:
        - { $ref: "#/components/parameters/IdempotencyKey" }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [to]
              properties:
                to:
                  oneOf:
                    - { type: string, format: email }
                    - { type: array, items: { type: string, format: email } }
                subject: { type: string }
                plainBody: { type: string }
                htmlBody: { type: string }
                labels: { $ref: "#/components/schemas/Labels" }
                trackOpens:
                  type: boolean
                  default: false
                  description: Add an open-tracking pixel (HTML body only). See `SendExtras`.
      responses:
        "200": { description: Sent }
        "400": { description: "Validation error, or IDEMPOTENCY_KEY_INVALID" }
        "409": { $ref: "#/components/responses/IdempotencyConflict" }

  /v1/inboxes/{id}/threads:
    parameters: [ { $ref: "#/components/parameters/InboxId" } ]
    get:
      tags: [Messages]
      summary: List threads
      description: |
        Newest first, each with its `labels`. `?labels=a,b` returns threads
        that carry every label across their messages. Spam is left out unless
        `includeSpam=true`; a thread containing spam then carries `hasSpam: true`.
      operationId: listThreads
      parameters:
        - { $ref: "#/components/parameters/LimitQuery" }
        - { $ref: "#/components/parameters/OffsetQuery" }
        - { $ref: "#/components/parameters/LabelsQuery" }
        - { $ref: "#/components/parameters/IncludeSpamQuery" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  threads:
                    type: array
                    items: { $ref: "#/components/schemas/Thread" }

  /v1/inboxes/{id}/threads/{threadId}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - name: threadId
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [Messages]
      summary: Get a thread with all messages
      operationId: getThread
      parameters:
        - name: view
          in: query
          description: |
            Payload weight. `metadata` = no bodies; `snippet` = 200-char plain
            snippet; `full` (default) = plainBody only; `raw` = plainBody +
            htmlBody. htmlBody is ~95% of a thread's bytes — only request it
            when you actually need rendered HTML.
          schema: { type: string, enum: [metadata, snippet, full, raw], default: full }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  threadId: { type: string, format: uuid }
                  messageCount: { type: integer }
                  messages:
                    type: array
                    items: { $ref: "#/components/schemas/Message" }
    patch:
      tags: [Messages]
      summary: Update a thread
      description: |
        Applies to every message in the thread: labels (replace with `labels`,
        or change with `addLabels` / `removeLabels`), read, starred, archived
        and spam. Labelling a thread labels each of its messages.
      operationId: updateThread
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                labels: { $ref: "#/components/schemas/Labels" }
                addLabels: { $ref: "#/components/schemas/Labels" }
                removeLabels: { $ref: "#/components/schemas/Labels" }
                isRead: { type: boolean }
                isStarred: { type: boolean }
                isArchived: { type: boolean }
                isSpam: { type: boolean, description: "true moves the thread to Spam; false recovers it." }
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  updated: { type: boolean }
                  threadId: { type: string }
                  messageCount: { type: integer }
                  labels: { type: array, items: { type: string } }
        "400": { $ref: "#/components/responses/ValidationError" }
        "404": { $ref: "#/components/responses/NotFound" }
    delete:
      tags: [Messages]
      summary: Delete a thread
      description: Soft-deletes every message in the thread (moves them to Trash), the same way deleting one message does.
      operationId: deleteThread
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted: { type: boolean }
                  threadId: { type: string }
                  messageCount: { type: integer }
        "404": { $ref: "#/components/responses/NotFound" }

  /v1/messages:
    get:
      tags: [Messages]
      summary: List messages across inboxes
      description: |
        One list across every inbox the key can see (tenant, workspace, inbox or
        teammate scope). `?labels=a,b` returns messages carrying every label;
        with `group=thread` it matches whole threads (a thread matches when any
        of its messages carries the labels) and each row carries the thread's
        `labels`.
      operationId: listAllMessages
      parameters:
        - name: folder
          in: query
          schema: { type: string, enum: [inbox, sent, starred, archived, spam, trash], default: inbox }
        - name: group
          in: query
          description: "`thread` returns one row per thread (its latest message)."
          schema: { type: string, enum: [thread] }
        - name: inboxId
          in: query
          schema: { type: string, format: uuid }
        - { $ref: "#/components/parameters/LabelsQuery" }
        - { $ref: "#/components/parameters/LimitQuery" }
        - { $ref: "#/components/parameters/OffsetQuery" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  messages:
                    type: array
                    items: { $ref: "#/components/schemas/Message" }

  /v1/messages/labels:
    get:
      tags: [Messages]
      summary: List labels in use
      description: Every label in use, with how many threads carry it. Same scoping as `GET /v1/messages`.
      operationId: listLabels
      parameters:
        - name: inboxId
          in: query
          description: Limit to one inbox.
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  labels:
                    type: array
                    items:
                      type: object
                      properties:
                        label: { type: string, example: "needs-review" }
                        threads: { type: integer, example: 4 }

  /v1/messages/search:
    get:
      tags: [Messages]
      summary: Search messages (full-text, cross-inbox)
      description: |
        Full-text search across every inbox the key can see (tenant-, workspace-,
        or inbox-scoped automatically by key tier). Matches subject, plain-text
        body, and participant addresses. Returns lightweight hits — ids,
        participants, subject, receivedAt, hasAttachments, and a ~200-character
        snippet centred on the match — never htmlBody, so results stay small
        enough for an agent to consume in one call, then fetch the winning
        message/thread in full.
      operationId: searchMessages
      parameters:
        - name: query
          in: query
          description: |
            Full-text across subject, body, and participants. Gmail-style operators work in the text: from:ben, to:, cc:, subject: (quote a value with
            spaces: from:"ben hubner"), is:unread, is:read, is:starred, has:attachment, label:billing,
            in:inbox|sent|archive|spam, before:2026-01-31, after:2026-01-01 (UTC, after inclusive,
            before exclusive), and -term or -from:x to exclude. Operators combine with AND; anything
            else is free text. in:drafts and in:trash are not supported.
          schema: { type: string }
        - name: inboxId
          in: query
          description: Scope to one inbox. Omit = all inboxes the key can see.
          schema: { type: string, format: uuid }
        - name: from
          in: query
          description: Filter by sender address or domain (substring match).
          schema: { type: string }
        - name: to
          in: query
          schema: { type: string }
        - name: participant
          in: query
          description: Match from OR to OR cc (address or domain).
          schema: { type: string }
        - name: direction
          in: query
          schema: { type: string, enum: [inbound, outbound] }
        - name: after
          in: query
          schema: { type: string, format: date-time }
        - name: before
          in: query
          schema: { type: string, format: date-time }
        - name: hasAttachment
          in: query
          schema: { type: boolean }
        - name: attachmentFilename
          in: query
          description: Match an attachment filename substring (e.g. `invoice`).
          schema: { type: string }
        - { $ref: "#/components/parameters/LimitQuery" }
        - { $ref: "#/components/parameters/OffsetQuery" }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  results:
                    type: array
                    items:
                      type: object
                      properties:
                        messageId: { type: string, format: uuid }
                        threadId: { type: string, format: uuid, nullable: true }
                        inboxId: { type: string, format: uuid }
                        inboxUsername: { type: string }
                        inboxDomain: { type: string }
                        direction: { type: string, enum: [inbound, outbound] }
                        from: { type: string }
                        to: { type: string }
                        subject: { type: string }
                        receivedAt: { type: string, format: date-time }
                        hasAttachments: { type: boolean }
                        snippet:
                          type: string
                          description: ~200 chars of plain body centred on the match.
                  totalCount: { type: integer }
                  nextOffset: { type: integer, nullable: true }
  /v1/inboxes/{id}/messages:
    parameters: [ { $ref: "#/components/parameters/InboxId" } ]
    get:
      tags: [Messages]
      summary: List messages
      description: |
        Lists messages in an inbox. Tracking fields (firstOpenedAt,
        openCount, firstClickedAt, clickCount, etc.) are returned on every
        row — no separate detail fetch needed for an engagement-aware view.
        Each row also carries a ~200-char plain-body `snippet` for triage
        without fetching the full message. Filters can be combined.

        Every row carries `labels`, `isSpam` and, for sent mail,
        `deliveryStatus` and `deliveredAt`. Spam is left out unless
        `includeSpam=true`.
      operationId: listMessages
      parameters:
        - { $ref: "#/components/parameters/LimitQuery" }
        - { $ref: "#/components/parameters/OffsetQuery" }
        - { $ref: "#/components/parameters/LabelsQuery" }
        - { $ref: "#/components/parameters/IncludeSpamQuery" }
        - name: q
          in: query
          description: |
            Substring search over subject, body, sender and recipient. Gmail-style operators work in the text: from:ben, to:, cc:, subject: (quote a value with
            spaces: from:"ben hubner"), is:unread, is:read, is:starred, has:attachment, label:billing,
            in:inbox|sent|archive|spam, before:2026-01-31, after:2026-01-01 (UTC, after inclusive,
            before exclusive), and -term or -from:x to exclude. Operators combine with AND; anything
            else is free text. in:drafts and in:trash are not supported.
          schema: { type: string, maxLength: 200 }
        - name: direction
          in: query
          schema: { type: string, enum: [inbound, outbound] }
        - name: opened
          in: query
          description: When true, return only messages with open_count > 0.
          schema: { type: boolean }
        - name: clicked
          in: query
          description: |
            When true, return only messages with click_count > 0. Useful for
            cadence engines listing engaged leads who haven't yet replied.
          schema: { type: boolean }
        - name: engagedSince
          in: query
          description: |
            ISO-8601 timestamp. Returns only messages whose lastOpenedAt OR
            lastClickedAt is at or after this time. Use for incremental
            polling — pass the timestamp of your last successful sync.
          schema: { type: string, format: date-time }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  messages:
                    type: array
                    items: { $ref: "#/components/schemas/Message" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }

  /v1/inboxes/{id}/messages/{messageId}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/MessageId" }
    get:
      tags: [Messages]
      summary: Get a message
      description: |
        Returns full bodies plus attachment metadata. Also marks the message as read.

        Some mail clients paste a screenshot straight into the HTML as a `data:`
        URI, which can be hundreds of KB inside `htmlBody`. Pass
        `inlineImages=refs` to get each one replaced by `attachment:<id>`, the
        id of the attachment holding the same image, and that attachment marked
        `inline: true`. Fetch it from the attachments endpoint. The response then
        also carries `inlineImages: { replaced, unmatched }`; `unmatched` counts
        images that had no matching attachment and were removed with no pointer.
        Without the parameter `htmlBody` is returned exactly as received.
      operationId: getMessage
      parameters:
        - name: inlineImages
          in: query
          required: false
          description: "`refs` replaces inline `data:` images in `htmlBody` with `attachment:<id>` references."
          schema: { type: string, enum: [refs] }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Message" }
    patch:
      tags: [Messages]
      summary: Update a message
      description: |
        Change labels (replace with `labels`, or change with `addLabels` /
        `removeLabels`) and state (read, starred, archived, spam). Returns the
        message's labels after the change.
      operationId: updateMessage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                labels: { $ref: "#/components/schemas/Labels" }
                addLabels: { $ref: "#/components/schemas/Labels" }
                removeLabels: { $ref: "#/components/schemas/Labels" }
                isRead: { type: boolean }
                isStarred: { type: boolean }
                isArchived: { type: boolean }
                isSpam: { type: boolean, description: "true moves it to Spam; false recovers it." }
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  updated: { type: boolean }
                  id: { type: string }
                  labels: { type: array, items: { type: string } }
                  isRead: { type: boolean }
                  isStarred: { type: boolean }
                  isArchived: { type: boolean }
                  isSpam: { type: boolean }
        "400": { $ref: "#/components/responses/ValidationError" }
        "404": { $ref: "#/components/responses/NotFound" }
    delete:
      tags: [Messages]
      summary: Soft-delete a message
      description: Sets `deleted_at`. The row stays so thread history doesn't renumber; list queries filter deleted messages out.
      operationId: deleteMessage
      responses:
        "200": { description: Deleted }

  /v1/inboxes/{id}/messages/{messageId}/raw:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/MessageId" }
    get:
      tags: [Messages]
      summary: Download raw .eml source
      description: Returns the full RFC 5322 source as `message/rfc822`. Only available for inbound messages; outbound messages do not persist their raw source.
      operationId: getMessageRaw
      responses:
        "200":
          description: Raw email source
          content:
            message/rfc822:
              schema: { type: string, format: binary }
        "404": { description: "Raw source not available" }

  /v1/inboxes/{id}/messages/{messageId}/attachments:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/MessageId" }
    get:
      tags: [Messages]
      summary: List attachments on a message
      operationId: listAttachments
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  attachments:
                    type: array
                    items: { $ref: "#/components/schemas/AttachmentMeta" }

  /v1/inboxes/{id}/messages/{messageId}/attachments/{aid}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/MessageId" }
      - { $ref: "#/components/parameters/AttachmentId" }
    get:
      tags: [Messages]
      summary: Download an attachment
      description: |
        Streams the raw attachment bytes with the original `Content-Type` and `Content-Disposition` headers.

        A PNG, JPEG, GIF or WebP is read for hidden instructions before an API key
        or agent is given it, because a model can look at an image the way it reads
        a body. If the text in it reads like instructions aimed at an AI, or it
        cannot be checked, this returns `403 IMAGE_HELD` and a person can still open
        it in the dashboard. `503 IMAGE_HELD` means it could not be checked right now
        and is worth retrying. A signed-in person in the dashboard is never held, and
        neither is an inbox or account that has turned mail protection off.
      operationId: getAttachment
      responses:
        "200":
          description: Attachment bytes
          content:
            application/octet-stream:
              schema: { type: string, format: binary }
        "403":
          description: The image is held (`IMAGE_HELD`), or its message is quarantined (`QUARANTINED`)
        "503":
          description: The image could not be checked right now (`IMAGE_HELD`); retry shortly

  /v1/inboxes/{id}/messages/{messageId}/attachments/{aid}/download-url:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/MessageId" }
      - { $ref: "#/components/parameters/AttachmentId" }
    post:
      tags: [Messages]
      summary: Get a short-lived download link for an attachment
      description: |
        For a file too big to pass through an agent's context (a PDF as base64 is
        millions of characters). Returns a link to fetch the file with a plain
        `GET`, no API key. The link works for one attachment only, for 10 minutes
        and 3 uses; a `HEAD` request does not spend a use. It is served as a
        download, never rendered, and active types such as HTML and SVG are sent
        as `application/octet-stream`. The content is untrusted: it was written
        by the sender.

        Refused with `403 QUARANTINED` for a message held for review, and with
        `403 IMAGE_HELD` for an image whose text looks like instructions to an AI or
        which could not be checked (see the attachment download). A link stops
        working if its message is held after the link was issued.
      operationId: createAttachmentDownloadUrl
      responses:
        "201":
          description: Link issued
          content:
            application/json:
              schema:
                type: object
                properties:
                  attachmentId: { type: string, format: uuid }
                  filename: { type: string }
                  contentType: { type: string }
                  sizeBytes: { type: integer }
                  url: { type: string, format: uri, description: "Fetch with GET. The token in it is the credential." }
                  expiresAt: { type: string, format: date-time }
                  expiresInMinutes: { type: integer, example: 10 }
                  maxUses: { type: integer, example: 3 }
                  howTo: { type: string }
        "403":
          description: The message is held for review (`QUARANTINED`)
        "404":
          description: No such attachment on this message

  /downloads/{downloadId}:
    get:
      tags: [Messages]
      summary: Fetch an attachment through a download link
      description: |
        The receiver for links from `download-url`. Not under `/v1` and takes no
        API key: the `t` token in the query string is the credential. Every
        failure, whether the token is wrong, the link expired, its uses ran out,
        or the message is held, returns the same `404`, so a wrong guess learns
        nothing about whether a link exists.
      operationId: getAttachmentByDownloadLink
      security: []
      parameters:
        - { name: downloadId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: t, in: query, required: true, schema: { type: string }, description: Link token }
      responses:
        "200":
          description: Attachment bytes, as a download
          content:
            application/octet-stream:
              schema: { type: string, format: binary }
        "404":
          description: Not valid, expired, used up, or held

  /v1/inboxes/{id}/attachment-uploads:
    parameters: [ { $ref: "#/components/parameters/InboxId" } ]
    post:
      tags: [Messages]
      summary: Get a one-time URL to upload a file to
      description: |
        For attaching a real file without putting its bytes in a request an agent
        has to write out. Returns an `uploadUrl`. `PUT` the raw file to it with no
        API key, then attach it by passing `{ "uploadId": "..." }` in `attachments`
        on a send, reply, reply-all, forward or draft call. One file, up to 10 MB,
        valid for 60 minutes, and single-use in both directions: it can be uploaded
        to once and attached once.
      operationId: createAttachmentUpload
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [filename]
              properties:
                filename: { type: string, example: "report.pdf" }
                contentType: { type: string, example: "application/pdf" }
                sizeBytes: { type: integer, description: "If known, so an oversized file is refused before upload." }
      responses:
        "201":
          description: Upload slot created
          content:
            application/json:
              schema:
                type: object
                properties:
                  uploadId: { type: string, format: uuid }
                  uploadUrl: { type: string, format: uri }
                  expiresAt: { type: string, format: date-time }
                  maxBytes: { type: integer }
                  filename: { type: string }
                  howTo: { type: string }

  /uploads/{uploadId}:
    put:
      tags: [Messages]
      summary: Upload a file to a one-time URL
      description: |
        The receiver for URLs from `attachment-uploads`. No API key: the `t` token
        in the query string is the credential. The body is the raw file bytes.
        A second upload to the same URL is refused, and so is any wrong or expired
        token, with the same `404`.
      operationId: uploadAttachmentFile
      security: []
      parameters:
        - { name: uploadId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: t, in: query, required: true, schema: { type: string }, description: Upload token }
      requestBody:
        required: true
        content:
          application/octet-stream:
            schema: { type: string, format: binary }
      responses:
        "200":
          description: Stored
          content:
            application/json:
              schema:
                type: object
                properties:
                  uploaded: { type: boolean }
                  uploadId: { type: string, format: uuid }
                  filename: { type: string }
                  sizeBytes: { type: integer }
        "400": { description: Already used, or empty }
        "404": { description: Not valid or expired }
        "413": { description: Larger than the slot allows }

  # ────────────────────────────────────────────────────────────────
  # DRAFTS
  # ────────────────────────────────────────────────────────────────
  /v1/inboxes/{id}/drafts:
    parameters: [ { $ref: "#/components/parameters/InboxId" } ]
    post:
      tags: [Drafts]
      summary: Create a draft
      description: |
        `labels` are applied to the message when the draft is sent. Set
        `sendAt` to schedule the send: Anjal sends it at that time, no cron
        needed.
      operationId: createDraft
      requestBody:
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DraftInput" }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Draft" }
        "400": { description: "Validation error, e.g. sendAt in the past, more than 90 days ahead, or a scheduled draft without recipients or a body" }
    get:
      tags: [Drafts]
      summary: List drafts
      description: "`scheduled=true` lists only drafts waiting to be sent, soonest first. A failed scheduled send shows `sendError`."
      operationId: listDrafts
      parameters:
        - { $ref: "#/components/parameters/LimitQuery" }
        - { $ref: "#/components/parameters/OffsetQuery" }
        - name: scheduled
          in: query
          schema: { type: boolean, default: false }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  drafts:
                    type: array
                    items: { $ref: "#/components/schemas/Draft" }

  /v1/inboxes/{id}/drafts/{did}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/DraftId" }
    get:
      tags: [Drafts]
      summary: Get a draft
      operationId: getDraft
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Draft" }
    patch:
      tags: [Drafts]
      summary: Update a draft
      description: |
        Merge-patch. Omitted fields are left as-is. Set `sendAt` to schedule or
        reschedule the send (this also clears `sendError`); `sendAt: null`
        cancels it.
      operationId: updateDraft
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/DraftInput" }
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Draft" }
                  - type: object
                    properties:
                      updated: { type: boolean }
        "400": { $ref: "#/components/responses/ValidationError" }
    delete:
      tags: [Drafts]
      summary: Delete a draft
      operationId: deleteDraft
      responses:
        "200": { description: Deleted }

  /v1/inboxes/{id}/drafts/{did}/send:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/DraftId" }
    post:
      tags: [Drafts]
      summary: Send a draft
      description: Sends the current draft contents now and deletes the draft atomically. If the draft has `replyToMessageId`, the sent message is threaded as a reply. The draft's `labels` are applied to the sent message. Accepts an `Idempotency-Key` header.
      operationId: sendDraft
      parameters:
        - { $ref: "#/components/parameters/IdempotencyKey" }
      responses:
        "200":
          description: Sent
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  threadId: { type: string, format: uuid }
                  status: { type: string }
                  messageId: { type: string }
                  draftId: { type: string, format: uuid }
        "400": { description: "Validation error, or IDEMPOTENCY_KEY_INVALID" }
        "409": { $ref: "#/components/responses/IdempotencyConflict" }

  # ────────────────────────────────────────────────────────────────
  # LISTS
  # ────────────────────────────────────────────────────────────────
  /v1/inboxes/{id}/lists:
    parameters: [ { $ref: "#/components/parameters/InboxId" } ]
    get:
      tags: [Lists]
      summary: List lists
      operationId: listLists
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  lists:
                    type: array
                    items: { $ref: "#/components/schemas/List" }
    post:
      tags: [Lists]
      summary: Create a list
      operationId: createList
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string }
                description: { type: string }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/List" }

  /v1/inboxes/{id}/lists/{lid}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/ListId" }
    get:
      tags: [Lists]
      summary: Get a list with entries
      operationId: getList
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/List" }
    delete:
      tags: [Lists]
      summary: Delete a list
      operationId: deleteList
      responses:
        "200": { description: Deleted }

  /v1/inboxes/{id}/lists/{lid}/entries:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/ListId" }
    post:
      tags: [Lists]
      summary: Add a list entry
      operationId: addListEntry
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              properties:
                email: { type: string, format: email }
                displayName: { type: string }
                metadata: { type: object, additionalProperties: true }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ListEntry" }
        "409": { $ref: "#/components/responses/Conflict" }

  /v1/inboxes/{id}/lists/{lid}/entries/{eid}:
    parameters:
      - { $ref: "#/components/parameters/InboxId" }
      - { $ref: "#/components/parameters/ListId" }
      - name: eid
        in: path
        required: true
        schema: { type: string, format: uuid }
    delete:
      tags: [Lists]
      summary: Remove a list entry
      operationId: removeListEntry
      responses:
        "200": { description: Deleted }

  # ────────────────────────────────────────────────────────────────
  # DOMAINS
  # ────────────────────────────────────────────────────────────────
  /v1/domains:
    post:
      tags: [Domains]
      summary: Register a custom domain
      description: |
        Returns the DNS records you need to set at your registrar. Domain starts in `pending` status until you call the verify endpoint.

        **Domains that already get mail elsewhere (Google Workspace, Microsoft 365).**
        If the domain has MX records at another provider and you pass neither
        `sharedWith` nor `replaceMailProvider`, the call returns
        `422 DOMAIN_HAS_MAIL_PROVIDER` with `detectedProvider`, `mx` and a
        `fix` string, because pointing the MX at Anjal would cut off that mail.
        You then have three options:

        1. **Keep the provider** (`sharedWith: "google" | "microsoft" | "other"`).
           No MX record is returned: the provider stays the main mail server.
           The SPF TXT record is merged into the domain's existing SPF (its
           `note` says to replace the existing record, since a domain may have
           only one). Anjal's DMARC record is only included if the domain has
           none. The response includes `routingSteps` for the provider's admin
           console: for Google, a Default routing rule that sends mail for
           non-recognized addresses to the Anjal host; for Microsoft, setting
           the Accepted domain to Internal relay plus an outbound connector to
           the Anjal smart host. In this setup the provider forwards mail for
           addresses it doesn't know, so it keeps its own users and Anjal
           receives mail only for addresses the provider doesn't have.
        2. **Use a subdomain** such as `agents.example.com`, which has no MX
           yet and can point at Anjal without touching the main domain's mail.
        3. **Move all mail to Anjal** (`replaceMailProvider: true`). The MX
           record returned replaces the current provider's.
      operationId: createDomain
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [domain]
              properties:
                domain: { type: string, example: "mail.example.com" }
                workspaceId:
                  type: string
                  format: uuid
                  description: (Tenant master only) target workspace.
                sharedWith:
                  type: string
                  enum: [google, microsoft, other]
                  description: Keep this provider as the domain's main mail server and add Anjal mailboxes alongside it (`shared_with` also works).
                replaceMailProvider:
                  type: boolean
                  description: Move all mail for the domain to Anjal (the returned MX record replaces the current one).
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Domain" }
                  - type: object
                    properties:
                      message: { type: string }
        "422":
          description: The domain already receives mail at another provider
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string }
                  code: { type: string, example: "DOMAIN_HAS_MAIL_PROVIDER" }
                  detectedProvider: { type: string, enum: [google, microsoft, other] }
                  mx: { type: array, items: { type: string }, example: ["aspmx.l.google.com"] }
                  fix: { type: string }
    get:
      tags: [Domains]
      summary: List domains
      operationId: listDomains
      parameters:
        - name: workspace
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  domains:
                    type: array
                    items: { $ref: "#/components/schemas/Domain" }

  /v1/domains/{domain}:
    parameters: [ { $ref: "#/components/parameters/DomainName" } ]
    get:
      tags: [Domains]
      summary: Get a domain
      operationId: getDomain
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Domain" }
    delete:
      tags: [Domains]
      summary: Delete a domain
      operationId: deleteDomain
      responses:
        "200": { description: Deleted }

  /v1/domains/{domain}/verify:
    parameters: [ { $ref: "#/components/parameters/DomainName" } ]
    get:
      tags: [Domains]
      summary: Verify a domain
      description: Re-checks DNS records with the upstream ESP. If the domain is now verified, Mission Control atomically adds the new address as a primary alias on the inbox (preserving thread history). The first time this sees the domain verified, the `domain.verified` webhook fires.
      operationId: verifyDomain
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  domain: { type: string }
                  status: { type: string, enum: [pending, verified, failed] }
                  verified: { type: boolean }
                  dnsRecords:
                    type: array
                    items: { $ref: "#/components/schemas/DnsRecord" }
                  sharedWith: { type: string, nullable: true, enum: [google, microsoft, other, null] }
                  routingSteps:
                    type: array
                    items: { type: string }
                    description: Present only for shared domains.
                  message: { type: string }

  /v1/domains/{domain}/zone-file:
    parameters: [ { $ref: "#/components/parameters/DomainName" } ]
    get:
      tags: [Domains]
      summary: Export BIND zone file
      description: Returns the current DNS records as a BIND-format zone file fragment. Convenient for pasting into a DNS editor that accepts zone-file imports.
      operationId: getDomainZoneFile
      responses:
        "200":
          description: Zone file text
          content:
            text/plain:
              schema: { type: string }

  # ────────────────────────────────────────────────────────────────
  # WEBHOOKS
  # ────────────────────────────────────────────────────────────────
  /v1/webhooks:
    post:
      tags: [Webhooks]
      summary: Create a webhook
      description: Subscribe a URL to one or more events. See `WebhookEvent` for the full list and the newer payloads.
      operationId: createWebhook
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events]
              properties:
                url: { type: string, format: uri }
                events:
                  type: array
                  minItems: 1
                  items: { $ref: "#/components/schemas/WebhookEvent" }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Webhook" }
    get:
      tags: [Webhooks]
      summary: List webhooks
      operationId: listWebhooks
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  webhooks:
                    type: array
                    items: { $ref: "#/components/schemas/Webhook" }

  /v1/webhooks/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [Webhooks]
      summary: Get a webhook
      operationId: getWebhook
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Webhook" }
    patch:
      tags: [Webhooks]
      summary: Update a webhook
      description: Change url, events, or enabled state.
      operationId: updateWebhook
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                url: { type: string, format: uri }
                events:
                  type: array
                  minItems: 1
                  items: { $ref: "#/components/schemas/WebhookEvent" }
                isActive: { type: boolean }
      responses:
        "200": { description: Updated }
    delete:
      tags: [Webhooks]
      summary: Delete a webhook
      operationId: deleteWebhook
      responses:
        "200": { description: Deleted }

  # ────────────────────────────────────────────────────────────────
  # METRICS
  # ────────────────────────────────────────────────────────────────
  /v1/metrics:
    get:
      tags: [Metrics]
      summary: Query metrics
      description: Returns counts (sent, received, bounced) and resource totals (inboxes, domains) for a time window. Workspace master keys are locked to their own workspace; tenant master keys can scope with query params.
      operationId: getMetrics
      parameters:
        - name: from
          in: query
          schema: { type: string, format: date-time }
          description: ISO-8601 or epoch seconds/ms. Defaults to 30 days ago.
        - name: to
          in: query
          schema: { type: string, format: date-time }
          description: ISO-8601 or epoch seconds/ms. Defaults to now.
        - name: workspace
          in: query
          schema: { type: string, format: uuid }
        - name: inbox
          in: query
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema: { $ref: "#/components/schemas/MetricsResponse" }

  # ────────────────────────────────────────────────────────────────
  # WEBSOCKET
  # ────────────────────────────────────────────────────────────────
  /v1/ws:
    get:
      tags: [WebSocket]
      summary: Open a WebSocket connection
      description: |
        Upgrade this GET to a WebSocket. After the handshake, the server
        sends a `connected` frame and the client sends a `subscribe`
        frame to start receiving events.

        This protocol is wire-compatible with agentmail.to's WebSocket
        API — `workspace_ids` also accepts `pod_ids` as an alias.

        ### Client → server frames

        ```json
        { "type": "subscribe",
          "event_types": ["message.received", "message.sent"],
          "inbox_ids":    ["..."],
          "workspace_ids": ["..."] }
        ```

        ### Server → client frames

        ```json
        { "type": "connected", "inboxId": "...", "email": "..." }
        { "type": "subscribed", "event_types": [...], "inbox_ids": [...], "workspace_ids": [...] }
        { "type": "event",
          "event_type": "message.received",
          "event_id":   "evt_...",
          "message":    { "inbox_id": "...", "thread_id": "...", "from": "...", "to": ["..."], "subject": "...", "plain_body": "...", "html_body": "...", "timestamp": "..." },
          "thread":     { "thread_id": "...", "subject": "..." } }
        { "type": "ping" }
        { "type": "error", "message": "..." }
        ```

        Use `?api_key=<key>` as a query parameter when your client
        (e.g. browser `new WebSocket`) can't set the `X-API-Key`
        header.
      operationId: openWebSocket
      responses:
        "101": { description: Switching protocols }
        "401": { $ref: "#/components/responses/Unauthorized" }

  # ────────────────────────────────────────────────────────────────
  # UTILITIES
  # ────────────────────────────────────────────────────────────────
  /v1/verify-email:
    post:
      tags: [Messages]
      summary: Check recipient deliverability
      description: "MX-probe the recipient domain(s) to filter invalid addresses before sending. Use in combination with `verified: true` on the send endpoint."
      operationId: verifyEmail
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                email: { type: string, format: email }
                emails:
                  type: array
                  items: { type: string, format: email }
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  valid: { type: boolean }
                  validAddresses: { type: array, items: { type: string } }
                  invalidAddresses: { type: array, items: { type: string } }

  # ────────────────────────────────────────────────────────────────
  # TENANTS (super admin)
  # ────────────────────────────────────────────────────────────────
  /v1/tenants:
    post:
      tags: [Tenants]
      summary: Create a tenant
      description: Super admin only. Creates a new billing root and auto-provisions its Default workspace.
      operationId: createTenant
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string }
      responses:
        "201": { description: Created }
    get:
      tags: [Tenants]
      summary: List tenants
      operationId: listTenants
      responses:
        "200": { description: OK }

  /v1/tenants/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    delete:
      tags: [Tenants]
      summary: Delete a tenant
      description: Super admin only. Cascades to everything.
      operationId: deleteTenant
      responses:
        "200": { description: Deleted }

  /linkedin/sessions:
    post:
      tags: [LinkedIn — Sessions]
      summary: Login (may challenge)
      description: |
        Begin a LinkedIn login on behalf of the customer using their email +
        password. Returns `{ ok: true, sessionId }` on direct success, or
        `{ challenge: true, challengeId, challengeType }` if LinkedIn requires
        a PIN (email/SMS) or mobile-app approval. Follow up with
        `/sessions/verify` (PIN) or `/sessions/poll` (mobile approval).
      operationId: linkedinLogin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password]
              properties:
                email:    { type: string, format: email }
                password: { type: string, format: password }
                label:    { type: string, description: "Optional friendly label for this session." }
      responses:
        "200":
          description: Either a successful login or a challenge requirement.
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    properties:
                      ok:        { type: boolean, enum: [true] }
                      sessionId: { type: string }
                      label:     { type: string, nullable: true }
                      createdAt: { type: string, format: date-time }
                  - type: object
                    properties:
                      ok:             { type: boolean, enum: [false] }
                      challenge:      { type: boolean, enum: [true] }
                      challengeId:    { type: string }
                      challengeType:  { type: string }
                      verifyEndpoint: { type: string }
                      pollEndpoint:   { type: string }
                      expiresAt:      { type: string, format: date-time }
        "401": { description: Invalid email/password. }
        "402": { description: LinkedIn module not subscribed. }
        "403": { description: Session limit reached. }
    get:
      tags: [LinkedIn — Sessions]
      summary: List sessions
      operationId: linkedinListSessions
      responses:
        "200":
          description: Array of session metadata (cookies are never returned).
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:       { type: boolean }
                  sessions:
                    type: array
                    items:
                      type: object
                      properties:
                        id:           { type: string }
                        label:        { type: string, nullable: true }
                        workspaceId:  { type: string, nullable: true }
                        status:       { type: string }
                        createdAt:    { type: string, format: date-time }
                        lastUsedAt:   { type: string, format: date-time, nullable: true }

  /linkedin/sessions/verify:
    post:
      tags: [LinkedIn — Sessions]
      summary: Submit PIN to complete a challenge
      description: Submit the email/SMS PIN LinkedIn sent to the customer.
      operationId: linkedinVerifyPin
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [challengeId, pin]
              properties:
                challengeId: { type: string }
                pin:         { type: string }
                label:       { type: string }
      responses:
        "200": { description: Session created. }
        "401": { description: Wrong PIN. }
        "404": { description: Challenge not found or expired. }

  /linkedin/sessions/poll:
    post:
      tags: [LinkedIn — Sessions]
      summary: Collect mobile-app approval
      description: |
        For mobile-approval challenges, after the customer taps "I've approved"
        in the LinkedIn mobile app. Returns 202 + `pending: true` if not yet
        approved (try again in a few seconds).
      operationId: linkedinPollMobileApproval
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [challengeId]
              properties:
                challengeId: { type: string }
                label:       { type: string }
      responses:
        "200": { description: Session created. }
        "202": { description: Approval not yet processed. }
        "404": { description: Challenge not found or expired. }

  /linkedin/sessions/import:
    post:
      tags: [LinkedIn — Sessions]
      summary: Import existing cookies
      description: |
        Escape hatch for customers who already extracted `li_at` + `JSESSIONID`
        from a logged-in browser. Skip when you can use `/sessions` instead.
      operationId: linkedinImportSession
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [liAt, jsessionId]
              properties:
                liAt:       { type: string }
                jsessionId: { type: string }
                label:      { type: string }
      responses:
        "200": { description: Session created. }

  /linkedin/sessions/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      tags: [LinkedIn — Sessions]
      summary: Get session metadata
      operationId: linkedinGetSession
      responses:
        "200": { description: Session metadata (cookies never returned). }
        "404": { description: Not found. }
    delete:
      tags: [LinkedIn — Sessions]
      summary: Revoke session
      operationId: linkedinRevokeSession
      responses:
        "200": { description: Revoked. }
        "404": { description: Not found or already revoked. }

  /linkedin/profiles/lookup:
    post:
      tags: [LinkedIn — Outreach]
      summary: Resolve profile URL
      description: |
        Resolve a LinkedIn profile URL to its `profileId`, name, headline, and
        location. Use the returned `profileId` with `/connections` for the most
        reliable connection-request results.
      operationId: linkedinLookupProfile
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sessionId, profileUrl]
              properties:
                sessionId:  { type: string }
                profileUrl: { type: string, example: "https://www.linkedin.com/in/john-doe" }
      responses:
        "200": { description: Profile data. }
        "404": { description: Session not found. }
        "429": { description: Daily quota exceeded for this session. }

  /linkedin/connections:
    post:
      tags: [LinkedIn — Outreach]
      summary: Send connection request
      description: |
        Send a LinkedIn connection request. `target` may be a profile URL
        (https://www.linkedin.com/in/slug), a slug, or an `ACoA...` profileId.
        Optional personalized message up to 300 characters significantly
        improves acceptance rates.
      operationId: linkedinSendConnection
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sessionId, target]
              properties:
                sessionId: { type: string }
                target:    { type: string, description: "Profile URL, slug, or ACoA... profileId." }
                message:   { type: string, maxLength: 300 }
      responses:
        "200": { description: Connection request created. }
        "404": { description: Session not found. }
        "429": { description: Daily quota exceeded for this session. }

    get:
      tags: [LinkedIn — Outreach]
      summary: List 1st-degree connections
      description: |
        Lists the connected account's 1st-degree connections, newest-first.
        Source for the `connection_accepted` signal kind on the cadence
        runner; usable directly by clients rendering a "connections" view.

        ## Names are included — no profile lookup needed

        Unlike the URN-only legacy LinkedIn endpoints, this response
        returns fully-resolved `firstName`, `lastName`, `fullName`,
        `headline`, and `pictureUrl` extracted server-side from
        LinkedIn's SDUI payload. Render directly.

        - `fullName`         — Convenience field, `firstName + " " + lastName`
                               with internal whitespace normalised. Use this
                               for display rather than concatenating
                               `firstName`/`lastName` yourself.
        - `connectedAt`      — ISO 8601 timestamp of when the connection
                               formed. Nullable for older connections where
                               LinkedIn doesn't surface the date.
        - `pictureUrl`       — Direct CDN URL. Nullable for accounts
                               without a photo. Stable enough to cache
                               for ~24h.
        - `publicIdentifier` — `linkedin.com/in/<slug>` segment. Build a
                               profile URL with
                               `https://www.linkedin.com/in/${publicIdentifier}/`.
        - `profileUrn`       — Use for cross-endpoint joins (matching
                               against the `participants[].urn` from
                               `GET /linkedin/conversations`, or against
                               `connection_accepted` signal payloads).

        ## Pagination

        Newest-first. `start=0,count=50` returns the most recent 50.
        LinkedIn's SDUI pager returns ~10 per page internally; this
        endpoint paginates server-side to satisfy `count` up to the cap of
        100. For larger backfills, page through with `start` increments.

        ## Worked example response

        ```json
        {
          "ok": true,
          "total": 234,
          "count": 2,
          "start": 0,
          "connections": [
            {
              "profileUrn": "urn:li:fsd_profile:ACoAAA…aaaa",
              "publicIdentifier": "jane-doe-1a2b3c",
              "firstName": "Jane",
              "lastName": "Doe",
              "fullName": "Jane Doe",
              "headline": "Head of Sales at Acme",
              "connectedAt": "2026-05-12T14:23:00Z",
              "pictureUrl": "https://media.licdn.com/dms/image/v2/…/headshot.jpg"
            },
            {
              "profileUrn": "urn:li:fsd_profile:ACoAAA…bbbb",
              "publicIdentifier": "john-smith-4d5e6f",
              "firstName": "John",
              "lastName": "Smith",
              "fullName": "John Smith",
              "headline": "Founder & CEO at Beta",
              "connectedAt": "2026-05-10T09:14:00Z",
              "pictureUrl": null
            }
          ]
        }
        ```
      operationId: linkedinListConnections
      parameters:
        - { name: sessionId, in: query, required: true, schema: { type: string } }
        - name: count
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
          description: Page size. Server internally paginates LinkedIn's 10-per-page SDUI pager to satisfy this.
        - name: start
          in: query
          schema: { type: integer, minimum: 0, default: 0 }
          description: 0-based offset.
      responses:
        "200":
          description: Array of connections.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:    { type: boolean }
                  total: { type: integer, description: "Approximate total count of 1st-degree connections (LinkedIn's count, when surfaced)." }
                  count: { type: integer, description: "Items in this `connections` array." }
                  start: { type: integer }
                  connections:
                    type: array
                    items:
                      type: object
                      properties:
                        profileUrn:
                          type: string
                          example: "urn:li:fsd_profile:ACoAAA…aaaa"
                          description: Cross-endpoint identity key.
                        publicIdentifier:
                          type: string
                          example: "jane-doe-1a2b3c"
                          description: "`linkedin.com/in/<slug>` segment."
                        firstName: { type: string }
                        lastName:  { type: string }
                        fullName:
                          type: string
                          description: Convenience; prefer this for display.
                        headline:
                          type: string
                          description: LinkedIn's one-line tagline. May be empty string.
                        connectedAt:
                          type: string
                          format: date-time
                          nullable: true
                          description: ISO 8601. Null for older connections where LinkedIn omits the date.
                        pictureUrl:
                          type: string
                          format: uri
                          nullable: true
                          description: Direct CDN URL. Null for accounts without a photo.

  /linkedin/invitations/sent:
    get:
      tags: [LinkedIn — Outreach]
      summary: List pending sent invitations
      description: |
        Lists the connected account's outbound connection invitations that
        are still pending (haven't been accepted, rejected, or withdrawn).
        Drives the `connection_accepted` signal kind on the cadence runner
        side; usable directly by clients rendering a "sent invitations"
        view.

        ## Response shape — names included

        Unlike older URN-only LinkedIn list endpoints, this one returns
        **resolved recipient identity** already extracted server-side
        from LinkedIn's SDUI payload — no follow-up `profile/lookup`
        round-trip needed:

        - `recipientName`              — Display name parsed from the
                                         `aria-label="Withdraw invitation
                                         sent to NAME"` anchor LinkedIn
                                         renders on each row. Always a
                                         non-empty string for valid
                                         invitations.
        - `recipientPublicIdentifier`  — `linkedin.com/in/<slug>` segment.
                                         Build the profile URL as
                                         `https://www.linkedin.com/in/${slug}/`.
        - `recipientUrn`               — `urn:li:fsd_profile:ACoA…`. Use
                                         when calling other LinkedIn API
                                         endpoints that take a profile URN.
        - `invitationUrn`              — `urn:li:fsd_invitation:<numeric>`.
                                         Stable identifier for the
                                         invitation itself (used for
                                         withdraw on the LinkedIn side; not
                                         currently exposed as an Anjal
                                         endpoint).
        - `recipientHeadline`          — Currently always empty string —
                                         the SDUI payload puts the headline
                                         in a separate textProps block we
                                         don't parse yet. Don't rely on it.
        - `sentAt`                     — Currently always `null` —
                                         LinkedIn's sent-invitations SDUI
                                         page doesn't expose the original
                                         send timestamp. Don't rely on it.
        - `message`                    — Currently always `null` — original
                                         invitation note isn't in the SDUI
                                         payload either. Don't rely on it.
        - `state`                      — Always `"pending"` for invitations
                                         returned by this endpoint
                                         (LinkedIn's SDUI page only lists
                                         pending). The type union includes
                                         `accepted | withdrawn | rejected |
                                         expired | unknown` for internal
                                         reconciliation use, but the public
                                         response only ever surfaces
                                         `pending`.

        ## Pagination

        - `count`  — page size, max 50, default 50
        - `start`  — 0-based offset

        LinkedIn's SDUI page embeds ~20 invitations per response. Asking
        for `count > 20` may return fewer than requested; treat `total`
        as advisory rather than authoritative.

        ## Worked example response

        ```json
        {
          "ok": true,
          "total": 3,
          "count": 3,
          "start": 0,
          "invitations": [
            {
              "invitationUrn": "urn:li:fsd_invitation:7195484920123456789",
              "recipientUrn": "urn:li:fsd_profile:ACoAAA…aaaa",
              "recipientPublicIdentifier": "jane-doe-1a2b3c",
              "recipientName": "Jane Doe",
              "recipientHeadline": "",
              "state": "pending",
              "sentAt": null,
              "message": null
            },
            {
              "invitationUrn": "urn:li:fsd_invitation:7195484921987654321",
              "recipientUrn": "urn:li:fsd_profile:ACoAAA…bbbb",
              "recipientPublicIdentifier": "john-smith-4d5e6f",
              "recipientName": "John Smith",
              "recipientHeadline": "",
              "state": "pending",
              "sentAt": null,
              "message": null
            }
          ]
        }
        ```

        ## Rendering recipe

        ```ts
        const { invitations } = await mam.linkedinListSentInvitations({ sessionId });
        for (const inv of invitations) {
          const profileUrl = `https://www.linkedin.com/in/${inv.recipientPublicIdentifier}/`;
          render({
            name: inv.recipientName,
            profileUrl,
            withdrawUrl: profileUrl,   // LinkedIn's withdraw lives on the recipient's profile UI
          });
        }
        ```
      operationId: linkedinListSentInvitations
      parameters:
        - { name: sessionId, in: query, required: true, schema: { type: string } }
        - name: count
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 50, default: 50 }
          description: Page size. Capped at 50; LinkedIn returns ~20 per SDUI response so larger counts may under-fill.
        - name: start
          in: query
          required: false
          schema: { type: integer, minimum: 0, default: 0 }
          description: 0-based offset for pagination.
      responses:
        "200":
          description: Pending invitations.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:    { type: boolean }
                  total:
                    type: integer
                    description: Total count of pending invitations on this page response. Advisory; LinkedIn doesn't expose a true overall count.
                  count:
                    type: integer
                    description: Number of items in the `invitations` array.
                  start:
                    type: integer
                    description: 0-based offset of this page.
                  invitations:
                    type: array
                    items:
                      type: object
                      properties:
                        invitationUrn:
                          type: string
                          description: "`urn:li:fsd_invitation:<numeric>`. Stable identifier."
                        recipientUrn:
                          type: string
                          description: "`urn:li:fsd_profile:ACoA…`. Use for cross-endpoint joins (e.g. matching against connection_accepted signal payloads)."
                        recipientPublicIdentifier:
                          type: string
                          description: |
                            `linkedin.com/in/<slug>` segment. Build the profile URL as
                            `https://www.linkedin.com/in/${recipientPublicIdentifier}/`.
                        recipientName:
                          type: string
                          description: Display name parsed from LinkedIn's `aria-label`. Always non-empty for valid invitations.
                        recipientHeadline:
                          type: string
                          description: Currently always empty string — the headline isn't in the SDUI payload we parse. Don't rely on this field.
                        state:
                          type: string
                          enum: [pending]
                          description: Always `pending` — LinkedIn's SDUI page only lists pending invitations.
                        sentAt:
                          type: string
                          nullable: true
                          description: Currently always `null` — LinkedIn doesn't expose the original send timestamp on this page.
                        message:
                          type: string
                          nullable: true
                          description: Currently always `null` — the original invitation note isn't in the SDUI payload.

  /linkedin/messages:
    post:
      tags: [LinkedIn — Outreach]
      summary: Send a DM
      description: |
        Send a direct message. Recipient must be a 1st-degree connection
        (LinkedIn rejects non-1st sends; the upstream error surfaces verbatim).

        Pass exactly one of:
        - `recipient` (preferred): profile URL, slug, ACoA... profileId, or
          full URN. The backend resolves and does find-or-create on the
          1:1 thread.
        - `conversationUrn` (advanced): append to a known thread you
          already have an URN for, e.g. from a previous send response or
          from `GET /v1/linkedin/conversations`.
      operationId: linkedinSendMessage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sessionId, text]
              properties:
                sessionId:       { type: string }
                text:            { type: string, maxLength: 8000 }
                recipient:       { type: string, description: "Profile URL, slug, ACoA... profileId, or full URN." }
                conversationUrn: { type: string, description: "urn:li:msg_conversation:(...) — append to known thread." }
      responses:
        "200":
          description: Message sent.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:                       { type: boolean }
                  messageUrn:               { type: string }
                  conversationUrn:          { type: string }
                  backendConversationUrn:   { type: string }
                  deliveredAt:              { type: integer, description: Unix ms. }
        "400": { description: Validation error or LinkedIn rejected the send. }
        "404": { description: Session not found. }
        "429": { description: Daily quota exceeded for this session. }

  /linkedin/conversations:
    get:
      tags: [LinkedIn — Outreach]
      summary: List inbox conversations
      description: |
        Returns the most recent ~20 conversations on the connected account.

        ## Response shape — read this before parsing

        The response returns **two parallel views** of the people in each
        thread:

        - **`participants[]`** — preferred. Already enriched with `name`,
          `slug`, and `headline` extracted from the LinkedIn payload server-
          side, **with zero extra API calls.** Use these for rendering.
        - **`participantUrns[]`** — back-compat, URN strings only.

        There is **no** `participant.name` at the top level, no `peer`, no
        `otherPerson`, no `lastMessage.snippet`, no `last_message` field. If
        you normalise against those, every contact renders as "(unnamed)".

        Field map (exact names, camelCase):

        - `conversationUrn`     — `urn:li:msg_conversation:(...)`. Pass this to
                                  `GET /linkedin/conversations/{conversationUrn}/messages`.
                                  Always URL-encode when used as a path parameter.
        - `participants[]`      — Enriched: `{ urn, name, slug, headline }`. Any
                                  of name/slug/headline may be `null` (deleted
                                  accounts, restricted profiles), but `urn` is
                                  always present.
        - `participantUrns[]`   — Mirror of `participants[].urn`. Kept for
                                  back-compat with clients written before the
                                  enrichment landed.
        - `title`               — Group chat title only. **Null on 1-on-1
                                  conversations.** Don't fall back to this for
                                  the contact name; use `participants` instead.
        - `lastMessage.text`    — Plain text body. Not `snippet`, not `preview`,
                                  not `bodyText`.
        - `lastMessage.senderName` — Display name of the sender of the latest
                                  message. Already resolved server-side; null
                                  only when LinkedIn omits the inline profile.
        - `lastMessage.senderUrn` — URN of the same sender.
        - `lastActivityAt`, `lastReadAt`, `lastMessage.deliveredAt` — Unix **ms**,
                                  not seconds. Nullable for system-initiated
                                  threads.

        ## Worked example response

        ```json
        {
          "ok": true,
          "conversations": [
            {
              "conversationUrn": "urn:li:msg_conversation:(urn:li:fsd_profile:ACoAAA…,2-MWE…)",
              "backendUrn": "urn:li:fs_conversation:2-MWE…",
              "isGroup": false,
              "title": null,
              "lastActivityAt": 1715990400000,
              "lastReadAt": 1715990405000,
              "unreadCount": 1,
              "read": false,
              "participants": [
                {
                  "urn": "urn:li:fsd_profile:ACoAAA…aaaa",
                  "name": "Jane Doe",
                  "slug": "jane-doe-1a2b3c",
                  "headline": "Head of Sales at Acme"
                },
                {
                  "urn": "urn:li:fsd_profile:ACoAAA…me",
                  "name": "Me",
                  "slug": "me-1a2b3c",
                  "headline": null
                }
              ],
              "participantUrns": [
                "urn:li:fsd_profile:ACoAAA…aaaa",
                "urn:li:fsd_profile:ACoAAA…me"
              ],
              "lastMessage": {
                "messageUrn": "urn:li:msg_message:(urn:li:fsd_profile:ACoAAA…,2-MWE…)",
                "text": "Sure, happy to chat — Tuesday at 2pm work?",
                "senderUrn": "urn:li:fsd_profile:ACoAAA…aaaa",
                "senderName": "Jane Doe",
                "deliveredAt": 1715990400000
              }
            }
          ]
        }
        ```

        ## Rendering the contact name (1-on-1 thread)

        Filter your own viewer URN out of `participants`, then read `name`
        directly. No profile-lookup round-trip needed:

        ```ts
        const { conversations } = await client.linkedinListConversations({ sessionId });
        const viewerUrn = (await client.linkedinGetSession({ id: sessionId })).viewerProfileUrn;

        for (const c of conversations) {
          const other = c.participants.find(p => p.urn !== viewerUrn);
          const displayName = other?.name
            ?? (c.isGroup && c.title)
            ?? "(unknown)";
          // …render
        }
        ```

        For group chats, prefer `title`; if absent (rare), join the other
        participants' names with commas. For the rare case where
        `participants[i].name` is null (deleted / restricted), fall back to
        `POST /linkedin/profile/lookup` with the URN — but you'll only need
        that on a handful of edge cases, not every conversation.
      operationId: linkedinListConversations
      parameters:
        - { name: sessionId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: Array of conversations.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  conversations:
                    type: array
                    items:
                      type: object
                      properties:
                        conversationUrn:
                          type: string
                          description: "`urn:li:msg_conversation:(…)`. URL-encode when used as a path parameter."
                        backendUrn:
                          type: string
                          description: Internal backend ref. Not usable as a path param.
                        isGroup:
                          type: boolean
                          description: True for 3+ participants.
                        title:
                          type: string
                          nullable: true
                          description: Group chat title. **Null on 1-on-1 conversations** — don't display as the contact name.
                        lastActivityAt:
                          type: integer
                          nullable: true
                          description: Unix **ms** (not seconds). Time of the most recent message or system event.
                        lastReadAt:
                          type: integer
                          nullable: true
                          description: Unix ms when the viewer last read this thread.
                        unreadCount:
                          type: integer
                          description: Messages the viewer hasn't read yet.
                        read:
                          type: boolean
                        participants:
                          type: array
                          description: |
                            Enriched participant list — extracted server-side from the
                            same Voyager payload, so no extra API calls or `profile_lookup`
                            budget is spent. Includes the viewer themselves; filter them
                            out by comparing each URN against the viewer URN (available
                            via GET /linkedin/sessions/{id}). For the rare null `name`
                            (deleted / restricted accounts), fall back to
                            POST /linkedin/profile/lookup with the URN.
                          items:
                            type: object
                            properties:
                              urn:
                                type: string
                                description: "`urn:li:fsd_profile:xxxx`."
                              name:
                                type: string
                                nullable: true
                                description: Display name, typically `"First Last"`. Null when LinkedIn omits the inline profile.
                              slug:
                                type: string
                                nullable: true
                                description: |
                                  `linkedin.com/in/<slug>` segment when LinkedIn includes
                                  `publicIdentifier` inline; otherwise the trailing URN
                                  token as a fallback (opaque but stable for keying).
                              headline:
                                type: string
                                nullable: true
                                description: One-line title shown next to the participant on LinkedIn.
                        participantUrns:
                          type: array
                          items: { type: string }
                          description: |
                            URN-only list, mirror of `participants[].urn`. Retained for
                            back-compat with clients written before the enrichment landed —
                            prefer `participants` for new code.
                        lastMessage:
                          type: object
                          nullable: true
                          description: Null when LinkedIn has no rendered preview (rare — system threads).
                          properties:
                            messageUrn: { type: string }
                            text:
                              type: string
                              description: Plain text. Not `snippet` / `preview` / `bodyText`.
                            senderUrn:
                              type: string
                              description: URN of the sender.
                            senderName:
                              type: string
                              nullable: true
                              description: |
                                Display name of the sender of the latest message,
                                resolved server-side from the same Voyager payload.
                                Null when LinkedIn omits the inline profile (rare).
                            deliveredAt:
                              type: integer
                              nullable: true
                              description: Unix ms.

  /linkedin/conversations/{conversationUrn}/messages:
    get:
      tags: [LinkedIn — Outreach]
      summary: Read messages in a conversation
      description: |
        Read messages in one thread, most-recent first.

        ## URL-encode the path parameter

        `conversationUrn` contains parens and colons — both are reserved
        characters in URL paths. Always wrap in `encodeURIComponent()`
        before constructing the URL:

        ```ts
        const encoded = encodeURIComponent(conv.conversationUrn);
        const r = await fetch(`/v1/linkedin/conversations/${encoded}/messages?sessionId=${sessionId}`);
        ```

        ## Response shape

        Unlike `GET /linkedin/conversations`, this endpoint **does** return
        `senderName` and `senderSlug` for most messages — LinkedIn embeds
        the sender's display data in the message payload. They're still
        nullable for system-generated messages (e.g. "X joined the
        conversation"), so guard before rendering.

        Field map (exact names, camelCase):

        - `messageUrn`        — `urn:li:msg_message:(…)`. Stable identifier
                                for reaction / attachment lookups.
        - `text`              — Plain text body. Empty string for attachment-
                                only messages (check `attachmentCount > 0`).
        - `senderUrn`         — Profile URN. Null only on system messages.
        - `senderName`        — Display name; usually `"First Last"`.
                                Nullable.
        - `senderSlug`        — `linkedin.com/in/<slug>` segment. Nullable.
                                Useful when you want to build a profile URL
                                without a separate lookup.
        - `isFromViewer`      — `true` when sent by the authenticated session
                                holder. Use this for left/right bubble layout.
        - `deliveredAt`       — Unix **ms** (not seconds). Nullable.

        ## Worked example response

        ```json
        {
          "ok": true,
          "conversationUrn": "urn:li:msg_conversation:(urn:li:fsd_profile:ACoAAA…,2-MWE…)",
          "messages": [
            {
              "messageUrn": "urn:li:msg_message:(urn:li:fsd_profile:ACoAAA…,2-MWE…)",
              "conversationUrn": "urn:li:msg_conversation:(urn:li:fsd_profile:ACoAAA…,2-MWE…)",
              "text": "Sure, happy to chat — Tuesday at 2pm work?",
              "deliveredAt": 1715990400000,
              "senderUrn": "urn:li:fsd_profile:ACoAAA…aaaa",
              "senderName": "Jane Doe",
              "senderSlug": "jane-doe-1a2b3c",
              "attachmentCount": 0,
              "reactionCount": 0,
              "isFromViewer": false
            },
            {
              "messageUrn": "urn:li:msg_message:(urn:li:fsd_profile:ACoAAA…,2-XYZ…)",
              "conversationUrn": "urn:li:msg_conversation:(urn:li:fsd_profile:ACoAAA…,2-MWE…)",
              "text": "Hey Jane — quick one about your team's cold outbound setup. Got 5 minutes this week?",
              "deliveredAt": 1715986800000,
              "senderUrn": "urn:li:fsd_profile:ACoAAA…me",
              "senderName": "Me",
              "senderSlug": "me-1a2b3c",
              "attachmentCount": 0,
              "reactionCount": 0,
              "isFromViewer": true
            }
          ]
        }
        ```
      operationId: linkedinListConversationMessages
      parameters:
        - name: conversationUrn
          in: path
          required: true
          schema: { type: string }
          description: |
            URL-encoded `urn:li:msg_conversation:(…)` — pass through
            `encodeURIComponent()` before substituting. Source: the
            `conversationUrn` field on each conversation returned by
            `GET /linkedin/conversations`.
        - { name: sessionId, in: query, required: true, schema: { type: string } }
      responses:
        "200":
          description: Thread messages, newest first.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:               { type: boolean }
                  conversationUrn:  { type: string }
                  messages:
                    type: array
                    items:
                      type: object
                      properties:
                        messageUrn:
                          type: string
                          description: "`urn:li:msg_message:(…)`. Stable identifier."
                        conversationUrn:
                          type: string
                          description: Echoes the path parameter; convenient for downstream filtering.
                        text:
                          type: string
                          description: Plain text body. Empty string for attachment-only messages — check `attachmentCount > 0`.
                        deliveredAt:
                          type: integer
                          nullable: true
                          description: Unix **ms** (not seconds).
                        senderUrn:
                          type: string
                          nullable: true
                          description: Profile URN. Null only on system messages.
                        senderName:
                          type: string
                          nullable: true
                          description: Display name, typically `"First Last"`. Null on system messages.
                        senderSlug:
                          type: string
                          nullable: true
                          description: |
                            `linkedin.com/in/<slug>` segment. Build a profile URL
                            with `https://www.linkedin.com/in/${senderSlug}/`
                            instead of doing a separate lookup.
                        attachmentCount:
                          type: integer
                          description: Number of files/images in this message. Non-zero with empty `text` = attachment-only.
                        reactionCount:
                          type: integer
                          description: Total emoji reactions on this message.
                        isFromViewer:
                          type: boolean
                          description: |
                            `true` when sent by the authenticated session holder. Use this
                            for left/right bubble layout rather than comparing `senderUrn`
                            against the viewer URN.

  /linkedin/search/content:
    post:
      tags: [LinkedIn — Outreach]
      summary: Keyword post search
      description: |
        Search LinkedIn posts for a keyword and return posts with their
        author's name, profile URL, post URL, time-ago, and a short excerpt.
        Useful for keyword monitoring + just-in-time outreach.
      operationId: linkedinSearchContent
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sessionId, keyword]
              properties:
                sessionId:   { type: string }
                keyword:     { type: string }
                datePosted:  { type: string, enum: [past-24h, past-week, past-month, any], default: "past-24h" }
                count:       { type: integer, minimum: 1, maximum: 25, default: 10 }
      responses:
        "200":
          description: Posts matching the keyword.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:    { type: boolean }
                  posts:
                    type: array
                    items:
                      type: object
                      properties:
                        activityUrn:       { type: string }
                        postUrl:           { type: string }
                        authorName:        { type: string }
                        authorProfileUrl:  { type: string }
                        authorProfileSlug: { type: string }
                        timeAgo:           { type: string, example: "23h" }
                        excerpt:           { type: string }
        "404": { description: Session not found. }
        "429": { description: Daily quota exceeded for this session. }

  /linkedin/posts:
    post:
      tags: [LinkedIn — Posts]
      summary: Publish a new post on the connected account's feed
      description: |
        Creates a feed post on the connected LinkedIn account. Text is
        required; an inline image is optional. The endpoint handles the
        underlying three-step LinkedIn upload flow (register upload → PUT bytes →
        create share) so the customer just sends one JSON request.

        **Visibility:**
        - `ANYONE` (default) — public on the feed.
        - `CONNECTIONS` — visible to 1st-degree connections only.

        **Image:**
        Pass an `image.dataUrl` (full data URL with embedded mime + base64) for
        the simplest agent shape, OR a separate `image.base64` + `image.contentType`.
        Accepts `image/png`, `image/jpeg`, `image/gif`, `image/webp` up to ~10 MB.

        Quota: 1 `connection_request` slot per call (shared outbound-write
        bucket).
      operationId: linkedinCreatePost
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sessionId, text]
              properties:
                sessionId: { type: string }
                text:
                  type: string
                  minLength: 1
                  maxLength: 3000
                  description: Post commentary. LinkedIn caps at 3000 characters.
                visibility:
                  type: string
                  enum: [ANYONE, CONNECTIONS]
                  default: ANYONE
                image:
                  type: object
                  description: |
                    Optional inline image. Pass either `dataUrl` (preferred — embeds
                    mime + base64 in one field) or `base64` + `contentType`.
                  properties:
                    dataUrl:
                      type: string
                      description: 'Full data URL, e.g. "data:image/png;base64,iVBORw0KG..."'
                    base64:
                      type: string
                      description: Bare base64-encoded bytes (no `data:` prefix).
                    contentType:
                      type: string
                      description: Required when using `base64`. Ignored when using `dataUrl`.
                      enum: [image/png, image/jpeg, image/gif, image/webp]
                    altText:
                      type: string
                      maxLength: 420
                      description: Accessibility alt-text on the rendered post.
                    filename:
                      type: string
                      maxLength: 255
      responses:
        "200":
          description: Post created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  shareUrn: { type: string, example: "urn:li:share:7455538267644641280" }
                  shareId: { type: string }
                  postUrl: { type: string, format: uri }
                  mediaUrn: { type: string, nullable: true, description: Set when an image was uploaded. }
        "400":
          description: |
            Validation error or LinkedIn rejected the post. Real LinkedIn
            errors are surfaced verbatim in `error` (e.g. commentary too
            long, invalid visibility enum).
        "404": { description: Session not found. }
        "429": { description: Daily quota exceeded for this session. }

  /linkedin/posts/by-author:
    get:
      tags: [LinkedIn — Posts]
      summary: List recent posts by a profile or company
      description: |
        Pull the most recent posts authored by a LinkedIn profile or
        company page. Same helper the engagement-signal runner uses
        internally; exposed as a GET so agents can do one-shot lookups
        ("show me Acme's last 5 posts") without spinning up a recurring
        signal.

        `profileUrl` accepts either a profile URL
        (`https://www.linkedin.com/in/<slug>/`) or a company URL
        (`https://www.linkedin.com/company/<slug>/`). The route resolves
        to a `urn:li:fsd_profile:` or `urn:li:fsd_company:` URN
        automatically.

        Quota: each call burns one `engagement_poll` slot from the
        per-session daily budget.
      operationId: linkedinListPostsByAuthor
      parameters:
        - { name: sessionId, in: query, required: true, schema: { type: string } }
        - { name: profileUrl, in: query, required: true, schema: { type: string } }
        - { name: count, in: query, schema: { type: integer, minimum: 1, maximum: 20, default: 20 } }
        - { name: sinceUrn, in: query, schema: { type: string }, description: "Watermark — return only posts whose activityUrn is newer than this." }
      responses:
        "200":
          description: Author identity + array of posts (newest first).
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:    { type: boolean }
                  author:
                    type: object
                    properties:
                      kind:  { type: string, enum: [profile, company] }
                      urn:   { type: string }
                      label: { type: string }
                  count: { type: integer }
                  posts:
                    type: array
                    items:
                      type: object
                      properties:
                        activityUrn: { type: string, example: "urn:li:activity:7332661864792854528" }
                        postedAt:    { type: integer, nullable: true, description: "Unix ms; null when LinkedIn omits it." }
                        excerpt:     { type: string }
        "400": { description: Could not resolve the profile/company URL. }
        "404": { description: Session not found. }
        "429": { description: Daily quota exceeded for this session. }

  /linkedin/posts/{postUrn}/comments:
    get:
      tags: [LinkedIn — Posts]
      summary: List comments on a post
      description: |
        Fetch commenters on a LinkedIn post. Returns the engager array
        (profile URN, name, headline, comment text), plus the total
        reported by LinkedIn. Same helper the engagement signal uses
        to enumerate commenters on tracked actor posts.

        `postUrn` is the activity URN — `urn:li:activity:<id>`. URL-
        encode it (the `:` characters need to be `%3A` in path
        position).

        Quota: one `engagement_poll` slot per call.
      operationId: linkedinListPostComments
      parameters:
        - { name: postUrn, in: path, required: true, schema: { type: string }, description: "URL-encoded urn:li:activity:<id>" }
        - { name: sessionId, in: query, required: true, schema: { type: string } }
        - { name: count, in: query, schema: { type: integer, minimum: 1, maximum: 50, default: 20 } }
      responses:
        "200":
          description: Commenters + total comment count reported by LinkedIn.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:      { type: boolean }
                  postUrn: { type: string }
                  total:   { type: integer, nullable: true, description: "LinkedIn-reported total. May be null if the count call failed." }
                  count:   { type: integer, description: "Number of commenters returned in this page." }
                  comments:
                    type: array
                    items:
                      type: object
                      properties:
                        profileUrn:  { type: string }
                        slug:        { type: string }
                        name:        { type: string }
                        headline:    { type: string }
                        commentText: { type: string }
                        postedAt:    { type: integer, nullable: true }
        "404": { description: Session not found. }
        "429": { description: Daily quota exceeded for this session. }

  /linkedin/posts/{postUrn}/reactions:
    get:
      tags: [LinkedIn — Posts]
      summary: List reactions on a post
      description: |
        Fetch reactors on a LinkedIn post. Returns each reactor's
        profile URN, name, headline, and reaction type
        (`LIKE` / `CELEBRATE` / `SUPPORT` / `LOVE` / `INSIGHTFUL` /
        `FUNNY`).

        Quota: one `engagement_poll` slot per call. LinkedIn's per-call
        rate-limiter cares about call count, not response size — large
        `count` values are no more expensive than small ones.
      operationId: linkedinListPostReactions
      parameters:
        - { name: postUrn, in: path, required: true, schema: { type: string }, description: "URL-encoded urn:li:activity:<id>" }
        - { name: sessionId, in: query, required: true, schema: { type: string } }
        - { name: count, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 100 } }
      responses:
        "200":
          description: Array of reactors.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:      { type: boolean }
                  postUrn: { type: string }
                  count:   { type: integer }
                  reactions:
                    type: array
                    items:
                      type: object
                      properties:
                        profileUrn:   { type: string }
                        slug:         { type: string }
                        name:         { type: string }
                        headline:     { type: string }
                        reactionType: { type: string, example: LIKE }
        "404": { description: Session not found. }
        "429": { description: Daily quota exceeded for this session. }

  /linkedin/sessions/utilization:
    get:
      tags: [LinkedIn — Sessions]
      summary: Per-session quota utilization
      description: |
        Returns each active LinkedIn session for the tenant with its
        action counts in the trailing 24 hours and the remaining daily
        budget per action type. Drives the "Today's utilization" panel
        in the dashboard and lets you decide when connecting another
        LinkedIn account would add headroom.

        Sessions used: search_signal (recurring polls), search_history
        (one-shot lookups), profile_lookup (Pass-2 verification),
        connection_request, send_message, post_like.
      operationId: linkedinSessionUtilization
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:     { type: boolean }
                  budget:
                    type: object
                    additionalProperties: { type: integer }
                    description: "Per-action daily budget per session (the operator's safety cap)."
                  sessions:
                    type: array
                    items: { $ref: "#/components/schemas/LinkedInSessionUtilization" }

  /linkedin/signals:
    get:
      tags: [LinkedIn — Signals]
      summary: List signals
      description: List all intent signals for the authenticated tenant.
      operationId: linkedinListSignals
      responses:
        "200":
          description: Signals owned by the tenant.
          content:
            application/json:
              schema:
                type: object
                properties:
                  signals:
                    type: array
                    items: { $ref: "#/components/schemas/LinkedInSignal" }
    post:
      tags: [LinkedIn — Signals]
      summary: Create a signal
      description: |
        Create a real-time intent watcher. We poll LinkedIn on the chosen
        cadence using the named session, classify each NEW post against
        the keyword, and (if a webhookUrl is set) POST high-intent matches
        to your endpoint with an HMAC-SHA256 signature. The lookback window
        is fixed at 24 hours — for historical lookups across a wider window
        use POST /v1/linkedin/searches instead.
      operationId: linkedinCreateSignal
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, intentDescription]
              properties:
                name:              { type: string, maxLength: 255 }
                kind:
                  type: string
                  enum: [keyword, engagement, job_change_watchlist]
                  default: keyword
                  description: |
                    keyword (default) — saved keyword search.
                    engagement — watch a profile/company for engagers; requires `target`.
                    job_change_watchlist — watch a list of profiles for role/company changes; requires `watchlist`.
                query:             { type: string, minLength: 2, maxLength: 500, description: "Required when kind=keyword." }
                target:
                  type: object
                  description: "Required when kind=engagement."
                  properties:
                    kind:  { type: string, enum: [profile, company] }
                    url:   { type: string, format: uri }
                    label: { type: string, maxLength: 255 }
                  required: [kind, url]
                watchlist:
                  type: array
                  description: "Required when kind=job_change_watchlist. Up to 500 entries."
                  maxItems: 500
                  items:
                    type: object
                    properties:
                      profileUrl: { type: string, format: uri }
                      label:      { type: string, maxLength: 255 }
                    required: [profileUrl]
                sessionId:
                  type: string
                  nullable: true
                  description: |
                    Omit or send null to auto-distribute polling across
                    every healthy LinkedIn session for this tenant
                    (recommended — multiplies daily throughput by the
                    number of connected accounts and protects each
                    individual account from rate limits). Pass a
                    specific session id to pin all polls for this
                    signal to that account.
                cadence:           { type: string, enum: [daily, every_12h, every_6h, manual], default: daily }
                webhookUrl:        { type: string, format: uri, nullable: true }
                filterMinIntent:   { type: string, enum: [low, medium, high], default: medium }
                intentDescription:
                  type: string
                  minLength: 1
                  maxLength: 2000
                  description: |
                    Plain-English firing rule the LLM classifier treats as
                    the authoritative definition of what should fire.
                    Example: "Flag as ready when the author is a founder/
                    operator complaining about cold email — skip vendors,
                    agencies, and content marketers."
      responses:
        "201":
          description: |
            Created signal. webhookSecret is returned ONCE on creation when
            webhookUrl is set — store it now to verify webhook signatures.
          content:
            application/json:
              schema:
                type: object
                properties:
                  signal: { $ref: "#/components/schemas/LinkedInSignal" }
        "403": { description: Signal limit reached for the tenant's tier. }
        "404": { description: LinkedIn session not found or inactive. }

  /linkedin/signals/{id}:
    get:
      tags: [LinkedIn — Signals]
      summary: Fetch a signal
      operationId: linkedinGetSignal
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  signal: { $ref: "#/components/schemas/LinkedInSignal" }
        "404": { description: Not found. }
    patch:
      tags: [LinkedIn — Signals]
      summary: Update a signal
      operationId: linkedinUpdateSignal
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:              { type: string }
                query:             { type: string }
                sessionId:         { type: string, nullable: true, description: "null to switch to auto-distribute, or a session id to pin." }
                cadence:           { type: string, enum: [daily, every_12h, every_6h, manual] }
                webhookUrl:        { type: string, format: uri, nullable: true }
                filterMinIntent:   { type: string, enum: [low, medium, high] }
                intentDescription: { type: string, minLength: 1, maxLength: 2000 }
                enabled:           { type: boolean }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  signal: { $ref: "#/components/schemas/LinkedInSignal" }
        "404": { description: Not found. }
    delete:
      tags: [LinkedIn — Signals]
      summary: Delete a signal
      operationId: linkedinDeleteSignal
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      responses:
        "200": { description: Deleted. }
        "404": { description: Not found. }

  /linkedin/signals/{id}/run:
    post:
      tags: [LinkedIn — Signals]
      summary: Run a signal now
      description: Force an immediate poll regardless of cadence. Useful for testing.
      operationId: linkedinRunSignal
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: object
                    properties:
                      ok:             { type: boolean }
                      fetched:        { type: integer }
                      newMatches:     { type: integer }
                      webhooksQueued: { type: integer }
                      errorCode:      { type: string, nullable: true }
                      errorMessage:   { type: string, nullable: true }

  /linkedin/signals/{id}/matches:
    get:
      tags: [LinkedIn — Signals]
      summary: List matches for a signal
      description: All historical matches for this signal, newest first. Pull-based alternative to webhooks.
      operationId: linkedinSignalMatches
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
        - in: query
          name: limit
          schema: { type: integer, default: 50, maximum: 500 }
        - in: query
          name: sinceId
          schema: { type: string }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  matches:
                    type: array
                    items: { $ref: "#/components/schemas/LinkedInSignalMatch" }

  /linkedin/signals/{id}/deliveries:
    get:
      tags: [LinkedIn — Signals]
      summary: Webhook delivery log
      operationId: linkedinSignalDeliveries
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
        - in: query
          name: status
          schema: { type: string, enum: [pending, success, failed, exhausted] }
        - in: query
          name: limit
          schema: { type: integer, default: 50 }

  /linkedin/signals/{id}/test-webhook:
    post:
      tags: [LinkedIn — Signals]
      summary: Send a synthetic webhook payload
      description: Fires a `signal.match.test` event to the configured webhook URL so you can verify the endpoint before any real match.
      operationId: linkedinSignalTestWebhook
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:           { type: boolean }
                  status:       { type: integer }
                  responseBody: { type: string }
        "400": { description: Signal has no webhook URL configured. }

  /linkedin/signals/{id}/watchlist:
    get:
      tags: [LinkedIn — Signals]
      summary: List watchlist entries
      description: List all profile entries on a watchlist signal, with last-known role/company.
      operationId: linkedinSignalWatchlistList
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  entries:
                    type: array
                    items: { $ref: "#/components/schemas/LinkedInWatchlistEntry" }
        "400": { description: Signal is not a watchlist signal. }
    post:
      tags: [LinkedIn — Signals]
      summary: Add watchlist entries
      operationId: linkedinSignalWatchlistAdd
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [entries]
              properties:
                entries:
                  type: array
                  minItems: 1
                  maxItems: 500
                  items:
                    type: object
                    properties:
                      profileUrl: { type: string, format: uri }
                      label:      { type: string, maxLength: 255 }
                    required: [profileUrl]
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  added:   { type: integer }
                  skipped: { type: integer, description: "Duplicates or invalid URLs." }
                  entries:
                    type: array
                    items: { $ref: "#/components/schemas/LinkedInWatchlistEntry" }

  /linkedin/signals/{id}/watchlist/{entryId}:
    delete:
      tags: [LinkedIn — Signals]
      summary: Remove a watchlist entry
      operationId: linkedinSignalWatchlistRemove
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
        - in: path
          name: entryId
          required: true
          schema: { type: string }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
        "404": { description: Entry not found. }

  /linkedin/searches:
    get:
      tags: [LinkedIn — Searches]
      summary: List past searches
      description: Audit log of historical searches run by this tenant, newest first.
      operationId: linkedinListSearches
      parameters:
        - in: query
          name: limit
          schema: { type: integer, default: 50, maximum: 100 }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  searches:
                    type: array
                    items: { $ref: "#/components/schemas/LinkedInSearch" }
    post:
      tags: [LinkedIn — Searches]
      summary: Run a historical search
      description: |
        Synchronous keyword search across the past 24 hours, week, or month.
        Returns the full hit list inline. Use this for one-shot lookups; for
        continuous monitoring use POST /v1/linkedin/signals.
      operationId: linkedinRunSearch
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [query, intentDescription]
              properties:
                sessionId:
                  type: string
                  nullable: true
                  description: "Omit or send null to auto-distribute. Pass a session id to pin."
                query:     { type: string, minLength: 2, maxLength: 500 }
                lookback:  { type: string, enum: [past-24h, past-week, past-month], default: past-week }
                minIntent: { type: string, enum: [low, medium, high], nullable: true, description: "Filter results below this intent level. Omit for unfiltered." }
                intentDescription:
                  type: string
                  minLength: 1
                  maxLength: 2000
                  description: |
                    Plain-English firing rule the LLM classifier treats as
                    the authoritative definition of what should fire (same
                    semantics as on signals). The keyword is a coarse
                    pre-filter; this rule decides engage and the cited
                    reason on every result.
                limit:     { type: integer, minimum: 1, maximum: 100, default: 50 }
      responses:
        "200":
          description: Search ran successfully. results may be empty.
          content:
            application/json:
              schema:
                type: object
                properties:
                  search:  { $ref: "#/components/schemas/LinkedInSearch" }
                  results:
                    type: array
                    items: { $ref: "#/components/schemas/LinkedInSearchResult" }
        "404": { description: LinkedIn session not found or inactive. }
        "429": { description: LinkedIn rate-limited this session. The search row is persisted with errorCode=LINKEDIN_RATE_LIMITED. }
        "502": { description: LinkedIn returned an unexpected error. The search row is persisted with the error captured. }

  /linkedin/searches/{id}:
    get:
      tags: [LinkedIn — Searches]
      summary: Fetch a past search + its results
      description: Re-open a persisted search without spending another LinkedIn quota.
      operationId: linkedinGetSearch
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string }
      responses:
        "200":
          content:
            application/json:
              schema:
                type: object
                properties:
                  search:  { $ref: "#/components/schemas/LinkedInSearch" }
                  results:
                    type: array
                    items: { $ref: "#/components/schemas/LinkedInSearchResult" }
        "404": { description: Not found. }

  /cadences:
    post:
      tags: [Cadences]
      summary: Create an outreach cadence
      description: |
        A cadence is a server-side outreach sequence — an ordered list of
        steps (LinkedIn invite → wait → DM → email → ...) that fire
        automatically per enrollment with branching on real-world events
        (invite accepted, lead replied).

        The runtime is on Anjal's side. Customer apps call
        `POST /v1/cadences/:id/enrollments` to enroll a lead and receive
        webhook events as the cadence progresses.
      operationId: createCadence
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name:               { type: string, maxLength: 255 }
                description:        { type: string, nullable: true }
                businessHoursOnly:  { type: boolean, default: true }
                exitOnReply:        { type: boolean, default: true }
                exitOnUnsubscribe:  { type: boolean, default: true }
                dailySendCap:       { type: integer, minimum: 1, maximum: 1000, default: 50 }
                webhookUrl:         { type: string, format: uri, nullable: true }
                steps:
                  type: array
                  items: { $ref: "#/components/schemas/CadenceStepInput" }
                  description: "Optional inline step list. You can also PATCH /v1/cadences/:id/steps later."
      responses:
        "201":
          description: Cadence created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:      { type: boolean }
                  cadence: { $ref: "#/components/schemas/Cadence" }
    get:
      tags: [Cadences]
      summary: List cadences
      operationId: listCadences
      responses:
        "200":
          description: All cadences in this tenant (or workspace).

  /cadences/{id}:
    get:
      tags: [Cadences]
      summary: Get a cadence with its steps
      operationId: getCadence
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200": { description: Cadence + steps }
        "404": { description: Not found }
    patch:
      tags: [Cadences]
      summary: Update cadence settings
      operationId: updateCadence
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200": { description: Updated. }
    delete:
      tags: [Cadences]
      summary: Delete a cadence
      operationId: deleteCadence
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200": { description: Deleted. }

  /cadences/{id}/steps:
    patch:
      tags: [Cadences]
      summary: Replace the step list atomically
      description: |
        Sends the full ordered list of steps in one call — wipes the
        previous steps and reinserts. Steps are tiny; diffing is more
        trouble than it's worth.

        Step kinds:
          • `linkedin_connect` — POST a connection request (with note)
          • `linkedin_message` — DM a 1st-degree connection
          • `email` — (v1.1) send via configured inbox
          • `wait` — no-op delay before the next step

        Conditions (optional, NULL = always run):
          • `after_accept` — only run if the previous linkedin_connect step's
            invite has been accepted (signal.connection_accepted with
            outbound attribution)
          • `no_reply_to_prev` — only run if the lead hasn't replied since
            the previous step
          • `never_replied` — only run if the lead has never replied during
            this enrollment
      operationId: replaceCadenceSteps
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [steps]
              properties:
                steps:
                  type: array
                  minItems: 1
                  maxItems: 20
                  items: { $ref: "#/components/schemas/CadenceStepInput" }
      responses:
        "200": { description: Steps replaced. }

  /cadences/{id}/enrollments:
    post:
      tags: [Cadences]
      summary: Enroll a lead in this cadence
      description: |
        Idempotent on (cadenceId, leadExternalId) — re-enrolling the
        same lead returns the existing enrollment with `created: false`.

        Lead identity fields: pass whatever you have. The runner uses
        `leadLinkedinUrl` for LinkedIn invites and `leadEmail` for
        email steps. `leadProfileUrn` is set automatically when the
        first LinkedIn invite is sent (the runner persists it for
        future after_accept attribution and reply-detection).
      operationId: enrollLeadInCadence
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [leadExternalId]
              properties:
                leadExternalId:    { type: string, description: "Your stable id for the lead. Idempotency key." }
                leadName:          { type: string, nullable: true }
                leadEmail:         { type: string, format: email, nullable: true }
                leadLinkedinUrl:   { type: string, format: uri, nullable: true }
                leadProfileUrn:    { type: string, nullable: true }
                sessionId:         { type: string, nullable: true, description: "Required if cadence has any LinkedIn step." }
                inboxId:           { type: string, format: uuid, nullable: true, description: "Required if cadence has any email step." }
                context:           { type: object, nullable: true }
                startAt:           { type: string, format: date-time, nullable: true }
      responses:
        "200":
          description: Enrollment ready. `created` distinguishes new from existing.
    get:
      tags: [Cadences]
      summary: List enrollments for this cadence
      description: |
        Returns enrollments newest-first, with per-row step-run summary so
        you can render a "3 of 5 ✅" progress + "Blocked: <reason>" badge
        in one HTTP call — no N+1 fetch into `/v1/enrollments/{id}`.

        ## What you get per enrollment

        Identity (set at enroll time, returned verbatim):

        - `leadExternalId`     — your idempotency key
        - `leadName`, `leadEmail`, `leadLinkedinUrl` — whatever you sent
                                   on enrollment. Returned even if null.
        - `leadProfileUrn`     — `urn:li:fsd_profile:…`, set by the runner
                                   after the first LinkedIn invite resolves
                                   the profile. Null until then.
        - `sessionId`          — LinkedIn session the cadence runs through.
                                   May be auto-picked from the workspace pool
                                   if you didn't pass one (see commit f0d2ff1)
                                   — once picked, it's pinned to the enrollment.

        State + progress:

        - `state`              — `active | paused | completed | replied |
                                   accepted | bounced | unenrolled | error`
        - `currentStep`        — 0-based index of the NEXT step due
        - `stepsCompleted`     — count of DISTINCT step indices that have
                                   fired with `status='sent'`. Visual: green
                                   checkmark count.
        - `nextStepDueAt`      — when the runner will next consider this row
                                   (ISO 8601). Past time = overdue + queued.
        - `lastStepFiredAt`    — ISO 8601 of the most recent step run.
        - `lastError`          — most recent FAILED step run (status=
                                   `failed`), or null if no failures. Keys:
                                   `code`, `message`, `atStepIndex`, `firedAt`.
                                   The `code` values match what `runner.ts`
                                   writes — most common today are
                                   `NO_SESSION_AVAILABLE`,
                                   `WORKSPACE_QUOTA_EXHAUSTED`,
                                   `PINNED_SESSION_UNUSABLE`, `NO_TARGET`,
                                   `NO_INBOX`, `DRAFT_WEBHOOK_FAILED`
                                   (your draft handler timed out, 5xx'd,
                                   or returned malformed JSON), and
                                   `AI_STRATEGY_REMOVED` (pre-existing
                                   step still on `draftStrategy: "ai"`
                                   — update the step to `static` or
                                   `webhook`). Skipped steps (a step
                                   whose condition didn't apply — e.g.
                                   `after_accept` on a rejected invite,
                                   or your draft handler returned
                                   `{ skip: true }`) are NOT counted as
                                   errors; they're a normal part of
                                   cadence execution.

        ## Worked example response

        ```json
        {
          "ok": true,
          "enrollments": [
            {
              "id": "01HZ…",
              "cadenceId": "01HY…",
              "leadExternalId": "delegated:lead:abc-123",
              "leadName": "Jane Doe",
              "leadEmail": "jane@acme.com",
              "leadLinkedinUrl": "https://www.linkedin.com/in/jane-doe-1a2b3c/",
              "leadProfileUrn": "urn:li:fsd_profile:ACoAAA…aaaa",
              "sessionId": "01HX…",
              "inboxId": "01HW…",
              "currentStep": 3,
              "state": "active",
              "stepsCompleted": 2,
              "nextStepDueAt": "2026-05-21T14:00:00Z",
              "lastStepFiredAt": "2026-05-19T14:00:00Z",
              "lastError": null,
              "enrolledAt": "2026-05-18T10:30:00Z",
              "updatedAt": "2026-05-19T14:00:00Z"
            },
            {
              "id": "01HZ…",
              "cadenceId": "01HY…",
              "leadExternalId": "delegated:lead:def-456",
              "leadName": "John Smith",
              "leadEmail": null,
              "leadLinkedinUrl": "https://www.linkedin.com/in/john-smith/",
              "leadProfileUrn": null,
              "sessionId": null,
              "inboxId": null,
              "currentStep": 0,
              "state": "active",
              "stepsCompleted": 0,
              "nextStepDueAt": "2026-05-19T13:00:00Z",
              "lastStepFiredAt": "2026-05-19T13:00:00Z",
              "lastError": {
                "code": "NO_SESSION_AVAILABLE",
                "message": "no_active_linkedin_session_in_workspace — connect a LinkedIn account from /dashboard/linkedin to start running cadence steps",
                "atStepIndex": 0,
                "firedAt": "2026-05-19T13:00:00Z"
              },
              "enrolledAt": "2026-05-19T12:00:00Z",
              "updatedAt": "2026-05-19T13:00:00Z"
            }
          ]
        }
        ```

        ## Drilling into one enrollment

        For per-step ✅ render (the full `stepRuns[]` history, including
        skipped steps, rendered message text, channel URNs), call
        `GET /v1/enrollments/{id}` — that endpoint returns the same
        enrollment fields plus a `stepRuns` array of the last 50 runs
        ordered newest-first.
      operationId: listCadenceEnrollments
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
        - in: query
          name: state
          schema: { type: string, enum: [active, paused, completed, replied, accepted, bounced, unenrolled, error] }
          description: Filter by enrollment state.
        - in: query
          name: limit
          schema: { type: integer, minimum: 1, maximum: 500, default: 100 }
      responses:
        "200":
          description: Enrollment list (with per-row step-run summary).
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  enrollments:
                    type: array
                    items:
                      type: object
                      properties:
                        id:                { type: string, format: uuid }
                        cadenceId:         { type: string, format: uuid }
                        leadExternalId:    { type: string }
                        leadName:          { type: string, nullable: true }
                        leadEmail:         { type: string, nullable: true }
                        leadLinkedinUrl:   { type: string, nullable: true }
                        leadProfileUrn:    { type: string, nullable: true, description: "Set by the runner after the first LinkedIn invite resolves. Null until then." }
                        sessionId:         { type: string, nullable: true }
                        inboxId:           { type: string, nullable: true }
                        currentStep:       { type: integer, description: "0-based index of the NEXT step due." }
                        state:             { type: string, enum: [active, paused, completed, replied, accepted, bounced, unenrolled, error] }
                        stepsCompleted:
                          type: integer
                          description: |
                            Count of DISTINCT step indices that have fired
                            with `status='sent'`. Skipped + failed steps do
                            NOT count. Visual: green-checkmark count.
                        nextStepDueAt:     { type: string, format: date-time, nullable: true }
                        lastStepFiredAt:   { type: string, format: date-time, nullable: true }
                        lastError:
                          type: object
                          nullable: true
                          description: |
                            Most recent FAILED step run, or null. `code`
                            values come from the cadence runner — see the
                            description above for the catalogue.
                          properties:
                            code:        { type: string, nullable: true }
                            message:     { type: string, nullable: true }
                            atStepIndex: { type: integer }
                            firedAt:     { type: string, format: date-time }
                        exitReason:        { type: string, nullable: true }
                        exitAt:            { type: string, format: date-time, nullable: true }
                        lastInvitationUrn: { type: string, nullable: true }
                        context:           { type: object, nullable: true }
                        enrolledAt:        { type: string, format: date-time }
                        updatedAt:         { type: string, format: date-time }

  /cadences/{id}/enrollments/bulk-relink:
    post:
      tags: [Cadences]
      summary: Batch-patch lead identity on multiple enrollments
      description: |
        Batched form of `PATCH /v1/enrollments/{id}` for the common
        recovery flow "we enrolled N leads with the wrong payload
        shape; fix all of them at once."

        Same merge semantics as the per-row PATCH (only fields present
        in each update are touched; explicit `null` clears).

        ### Partial failure is allowed

        A single bad row (terminal state, external-ID conflict,
        not-found) does NOT fail the whole batch. The response
        contains a `results[]` array mirroring the input order; each
        slot is either `{ ok: true, enrollmentId, enrollment }` or
        `{ ok: false, enrollmentId, code, error, detail }`. Response
        status is always 200; inspect `results[i].ok` per row.

        ### Limits

        - Max 100 updates per call. Iterate client-side for larger
          batches.
        - Each `enrollmentId` must belong to the cadence in the path —
          rows pointing at a different cadence are rejected with
          `CADENCE_MISMATCH`.

        ### `?retryNow=true`

        Applies to all rows in the batch. Same semantics as the per-row
        endpoint — resets `next_step_due_at` on each successfully-
        updated row to NOW so the runner re-attempts on its next tick.

        ### Worked example

        Request:

        ```
        POST /v1/cadences/01HY…/enrollments/bulk-relink?retryNow=true
        Content-Type: application/json

        {
          "updates": [
            {
              "enrollmentId": "01HZ…aaaa",
              "leadName": "Jane Doe",
              "leadLinkedinUrl": "https://www.linkedin.com/in/jane-doe-1a2b3c/"
            },
            {
              "enrollmentId": "01HZ…bbbb",
              "leadName": "John Smith",
              "leadLinkedinUrl": "https://www.linkedin.com/in/john-smith/"
            }
          ]
        }
        ```

        Response:

        ```json
        {
          "ok": true,
          "succeeded": 2,
          "failed": 0,
          "results": [
            { "ok": true, "enrollmentId": "01HZ…aaaa", "enrollment": { … } },
            { "ok": true, "enrollmentId": "01HZ…bbbb", "enrollment": { … } }
          ]
        }
        ```

        With one row in a terminal state:

        ```json
        {
          "ok": true,
          "succeeded": 1,
          "failed": 1,
          "results": [
            { "ok": true, "enrollmentId": "01HZ…aaaa", "enrollment": { … } },
            {
              "ok": false,
              "enrollmentId": "01HZ…bbbb",
              "code": "ENROLLMENT_TERMINAL_STATE",
              "error": "Enrollment is in terminal state 'replied'; lead identity cannot be modified.",
              "detail": { "state": "replied" }
            }
          ]
        }
        ```
      operationId: bulkRelinkEnrollments
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
          description: Cadence id. All enrollments in `updates` must belong to this cadence.
        - in: query
          name: retryNow
          schema: { type: boolean, default: false }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [updates]
              properties:
                updates:
                  type: array
                  minItems: 1
                  maxItems: 100
                  items:
                    type: object
                    required: [enrollmentId]
                    properties:
                      enrollmentId:    { type: string, format: uuid }
                      leadName:        { type: string, nullable: true, maxLength: 255 }
                      leadEmail:       { type: string, format: email, nullable: true, maxLength: 255 }
                      leadLinkedinUrl: { type: string, format: uri, nullable: true, maxLength: 500 }
                      leadProfileUrn:  { type: string, nullable: true, maxLength: 255 }
                      leadExternalId:  { type: string, minLength: 1, maxLength: 255 }
                      inboxId:         { type: string, format: uuid, nullable: true }
                      sessionId:       { type: string, format: uuid, nullable: true }
      responses:
        "200":
          description: Per-row results. Inspect each `results[i].ok` — overall status code is 200 even when some rows failed.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:        { type: boolean }
                  succeeded: { type: integer }
                  failed:    { type: integer }
                  results:
                    type: array
                    items:
                      type: object
                      properties:
                        ok:           { type: boolean }
                        enrollmentId: { type: string, format: uuid }
                        enrollment:
                          type: object
                          description: "Present when ok=true. Same shape as the per-row PATCH response."
                        code:
                          type: string
                          enum:
                            - NOT_FOUND
                            - CADENCE_MISMATCH
                            - ENROLLMENT_TERMINAL_STATE
                            - LEAD_EXTERNAL_ID_CONFLICT
                            - PATCH_FAILED
                          description: "Present when ok=false."
                        error: { type: string }
                        detail:
                          type: object
                          description: Extra context — `{ state }` on terminal, `{ conflictingExternalId }` on ID conflict.

  /cadences/{id}/run-now:
    post:
      tags: [Cadences]
      summary: Force a runner tick (debug)
      operationId: forceCadenceTick
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200": { description: Tick summaries. }

  /enrollments/{id}:
    get:
      tags: [Cadences]
      summary: Get an enrollment + its step-run history
      description: |
        Returns the enrollment row plus its `stepRuns[]` history (last 50,
        newest-first). Use this when you need per-step status — completed,
        skipped, failed — to render a step-by-step ✅ timeline.

        ## Step run statuses

        - `sent`     — step fired and LinkedIn / SMTP accepted the action.
                       Render as a green checkmark.
        - `skipped`  — step was evaluated but its `condition` didn't apply
                       (e.g. `after_accept` step on an unaccepted invitation,
                       or `never_replied` step when the lead replied).
                       Normal cadence flow — render as a grey checkmark or
                       skip-icon, NOT as an error.
        - `failed`   — runner tried and got back `ok:false` from the
                       downstream call. `errorCode` is set. The enrollment
                       is deferred 1h and retried on the next tick — this
                       is NOT a terminal state on its own.
        - `queued`   — internal scheduling state. You'll rarely see this in
                       practice; included for completeness.

        ## Error codes you'll see in `errorCode`

        Set by `api/src/lib/cadences/runner.ts`. The catalogue:

        - `NO_SESSION_AVAILABLE`      — workspace has zero connected
                                        LinkedIn sessions. Customer needs
                                        to connect one at /dashboard/linkedin.
        - `WORKSPACE_QUOTA_EXHAUSTED` — sessions exist but all at the
                                        per-action daily cap (e.g. 30
                                        connection_requests/day per
                                        session). Resets at midnight UTC,
                                        or add more sessions.
        - `PINNED_SESSION_UNUSABLE`   — `enrollment.sessionId` was set
                                        manually but that session is
                                        revoked / not-active / capped.
                                        Customer should reconnect or
                                        repin.
        - `NO_TARGET`                 — `leadLinkedinUrl` (for LinkedIn
                                        steps) or `leadEmail` (for email
                                        steps) was missing at enrollment.
        - `NO_INBOX`                  — email step but no `inboxId` on the
                                        enrollment or cadence.
        - `DRAFT_WEBHOOK_FAILED`      — step has `draftStrategy: "webhook"`
                                        and the customer's draft handler
                                        timed out (>30s), 5xx'd, returned
                                        non-JSON, returned an invalid
                                        defer, or returned no `body`.
                                        `errorMessage` carries the upstream
                                        detail (which status code, "no
                                        body in response", etc). The
                                        step defers 1h and retries —
                                        which means a flaky handler will
                                        keep getting opportunities to
                                        succeed. To stop retries, mark
                                        the enrollment `state: "paused"`
                                        or unenroll.
        - `AI_STRATEGY_REMOVED`       — pre-existing step still on
                                        `draftStrategy: "ai"` (removed
                                        2026-05-19). Update the step to
                                        `static` (with `staticBody`) or
                                        `webhook` (with the cadence's
                                        `webhookUrl` set to your draft
                                        handler).
        - `send_failed`               — downstream LinkedIn / SMTP returned
                                        an error. `errorMessage` carries the
                                        upstream detail.

        ## Worked example response

        ```json
        {
          "ok": true,
          "enrollment": {
            "id": "01HZ…",
            "cadenceId": "01HY…",
            "leadExternalId": "delegated:lead:abc-123",
            "leadName": "Jane Doe",
            "leadLinkedinUrl": "https://www.linkedin.com/in/jane-doe-1a2b3c/",
            "leadProfileUrn": "urn:li:fsd_profile:ACoAAA…aaaa",
            "sessionId": "01HX…",
            "currentStep": 3,
            "state": "active",
            "nextStepDueAt": "2026-05-21T14:00:00Z",
            "lastStepFiredAt": "2026-05-19T14:00:00Z",
            "enrolledAt": "2026-05-18T10:30:00Z",
            "updatedAt": "2026-05-19T14:00:00Z"
          },
          "stepRuns": [
            {
              "id": "01HZ…",
              "stepIndex": 2,
              "stepKind": "linkedin_message",
              "status": "sent",
              "channelUrn": "urn:li:msg_message:(…)",
              "renderedSubject": null,
              "renderedText": "Hey Jane — saw your post about cold outbound…",
              "errorMessage": null,
              "errorCode": null,
              "skipReason": null,
              "firedAt": "2026-05-19T14:00:00Z"
            },
            {
              "id": "01HZ…",
              "stepIndex": 1,
              "stepKind": "wait",
              "status": "sent",
              "channelUrn": null,
              "renderedSubject": null,
              "renderedText": null,
              "errorMessage": null,
              "errorCode": null,
              "skipReason": null,
              "firedAt": "2026-05-19T13:00:00Z"
            },
            {
              "id": "01HZ…",
              "stepIndex": 0,
              "stepKind": "linkedin_connect",
              "status": "sent",
              "channelUrn": "urn:li:fsd_profile:ACoAAA…aaaa",
              "renderedSubject": null,
              "renderedText": "Hi Jane — common interest in outbound; thought I'd connect.",
              "errorMessage": null,
              "errorCode": null,
              "skipReason": null,
              "firedAt": "2026-05-18T10:30:00Z"
            }
          ]
        }
        ```

        ## Rendering ✅ progress

        ```ts
        const r = await mam.getEnrollment({ id });
        const sentByIndex = new Map<number, true>();
        const skippedByIndex = new Map<number, true>();
        let lastFailure: typeof r.stepRuns[number] | null = null;

        for (const run of r.stepRuns) {
          if (run.status === "sent") sentByIndex.set(run.stepIndex, true);
          else if (run.status === "skipped") skippedByIndex.set(run.stepIndex, true);
          else if (run.status === "failed" && !lastFailure) lastFailure = run;
        }

        // For each step in cadence.steps[]:
        //   if (sentByIndex.has(i))    → ✅ done
        //   else if (skippedByIndex.has(i)) → ⊘ skipped (condition not met)
        //   else if (i === enrollment.currentStep && lastFailure) → ⚠ blocked
        //   else if (i === enrollment.currentStep) → ⏳ pending
        //   else → ◯ upcoming
        ```
      operationId: getEnrollment
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Enrollment + step runs.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  enrollment:
                    type: object
                    description: Same shape as items in `/cadences/{id}/enrollments` (minus the `stepsCompleted` / `lastError` summary — drill into `stepRuns[]` below instead).
                  runnerState:
                    type: object
                    description: |
                      Read-only diagnostic — answers "would the runner fire this
                      row right now? if not, why?". Same logic the runner uses
                      to pick enrollments (`pickDueEnrollments` + `evaluateCondition`),
                      replicated read-only so callers can self-diagnose
                      without poking the runner.

                      Use this BEFORE filing a support ticket. If `pickable: true`
                      and the row isn't firing, the runner tick interval is 5
                      minutes — `maxExpectedWaitSeconds` carries the upper bound.
                      Use `POST /v1/cadences/{id}/run-now` to force a tick.

                      If `pickable: false`, `reasons[]` lists every blocking
                      condition with the exact PATCH curl needed to unblock.
                      `details` exposes the underlying values (state, scheduling,
                      condition evaluation) for deeper inspection.
                    properties:
                      pickable:
                        type: boolean
                        description: True iff the runner would pick this enrollment on its next tick.
                      reasons:
                        type: array
                        items: { type: string }
                        description: "Empty when pickable=true. Each item is a human-readable explanation of a blocking condition, including the corrective curl when applicable."
                      details:
                        type: object
                        description: Underlying decision inputs — state, scheduling, condition evaluation, draft strategy sanity.
                        properties:
                          state:                       { type: string, description: "enrollment.state" }
                          cadenceEnabled:              { type: boolean }
                          nextStepDueAt:               { type: string, format: date-time, nullable: true }
                          nextStepDueInSeconds:        { type: integer, nullable: true, description: "Negative = overdue, positive = future." }
                          currentStep:                 { type: integer }
                          stepCount:                   { type: integer }
                          currentStepKind:             { type: string, nullable: true }
                          currentStepCondition:        { type: string, nullable: true }
                          currentStepDraftStrategy:    { type: string, nullable: true }
                          conditionOutcome:            { type: string, enum: [proceed, "skip-step", wait], nullable: true }
                          conditionReason:             { type: string, nullable: true }
                          runnerTickIntervalSeconds:   { type: integer, description: "How often the runner ticks (currently 300s/5min)." }
                          maxExpectedWaitSeconds:
                            type: integer
                            nullable: true
                            description: "Upper bound on time-to-fire when pickable=true. Null when blocked (no deterministic ETA)."
                  stepRuns:
                    type: array
                    description: Last 50 step runs for this enrollment, newest-first.
                    items:
                      type: object
                      properties:
                        id:              { type: string, format: uuid }
                        stepIndex:       { type: integer, description: "0-based; matches cadence.steps[stepIndex]." }
                        stepKind:        { type: string, enum: [linkedin_connect, linkedin_message, email, wait] }
                        status:          { type: string, enum: [sent, skipped, failed, queued] }
                        channelUrn:      { type: string, nullable: true, description: "For LinkedIn steps: invitation URN / message URN / profile URN. For email: the message-id." }
                        renderedSubject: { type: string, nullable: true, description: "Email subject (email steps only)." }
                        renderedText:    { type: string, nullable: true, description: "The body that was actually sent — AI-generated or static, post-rendering." }
                        errorMessage:    { type: string, nullable: true }
                        errorCode:       { type: string, nullable: true, description: "See description above for the catalogue." }
                        skipReason:      { type: string, nullable: true, description: "Why a `skipped`-status run was skipped (e.g. condition_not_met)." }
                        firedAt:         { type: string, format: date-time }
        "404": { description: Not found. }
    patch:
      tags: [Cadences]
      summary: Update an enrollment (state, lead identity, scheduling)
      description: |
        Two distinct use cases — both supported by this single endpoint:

        ### 1. Pause / resume / unenroll

        Pass `state` to move the enrollment between lifecycle states.
        `active` / `paused` / `unenrolled` are the values the runner
        respects. Terminal states (`completed`, `replied`, `accepted`,
        `bounced`) are set by the runner itself based on signals + the
        cadence's `exitOnReply` setting — don't write to them directly.

        ### 2. Fix-up bad enroll-time payload

        Use case: a row was enrolled with the wrong shape (missing
        `leadLinkedinUrl`, wrong `leadEmail`, etc.) and is now stuck on
        a step with a `NO_TARGET` / `NO_INBOX` error. Patch the
        identity fields and the runner picks up the corrected row on
        its next tick — no need to unenroll + re-enroll (which would
        lose `currentStep`, `lastStepFiredAt`, the step_runs audit, and
        any `leadExternalId` joins your side has against the
        enrollment).

        **Merge semantics**: only fields present in the request body
        are updated. Omitted fields stay as-is. Pass explicit `null` to
        clear a column (where the column is nullable).

        **Patchable identity fields**: `leadName`, `leadEmail`,
        `leadLinkedinUrl`, `leadProfileUrn`, `leadExternalId`,
        `inboxId`, `sessionId`. The runner resolves
        `leadLinkedinUrl` → `leadProfileUrn` automatically when the
        next LinkedIn step fires — you do not need to look up the URN
        separately before patching.

        ### `?retryNow=true` query param

        When fixing a stuck enrollment, also pass `?retryNow=true` to
        reset `next_step_due_at = NOW()` so the runner re-attempts on
        the next tick (~1 min) instead of waiting out the post-failure
        1h backoff. Opt-in so routine patches (typo fix on a name)
        don't unnecessarily trigger an immediate retry.

        Successful retry automatically clears `lastError` from the
        list endpoint's per-row summary — the `lastError` query
        ignores failed step_runs that occurred before the most recent
        successful run.

        ### Terminal-state guard

        Patching lead identity is rejected (`409 ENROLLMENT_TERMINAL_STATE`)
        when the enrollment is in `completed` / `replied` / `accepted` /
        `bounced` / `unenrolled`. There's no use case for "fix a lead
        on a completed cadence" — the runner won't re-run it. If you
        genuinely want to resume, PATCH `state: 'active'` first, then
        patch identity in a second call.

        ### `leadExternalId` conflict

        Changing `leadExternalId` to a value another enrollment in the
        same cadence already uses returns `409 LEAD_EXTERNAL_ID_CONFLICT`
        with the conflicting value in the response body. The
        `(cadence_id, lead_external_id)` unique constraint is what
        makes the enroll endpoint idempotent — you can't violate it
        via PATCH either.

        ### Worked example: fix-up flow

        Before — list endpoint shows:

        ```json
        {
          "id": "01HZ…",
          "leadName": null,
          "leadLinkedinUrl": null,
          "state": "active",
          "currentStep": 0,
          "stepsCompleted": 0,
          "lastError": {
            "code": "NO_TARGET",
            "message": "no_linkedin_url",
            "atStepIndex": 0,
            "firedAt": "2026-05-19T14:00:00Z"
          },
          "nextStepDueAt": "2026-05-19T15:00:00Z"
        }
        ```

        Patch request:

        ```
        PATCH /v1/enrollments/01HZ…?retryNow=true
        Content-Type: application/json

        {
          "leadName": "Jane Doe",
          "leadLinkedinUrl": "https://www.linkedin.com/in/jane-doe-1a2b3c/",
          "leadEmail": "jane@acme.com"
        }
        ```

        Response (immediate — `lastError` clears on the next list call
        after the runner ticks successfully):

        ```json
        {
          "ok": true,
          "enrollment": {
            "id": "01HZ…",
            "leadName": "Jane Doe",
            "leadLinkedinUrl": "https://www.linkedin.com/in/jane-doe-1a2b3c/",
            "leadEmail": "jane@acme.com",
            "state": "active",
            "currentStep": 0,
            "nextStepDueAt": "2026-05-19T14:32:11Z",
            "updatedAt": "2026-05-19T14:32:11Z"
          }
        }
        ```
      operationId: patchEnrollment
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
        - in: query
          name: retryNow
          schema: { type: boolean, default: false }
          description: |
            When true, also resets `next_step_due_at = NOW()` so the
            runner picks the enrollment up on the next tick instead of
            waiting out the post-failure 1h backoff.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                state:
                  type: string
                  enum: [active, paused, unenrolled]
                  description: Move between lifecycle states. Terminal states are set by the runner; don't write to them.
                exitReason:
                  type: string
                  nullable: true
                  maxLength: 255
                leadName:
                  type: string
                  nullable: true
                  maxLength: 255
                  description: "Merge semantics: omit to keep, null to clear, string to set."
                leadEmail:
                  type: string
                  format: email
                  nullable: true
                  maxLength: 255
                leadLinkedinUrl:
                  type: string
                  format: uri
                  nullable: true
                  maxLength: 500
                leadProfileUrn:
                  type: string
                  nullable: true
                  maxLength: 255
                  description: "`urn:li:fsd_profile:…`. Optional — the runner resolves this from `leadLinkedinUrl` automatically when the next LinkedIn step fires."
                leadExternalId:
                  type: string
                  minLength: 1
                  maxLength: 255
                  description: |
                    Idempotency key. Changing it to a value another
                    enrollment in this cadence already uses returns
                    409 LEAD_EXTERNAL_ID_CONFLICT.
                inboxId:
                  type: string
                  format: uuid
                  nullable: true
                sessionId:
                  type: string
                  format: uuid
                  nullable: true
                currentStep:
                  type: integer
                  minimum: 0
                  maximum: 50
                  description: |
                    Manual cursor advance/rewind. Use sparingly — the
                    runner manages this automatically. Legitimate cases:

                    1. Bypass an `after_accept`-gated step when the
                       lead accepted out-of-band (rare).
                    2. Replay from a step that fired against the wrong
                       inbox / session, after fixing the enrollment.
                    3. Abandon a step stuck on an external signal that
                       won't materialise.

                    Range: `[0, stepCount]` inclusive. Passing
                    `stepCount` transitions the enrollment to
                    `state: completed` (`exit_reason: manually_completed`,
                    `next_step_due_at` cleared). Out-of-range values
                    return `400 STEP_OUT_OF_RANGE` with the cadence's
                    actual step count.

                    Audit: every manual advance inserts a
                    `linkedin_cadence_step_runs` row with
                    `status: skipped`,
                    `skip_reason: manual_advance_via_patch`, anchored to
                    the step the cursor was on. Visible in
                    `GET /v1/enrollments/{id}`'s `stepRuns[]` so anyone
                    auditing the cadence sees the jump.

                    Risk: rewinding to an earlier email step may cause
                    a duplicate send when the runner re-fires. LinkedIn
                    dedups invitations server-side; SMTP does not. Pair
                    with `state: paused` first if you want to inspect
                    before letting the runner re-fire.
      responses:
        "200":
          description: Updated. Returns the full enrollment in the same shape as `GET /enrollments/{id}`'s `enrollment` field.
        "400":
          description: |
            `STEP_OUT_OF_RANGE` — `currentStep` was outside `[0, stepCount]`
            for this cadence. Response body includes `attempted` (the value
            you sent) and `stepCount` (the cadence's actual step count) so
            you can correct without a follow-up GET.
        "404":
          description: Enrollment not found, or it belongs to a different tenant.
        "409":
          description: |
            Either `ENROLLMENT_TERMINAL_STATE` (cadence is completed/replied/
            accepted/bounced/unenrolled and lead identity can't be patched
            on a terminal row) or `LEAD_EXTERNAL_ID_CONFLICT` (the new
            leadExternalId is already in use by another enrollment in this
            cadence).
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string }
                  code:
                    type: string
                    enum: [ENROLLMENT_TERMINAL_STATE, LEAD_EXTERNAL_ID_CONFLICT]
                  state:
                    type: string
                    description: "On ENROLLMENT_TERMINAL_STATE: the current state blocking the patch."
                  conflictingExternalId:
                    type: string
                    description: "On LEAD_EXTERNAL_ID_CONFLICT: the leadExternalId that's already in use."
                  hint:
                    type: string
                    description: "Human-readable next-step suggestion."
