openapi: 3.0.3
info:
  title: Postal API
  description: |
    Postal AI Content Marketing API - Schedule and manage social media content with AI assistance.

    ## Authentication
    All endpoints (except health check) require Firebase Authentication.
    Pass the Firebase ID token in the Authorization header:
    ```
    Authorization: Bearer <firebase-id-token>
    ```
  version: 1.0.0
  contact:
    name: Postal Support
    url: https://postal-ai.drawbuildplay.com
  license:
    name: Proprietary

servers:
  - url: https://api.postal-ai.drawbuildplay.com
    description: Production API

paths:
  /health:
    get:
      summary: Health Check
      description: Check API and Firebase connectivity status
      operationId: healthCheck
      tags:
        - System
      responses:
        '200':
          description: Health status
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HealthResponse'

  /pinterest/auth:
    get:
      summary: Get Pinterest Auth URL
      description: Generate the Pinterest OAuth authorization URL to start the connection flow
      operationId: pinterestAuth
      tags:
        - Pinterest
      parameters:
        - in: query
          name: state
          schema:
            type: string
          description: Optional state parameter to prevent CSRF
      responses:
        '200':
          description: Auth URL generated
          content:
            application/json:
              schema:
                type: object
                properties:
                  url:
                    type: string
                    description: The Pinterest authorization URL
                  state:
                    type: string
                    description: The state parameter passed or generated

  /pinterest/callback:
    post:
      summary: Pinterest OAuth Callback
      description: Exchange Pinterest OAuth authorization code for tokens and save connection
      operationId: pinterestCallback
      tags:
        - Pinterest
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - code
                - redirectUri
              properties:
                code:
                  type: string
                  description: OAuth authorization code from Pinterest
                redirectUri:
                  type: string
                  description: Redirect URI used in the OAuth flow
      responses:
        '200':
          description: Successfully connected Pinterest
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PinterestCallbackResponse'
        '400':
          description: Missing or invalid parameters
        '401':
          description: Not authenticated

  /pinterest/refresh:
    post:
      summary: Refresh Pinterest Token
      description: Refresh the Pinterest access token using the stored refresh token
      operationId: pinterestRefreshToken
      tags:
        - Pinterest
      security:
        - bearerAuth: []
      responses:
        '200':
          description: Token refreshed successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
        '401':
          description: Not authenticated
        '404':
          description: Pinterest connection not found

  /pinterest/boards:
    get:
      summary: Get Pinterest Boards
      description: Retrieve all boards from the connected Pinterest account
      operationId: pinterestGetBoards
      tags:
        - Pinterest
      security:
        - bearerAuth: []
      responses:
        '200':
          description: List of Pinterest boards
          content:
            application/json:
              schema:
                type: object
                properties:
                  boards:
                    type: array
                    items:
                      $ref: '#/components/schemas/PinterestBoard'
        '401':
          description: Not authenticated
        '404':
          description: Pinterest connection not found

  /pinterest/pins:
    post:
      summary: Create Pinterest Pin
      description: Create a new pin on a Pinterest board
      operationId: pinterestCreatePin
      tags:
        - Pinterest
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreatePinRequest'
      responses:
        '200':
          description: Pin created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreatePinResponse'
        '400':
          description: Missing required fields
        '401':
          description: Not authenticated
        '404':
          description: Pinterest connection not found

  /x/auth/start:
    post:
      summary: Start X (Twitter) OAuth
      description: Issue a single-use OAuth state for the signed-in user. Pass it as the `state` parameter to X and send it back to /x/callback.
      operationId: xAuthStart
      tags:
        - X
      security:
        - bearerAuth: []
      responses:
        '200':
          description: State issued
          content:
            application/json:
              schema:
                type: object
                properties:
                  state:
                    type: string
        '401':
          description: Not authenticated
        '405':
          description: Method not allowed

  /x/callback:
    post:
      summary: X (Twitter) OAuth Callback
      description: Exchange X OAuth authorization code for tokens and save connection
      operationId: xCallback
      tags:
        - X
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - code
                - redirectUri
                - codeVerifier
                - state
              properties:
                code:
                  type: string
                  description: OAuth authorization code from X
                redirectUri:
                  type: string
                  description: Redirect URI used in the OAuth flow
                codeVerifier:
                  type: string
                  description: PKCE Code Verifier
                state:
                  type: string
                  description: The state value returned by /x/auth/start. Single use, expires after 10 minutes.
      responses:
        '200':
          description: Successfully connected X
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  connection:
                    $ref: '#/components/schemas/SocialConnection'
        '400':
          description: Missing or invalid parameters, or the state is unknown, expired, or already used
        '401':
          description: Not authenticated

  /x/user:
    get:
      summary: Get X User Stats
      description: Retrieve X user public metrics
      operationId: getXUser
      tags:
        - X
      security:
        - bearerAuth: []
      parameters:
        - in: query
          name: connectionId
          required: true
          schema:
            type: string
          description: ID of the X connection
      responses:
        '200':
          description: X User Stats
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  user:
                    $ref: '#/components/schemas/XUser'
        '401':
          description: Not authenticated
        '404':
          description: Connection not found

  /connections:
    get:
      summary: List Social Connections
      description: Retrieve all social media connections, optionally filtered by platform
      operationId: getConnections
      tags:
        - Connections
      security:
        - bearerAuth: []
      parameters:
        - in: query
          name: platform
          schema:
            type: string
          description: Optional platform name (e.g. 'pinterest')
      responses:
        '200':
          description: List of connections
          content:
            application/json:
              schema:
                type: object
                properties:
                  connections:
                    type: array
                    items:
                      $ref: '#/components/schemas/SocialConnection'
        '401':
          description: Not authenticated

  /connections/{connectionId}/default:
    post:
      summary: Set Default Connection
      description: Set a connection as the default for its platform
      operationId: setConnectionDefault
      tags:
        - Connections
      security:
        - bearerAuth: []
      parameters:
        - in: path
          name: connectionId
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
        '401':
          description: Not authenticated
        '404':
          description: Connection not found

  /connections/{connectionId}:
    delete:
      summary: Delete Connection
      description: Remove a social media connection
      operationId: deleteConnection
      tags:
        - Connections
      security:
        - bearerAuth: []
      parameters:
        - in: path
          name: connectionId
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
        '401':
          description: Not authenticated
        '404':
          description: Connection not found

  /settings:
    get:
      summary: Get Owner Settings
      description: The signed-in owner's time zone (default America/New_York). Only the daily digest and its display use it; analytics days and planning stay on US Eastern.
      operationId: getOwnerSettings
      tags:
        - Settings
      security:
        - bearerAuth: []
      responses:
        '200':
          description: Settings
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OwnerSettings'
        '401':
          description: Not authenticated
    patch:
      summary: Update Owner Settings
      description: Set the owner's time zone. It must be an IANA name Intl knows (e.g. Europe/London); it is stored in canonical form.
      operationId: updateOwnerSettings
      tags:
        - Settings
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [timeZone]
              properties:
                timeZone: { type: string, example: Europe/London }
      responses:
        '200':
          description: Saved
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OwnerSettings'
        '400':
          description: "code invalid_time_zone: not an IANA time zone"
        '401':
          description: Not authenticated

  /scheduled-posts:
    get:
      summary: List Scheduled Posts
      description: List the caller's scheduled posts, newest first
      operationId: listScheduledPosts
      tags:
        - ScheduledPosts
      security:
        - bearerAuth: []
      parameters:
        - in: query
          name: platform
          schema:
            type: string
            enum: [pinterest, x]
        - in: query
          name: status
          schema:
            $ref: '#/components/schemas/ScheduledPostStatus'
      responses:
        '200':
          description: Posts
          content:
            application/json:
              schema:
                type: object
                properties:
                  posts:
                    type: array
                    items:
                      $ref: '#/components/schemas/ScheduledPost'
        '400':
          description: Unknown status or platform filter
        '401':
          description: Not authenticated

  /scheduled-posts/create:
    post:
      summary: Create Scheduled Post
      description: Schedule a post on one of the caller's connections. Clients cannot write scheduled posts to Firestore directly.
      operationId: createScheduledPost
      tags:
        - ScheduledPosts
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateScheduledPostRequest'
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ScheduledPostResponse'
        '400':
          description: Invalid input. PostalAi applies no length cap (X enforces the limit for the account at publish; a refusal ends the post failed with X's code in errorCode). Text containing a link returns code link_not_allowed, except one link to an 𝕏 post (https://x.com/<handle>/status/<id>, also twitter.com; query kept as written) as the very last thing in the main text, which 𝕏 shows as a card of that post (sent as text, not quote_tweet_id; counts 23 characters; part of textSha256). containsAiMedia true without media returns media_required. A scheduled post (any platform, including a Pinterest link) that links a URL another post on the same account links less than 7 days away (scheduled, pending or published) returns code same_url_too_soon; drafts are not checked.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Links aren't allowed in post text
                  code:
                    type: string
                    example: link_not_allowed
        '401':
          description: Not authenticated
        '404':
          description: Connection not found

  /scheduled-posts/{postId}:
    get:
      summary: Get Scheduled Post
      operationId: getScheduledPost
      tags:
        - ScheduledPosts
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      responses:
        '200':
          description: Post
          content:
            application/json:
              schema:
                type: object
                properties:
                  post:
                    $ref: '#/components/schemas/ScheduledPost'
        '401':
          description: Not authenticated
        '404':
          description: Scheduled post not found

  /scheduled-posts/{postId}/update:
    patch:
      summary: Update Scheduled Post
      description: Change the time or content of a post that has not started publishing
      operationId: updateScheduledPost
      tags:
        - ScheduledPosts
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateScheduledPostRequest'
      responses:
        '200':
          description: Updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ScheduledPostResponse'
        '400':
          description: Invalid input, or the post is publishing or published
        '401':
          description: Not authenticated
        '404':
          description: Scheduled post not found

  /scheduled-posts/{postId}/reschedule:
    post:
      summary: Reschedule Failed Post
      description: Move a failed post, or a skipped 'Late, needs Amit' post (held past the 2-hour rule and never sent), back to scheduled at a new time. Refused when the post has an X post id or an earlier publish attempt has an unknown outcome, so a post that may already be on X is never sent again.
      operationId: rescheduleScheduledPost
      tags:
        - ScheduledPosts
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [scheduledAt]
              properties:
                scheduledAt:
                  type: integer
                  format: int64
                  description: New publish time in ms since the epoch. Must be in the future.
      responses:
        '200':
          description: Rescheduled
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ScheduledPostResponse'
        '400':
          description: Missing or past scheduledAt
        '401':
          description: Not authenticated
        '404':
          description: Scheduled post not found
        '409':
          description: The post is not failed or Late, was already published, or has an unknown publish outcome

  /scheduled-posts/{postId}/delete-on-x:
    post:
      summary: Delete a Published Post on X (owner only)
      description: |
        Owner-only 'Delete on 𝕏' for a post PostalAi published. Deletes the thread's replies, then the main post, on X,
        then sets xDeletedAt and xDeletedBy 'owner'. Status stays published so history and analytics keep it, the post
        is not listed as a 'Deleted on 𝕏' attention item, and its text is freed for a new post. post.x_deleted webhooks
        fire as usual. The body must be {"confirm": true}. A second call is 409 already_deleted. If X cannot be reached,
        nothing is marked (503 x_unavailable). Requires a Firebase ID token for the signed-in owner. API keys and
        MCP/OAuth access tokens (any `Bearer pst_` token) are refused with 403 owner_only. There is no MCP tool and no
        agent scope for this.
      operationId: deleteScheduledPostOnX
      tags:
        - ScheduledPosts
      x-owner-only: true
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [confirm]
              properties:
                confirm: { type: boolean, enum: [true] }
      responses:
        '200':
          description: Deleted on X (or it was already gone there)
          content:
            application/json:
              schema:
                type: object
                properties:
                  outcome: { type: string, enum: [deleted, already_gone] }
                  xPostsDeleted: { type: integer }
                  post: { $ref: '#/components/schemas/ScheduledPost' }
        '400':
          description: Missing postId or confirm
        '401':
          description: Not signed in
        '403':
          description: owner_only (API keys and MCP tokens)
        '404':
          description: Post not found
        '409':
          description: not_published, already_deleted, delete_in_progress or x_refused
        '429':
          description: x_rate_limited
        '503':
          description: x_unavailable (nothing deleted), or x_partly_deleted (a thread failed partway; the deleted 𝕏 ids are recorded in xDeletedIds and a retry deletes only what is left)
  /scheduled-posts/{postId}/reattach-media:
    post:
      summary: Re-attach Media to a Held Post (owner only)
      description: |
        Owner-only 'Re-attach media' button on a post held by the pre-flight check for media (errorCode preflight_media).
        Each attached mediaId is read again from Postal media and storage, and the post's media is refreshed from it,
        keeping the post's alt text and sensitive labels. If any item is gone, nothing changes (409 media_missing).
        The hold stays until the next pre-flight check (within 5 minutes) passes and releases it. A bot post whose
        approved media changed goes back to pending_approval and must be approved again. Never sends anything to X.
        Requires a Firebase ID token for the signed-in owner. API keys and MCP/OAuth access tokens (any `Bearer pst_`
        token) are refused with 403 owner_only. There is no MCP tool and no agent scope for this.
      operationId: reattachMediaScheduledPost
      tags:
        - ScheduledPosts
      x-owner-only: true
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      responses:
        '200':
          description: Re-attached
          content:
            application/json:
              schema:
                type: object
                properties:
                  outcome: { type: string, enum: [reattached, needs_approval] }
                  post: { $ref: '#/components/schemas/ScheduledPost' }
        '400':
          description: Missing postId
        '401':
          description: Not signed in (no Firebase ID token)
        '403':
          description: owner_only. An API key or MCP/OAuth token was sent; only the signed-in owner can do this.
        '404':
          description: not_found
        '409':
          description: not_media_hold (not held for media, or it changed), or media_missing (an item is gone from Postal media or storage)
        '503':
          description: media_storage_unavailable

  /scheduled-posts/{postId}/resolve-unclear:
    post:
      summary: Resolve Unclear Post (owner only)
      description: |
        Owner-only buttons on an 'Unclear if posted, needs Amit' item (errorCode x_outcome_unclear, status failed).
        `posted` marks the post published without sending anything, and links the 𝕏 post when Postal finds it on the timeline.
        `post_now` sends it again; the owner's tap is the approval.
        Requires a Firebase ID token for the signed-in owner. API keys and MCP/OAuth access tokens (any `Bearer pst_` token) are refused with 403 owner_only.
        There is no MCP tool and no agent scope for this, so assistants cannot call it.
      operationId: resolveUnclearScheduledPost
      tags:
        - ScheduledPosts
      x-owner-only: true
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [action]
              properties:
                action:
                  type: string
                  enum: [posted, post_now]
      responses:
        '200':
          description: Resolved
          content:
            application/json:
              schema:
                type: object
                properties:
                  action: { type: string, enum: [posted, post_now] }
                  outcome: { type: string, description: "posted: published. post_now: the worker's result (published, failed, held)." }
                  tweetId: { type: string, nullable: true, description: The linked 𝕏 post id, or null when none was found }
                  post: { $ref: '#/components/schemas/ScheduledPost' }
        '400':
          description: invalid_action, or missing postId
        '401':
          description: Not signed in (no Firebase ID token)
        '403':
          description: owner_only. An API key or MCP/OAuth token was sent; only the signed-in owner can do this.
        '404':
          description: not_found
        '409':
          description: not_unclear. The post is no longer waiting on an unclear outcome (for example, a second tap).

  /scheduled-posts/{postId}/cancel:
    delete:
      summary: Cancel Scheduled Post
      description: Delete a post that has not been published
      operationId: cancelScheduledPost
      tags:
        - ScheduledPosts
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      responses:
        '200':
          description: Cancelled
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
        '400':
          description: The post is already published
        '401':
          description: Not authenticated
        '404':
          description: Scheduled post not found

  /scheduled-posts/{postId}/share-links:
    post:
      summary: Create a read-only share link (app only)
      description: |
        Creates an unlisted, revocable link to one post. The token is returned once; only its sha256 is stored.
        Expiry is 7 days by default, 1 to 30 days, or "never". At most 5 active links per post. The post itself
        is not changed. Accepts only Firebase ID tokens.
      operationId: createShareLink
      tags:
        - ShareLinks
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                expiresInDays:
                  oneOf:
                    - type: integer
                      minimum: 1
                      maximum: 30
                    - type: string
                      enum: [never]
                  default: 7
                showAccount:
                  type: boolean
                  default: false
      responses:
        '201':
          description: Link created. The token is not shown again.
          content:
            application/json:
              schema:
                type: object
                properties:
                  token:
                    type: string
                    example: shr_<43 characters>
                  shareLink:
                    $ref: '#/components/schemas/ShareLink'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'
        '409':
          description: The post already has 5 active links (code too_many_share_links)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentError'
    get:
      summary: List a post's share links (app only)
      description: Link metadata only, newest first. Never the token or its hash.
      operationId: listShareLinks
      tags:
        - ShareLinks
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/ScheduledPostId'
      responses:
        '200':
          description: Links
          content:
            application/json:
              schema:
                type: object
                properties:
                  shareLinks:
                    type: array
                    items:
                      $ref: '#/components/schemas/ShareLink'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'

  /share-links/{linkId}/revoke:
    post:
      summary: Revoke a share link (app only)
      description: Takes effect on the next request. Revoking an already revoked link returns it unchanged.
      operationId: revokeShareLink
      tags:
        - ShareLinks
      security:
        - bearerAuth: []
      parameters:
        - in: path
          name: linkId
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  shareLink:
                    $ref: '#/components/schemas/ShareLink'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'

  /scheduled-posts/post-now:
    post:
      summary: Publish a post now (app only)
      description: |
        Publishes one post immediately for the signed-in user through the same path as the scheduled worker:
        atomic claim, X post id saved before the status, duplicate-text guard (the post ends failed with the reason),
        no PostalAi length cap (an X refusal ends the post failed with X's status and code in post.errorCode), links refused with 400 link_not_allowed, and X rate-limit deferral. The post id is derived from requestId, so a repeated or
        concurrent request with the same requestId returns the same post (200, replayed true) and X receives it once.
        At most 10 requests per user per hour. Accepts only Firebase ID tokens; Social Assistant API keys get 401.
      operationId: postNow
      tags:
        - ScheduledPosts
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [requestId, connectionId, text]
              properties:
                requestId:
                  type: string
                  pattern: '^[A-Za-z0-9_-]{8,200}$'
                  description: Unique per intended post, for example a UUID generated when the confirm dialog opens.
                connectionId:
                  type: string
                text:
                  type: string
                  description: Published exactly as sent.
      responses:
        '201':
          description: Processed. outcome is published, failed (post.error says why), deferred (X rate limit; post.scheduledAt is the retry time) or skipped (another request is publishing it).
          content:
            application/json:
              schema:
                type: object
                properties:
                  outcome:
                    type: string
                    enum: [published, failed, deferred, skipped]
                  replayed:
                    type: boolean
                  post:
                    type: object
        '200':
          description: Same as 201, for a repeated requestId (replayed true).
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'
        '422':
          $ref: '#/components/responses/AgentError'
        '429':
          $ref: '#/components/responses/AgentRateLimited'

  /agent/x-posts:
    post:
      summary: Create a post for the owner to approve (Social Assistant)
      description: |
        Creates one post for the account that owns the API key with status pending_approval. Nothing is published until
        the owner approves the exact stored text in PostalAi; editing the text afterwards needs a new approval. If it is not
        approved by approval expiry, min(created + 8 hours, scheduledAt), its status becomes skipped. Each account can create at most
        50 assistant posts per UTC day across all API keys and MCP connections; past that, 429 daily_ceiling_reached. approval is optional;
        if sent, approval.textSha256 must be the SHA-256 (hex) of the UTF-8 bytes of text. scheduledAt must be at least
        10 minutes and at most 90 days ahead. Text already published or in flight on the same account, compared
        after trimming, collapsing whitespace and lowercasing, is refused with 409 with no time window.
        𝕏 compliance, per connection, against pending and scheduled posts (any source, never the post itself): the same text
        (after the same normalization) is refused with 409 duplicate_pending, and a scheduledAt less than 10 minutes from
        another post's is refused with 409 too_close (exactly 10 minutes is allowed). Both carry hint and postId (the other
        post). Drafts are checked when they are scheduled.
        Requests with the same Idempotency-Key and body within 24 hours return the original post with replayed true.
        PostalAi applies no length cap and never truncates; X enforces the account's limit at publish and a refusal ends the post
        failed with X's message in error and code in errorCode (for example x_403). Text containing a link (URL or bare domain, per
        twitter-text) is refused with 400 link_not_allowed. The only replies are self-thread replies (see replies): each answers the
        previous post of the same PostalAi thread and no reply target can be supplied. Only the first reply (thread position 2) may
        carry a link: one full https URL (400 link_too_many, link_not_https, link_shortener), UTM parameters only on instadram.me or
        drawbuildplay.com with utm_source=x and utm_medium=social (400 utm_not_allowed, utm_invalid); links in later replies return
        link_not_allowed. The link is checked before approval (2xx and og/twitter preview meta, SSRF-guarded); a failed check is a
        warning in post.linkCheck, never a refusal. One approval hash covers the whole thread (see AgentXPost.textSha256). Replies
        are posted right after the main post; if one fails the post stays published with threadStatus partial and errorCode
        thread_partial, and the main post is never re-sent. Each post in a thread counts toward the create limits.
        Media: upload each file first with POST /agent/media and pass the returned ids in mediaIds (up to 4 images, or 1 GIF, or 1 video;
        400 media_not_found, media_duplicate, media_mixed or media_too_many). containsAiMedia true needs media (400 media_required) and sets
        X's made_with_ai at publish. A chat approval of a post with media must also send approval.mediaSha256 (see AgentXPost.mediaSha256).
        Accepts only API keys (scope x.posts:create), never Firebase ID tokens.
      operationId: createAgentXPost
      tags:
        - Agent
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateAgentXPostRequest'
      responses:
        '201':
          description: Post scheduled, or the original post for a repeated Idempotency-Key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateAgentXPostResponse'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '403':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'
        '409':
          $ref: '#/components/responses/AgentError'
        '422':
          $ref: '#/components/responses/AgentError'
        '429':
          $ref: '#/components/responses/AgentRateLimited'

  /agent/x-posts/bulk:
    post:
      summary: Create several posts, each for the owner to approve (Social Assistant)
      description: |
        Creates up to 20 posts in one call (for example a week's plan). Each item is a CreateAgentXPostRequest and is
        processed exactly as POST /agent/x-posts would process it on its own: the same checks, its own approval hash and
        pending approval (nothing is approved in bulk), and its own count against maxPending, the per-key create limits and
        the per-account daily ceiling. Items are processed in order and one rejected item does not stop the rest, but a limit does: if the quota
        can't cover any item nothing is attempted, and once a rate limit, daily budget, loop cooldown or the pending cap stops an item, the
        remaining items are not_attempted with the same code and Retry-After. Only created posts are charged. Item i is stored under the derived
        idempotency key "<Idempotency-Key>#<i>": repeating the call with the same key and posts returns the created items
        with replayed true and never creates them twice; changing an item under the same key rejects that item with
        idempotency_conflict. Within one call, an item whose text matches an earlier created item after trimming,
        collapsing whitespace and lowercasing is rejected with duplicate_in_batch, and a scheduled item less than 10 minutes
        from an earlier created item is rejected with too_close_in_batch. The Idempotency-Key here is 8 to 190 characters. Over 20 posts is 400 bulk_too_large.
        Always 200 when the batch itself is valid; read results[] for each item.
      operationId: createAgentXPostsBulk
      tags:
        - Agent
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [posts]
              additionalProperties: false
              properties:
                posts:
                  type: array
                  minItems: 1
                  maxItems: 20
                  items:
                    $ref: '#/components/schemas/CreateAgentXPostRequest'
      responses:
        '200':
          description: One result per item, in order
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentBulkCreateResponse'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '403':
          $ref: '#/components/responses/AgentError'

  /agent/media:
    post:
      summary: Upload one media file for a later post (Social Assistant)
      description: |
        Stores one image, GIF or video in PostalAi (Firebase Storage) for the key's account and returns a mediaId to pass in
        mediaIds when creating a post. Nothing goes to X until the approved post publishes; then PostalAi uploads it with X's
        official v2 media upload (simple upload for images; INITIALIZE/APPEND/FINALIZE/STATUS for GIF and video), sets alt text and
        the sensitive-media warning with POST /2/media/metadata, and attaches media_ids to the post.
        Limits: JPEG, PNG, WebP up to 5 MB; GIF up to 15 MB; MP4 or MOV up to 20 MB here and 0.5 s to 20 min long. The content must
        match mimeType. Instead of base64 data you can pass url, a public https link PostalAi downloads once (see UploadMediaRequest.url).
        X limits: https://docs.x.com/x-api/media/quickstart/best-practices,
        https://docs.x.com/x-api/media/quickstart/media-upload-chunked, https://docs.x.com/x-api/media/metadata-create.
        Up to 40 uploads per key at once, refilling at 40 per hour. Returns 503 media_storage_unavailable when storage isn't set up. Accepts only API keys (scope x.posts:create).
      operationId: uploadAgentMedia
      tags:
        - Agent
      security:
        - apiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UploadMediaRequest'
      responses:
        '201':
          description: Stored
          content:
            application/json:
              schema:
                type: object
                properties:
                  media:
                    $ref: '#/components/schemas/MediaItem'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '403':
          $ref: '#/components/responses/AgentError'
        '429':
          $ref: '#/components/responses/AgentRateLimited'
        '503':
          $ref: '#/components/responses/AgentError'

  /media/{mediaId}:
    get:
      summary: Read one stored media file (app only)
      description: Streams the bytes of one of the signed-in user's media files for previews and the approval card. Firebase ID tokens only. Other users' media returns 404.
      operationId: getMedia
      tags:
        - ScheduledPosts
      security:
        - bearerAuth: []
      parameters:
        - in: path
          name: mediaId
          required: true
          schema:
            type: string
            pattern: '^med_[0-9a-f]{24}$'
      responses:
        '200':
          description: The file, with its stored Content-Type
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '401':
          description: Not authenticated
        '404':
          description: Not found
        '503':
          description: Storage unavailable

  /agent/x-posts/validate:
    post:
      summary: Check a post against every create rule without creating it (Social Assistant)
      description: Same rules as POST /agent/x-posts (text, links, media, schedule window, connection, approval hash) plus the duplicate check. Always 200 with ok and every error (code, message, field); only auth, body shape and quota (shared with reads: 300 per key, refilling at 300 per hour) give 4xx. postId checks an edit of one of the key's posts (not_found, not_editable) and ignores that post in the duplicate check. No length cap; weightedLength is informational.
      operationId: validateAgentXPost
      tags: [Agent]
      security:
        - apiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [text]
              additionalProperties: false
              properties:
                connectionId: { type: string }
                text: { type: string }
                scheduledAt: { type: integer, format: int64 }
                approval:
                  type: object
                  properties:
                    textSha256: { type: string, pattern: '^[0-9a-f]{64}$' }
                containsAiMedia: { type: boolean }
                poll: { $ref: '#/components/schemas/XPoll' }
                replySettings: { type: string, enum: [following, mentionedUsers, subscribers, verified], description: 'Same as CreateAgentXPostRequest.replySettings; included in the returned textSha256 only when set.' }
                paidPartnership: { type: boolean, description: 'Same as CreateAgentXPostRequest.paidPartnership; included in the returned textSha256 only when true.' }
                mediaIds: { type: array, maxItems: 20, items: { type: string } }
                replies: { $ref: '#/components/schemas/ThreadReplies' }
                article: { $ref: '#/components/schemas/XArticle' }
                postId: { type: string }
      responses:
        '200':
          description: The answer
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  errors:
                    type: array
                    items:
                      type: object
                      properties:
                        code: { type: string, example: link_not_allowed }
                        message: { type: string }
                        field: { type: string, example: text }
                  textSha256: { type: string }
                  mediaSha256: { type: string, nullable: true }
                  weightedLength: { type: integer }
                  replies:
                    type: array
                    items:
                      type: object
                      properties:
                        position: { type: integer, description: 'Thread position; the first reply is 2' }
                        weightedLength: { type: integer }
                  link:
                    type: object
                    nullable: true
                    properties:
                      url: { type: string }
                      domain: { type: string }
                      owned: { type: boolean }
                  linkCheck: { $ref: '#/components/schemas/LinkCheck' }
                  duplicateOf: { type: string, nullable: true }
                  account:
                    type: object
                    description: The account's 𝕏 subscription (Premium detection, read from 𝕏 at connect). maxWeightedLength is 280 without a subscription, 25000 with Basic, Premium or PremiumPlus, null when unknown.
                    properties:
                      subscriptionType: { type: string, nullable: true, example: None }
                      maxWeightedLength: { type: integer, nullable: true, example: 280 }
                      checkedAt: { type: integer, nullable: true }
                  nearDuplicates: { $ref: '#/components/schemas/NearDuplicates' }
                  warnings:
                    type: array
                    description: Warnings never change ok. near_duplicate when the wording reads nearly the same as an earlier post. over_account_limit when a part is longer than this account's 𝕏 limit (account.maxWeightedLength).
                    items: { type: object, properties: { code: { type: string }, message: { type: string }, field: { type: string } } }
                  madeWithAi: { type: boolean }
                  poll: { type: object, nullable: true, allOf: [{ $ref: '#/components/schemas/XPoll' }] }
                  replySettings: { type: string, nullable: true, enum: [following, mentionedUsers, subscribers, verified, null] }
                  paidPartnership: { type: boolean }
                  earliestScheduledAt: { type: integer, format: int64 }
                  approvalExpiresAt: { type: integer, format: int64, nullable: true }
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '429':
          $ref: '#/components/responses/AgentRateLimited'

  /agent/x-posts/check-duplicate:
    post:
      summary: Whether text is already published or publishing on the account (Social Assistant)
      description: Compares after trimming, collapsing whitespace and lowercasing. Shares the validate quota. nearDuplicates lists posts with nearly the same wording (a warning; duplicate stays false for them). Posts made on 𝕏 outside PostalAi (imported read-only with analytics) count too, at any age; such a match has postId null, an xPostId and source outside_postalai, and create refuses the same text with 409 duplicate_text.
      operationId: checkAgentXPostDuplicate
      tags: [Agent]
      security:
        - apiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [text]
              additionalProperties: false
              properties:
                connectionId: { type: string }
                text: { type: string }
      responses:
        '200':
          description: The answer
          content:
            application/json:
              schema:
                type: object
                properties:
                  duplicate: { type: boolean }
                  matches:
                    type: array
                    items:
                      type: object
                      properties:
                        postId: { type: string }
                        status: { type: string, nullable: true }
                        publishedAt: { type: integer, nullable: true }
                        xPostId: { type: string, nullable: true }
                  nearDuplicates: { $ref: '#/components/schemas/NearDuplicates' }
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '403':
          $ref: '#/components/responses/AgentError'
        '429':
          $ref: '#/components/responses/AgentRateLimited'

  /agent/attention:
    get:
      summary: What needs the owner
      description: >-
        The same queue as the PostalAi Dashboard "Needs you", for the key's connections. It lists posts waiting for
        approval (soonest deadline first; approval_expiring when under an hour), failed posts (mayBeOnX true means X may
        have accepted the post, so do not repost), a connection that needs reconnecting, and posts skipped in the last
        24 hours. Needs the x.calendar:read scope (API key issued with calendarRead true). MCP tool list_attention
        (postal.x.read); approve_x_post and reject_x_post appear as actions only for an MCP connection that may approve.
      operationId: getAgentAttention
      tags:
        - Agent
      security:
        - apiKeyAuth: []
      parameters:
        - { in: query, name: kind, schema: { type: string }, description: 'Comma-separated: approval_pending, approval_expiring, post_failed, post_skipped, connection_broken, x_deleted (published, then deleted on X; found by a read-only lookup), media_reconnect (connection lacks media.write with media posts coming up, or X refused media), media_storage_unavailable (stored media could not be read at publish time), preflight_hold (the pre-flight check ~10 minutes before the slot held the post, never sent: errorCode preflight_token, preflight_media or preflight_duplicate; detail has the reason and a Fix: hint), x_outage (𝕏 is down: one item while posts are held for it; they publish on recovery within 2h of the slot), x_outcome_unclear (Unclear if posted, needs Amit: a send got a 5xx and the timeline check was not conclusive; never sent again)' }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 50, default: 20 } }
      responses:
        '200':
          description: '{items: [{kind, severity (urgent, action, info), postId?, connectionId?, title, detail, deadline?, mayBeOnX?, actions}], total, generatedAt}'
        '400':
          description: invalid_request (unknown kind)
        '401':
          description: Missing, revoked or expired key
        '403':
          description: scope_denied (key not issued with calendarRead)
        '429':
          description: rate_limited (shares the read bucket: 300, refilling at 300 per hour)

  /agent/webhooks:
    post:
      summary: Register a signed webhook
      description: >-
        Sends approval.* and post.* events for this key's own posts (and, for a key issued with calendarRead, every
        post on its connections) to an https URL on a public host name. The signing secret is returned once, here
        only; PostalAi stores it encrypted. Each delivery is a POST with JSON {id, type, createdAt, data: {post}} and
        headers Postal-Webhook-Id, Postal-Event and Postal-Signature "t=<unix seconds>,v1=<hex HMAC-SHA256(secret,
        "<t>.<raw body>")>". Verify over the raw body and reject t older than 5 minutes; Postal-Webhook-Id is stable
        across retries, so use it to drop duplicates. Non-2xx answers or timeouts (10 s) are retried after 1 min,
        5 min, 30 min, 2 h and 8 h (6 attempts). Redirects are not followed. Up to 5 webhooks per key.
      operationId: createAgentWebhook
      tags: [Agent]
      security:
        - apiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              additionalProperties: false
              properties:
                url: { type: string, format: uri, maxLength: 500, example: 'https://hooks.example.com/postal' }
                events:
                  type: array
                  description: Defaults to every event.
                  items: { $ref: '#/components/schemas/WebhookEvent' }
      responses:
        '201':
          description: '{webhook: {id, url, events, createdAt, lastDelivery}, secret (whsec_..., shown once)}'
        '400':
          description: invalid_url (not https, IP literal, private or local host, credentials, non-default port) or invalid_request (unknown event)
        '401':
          description: Missing, revoked or expired key
        '409':
          description: too_many_webhooks
    get:
      summary: List this key's webhooks
      operationId: listAgentWebhooks
      tags: [Agent]
      security:
        - apiKeyAuth: []
      responses:
        '200':
          description: '{webhooks: [{id, url, events, createdAt, lastDelivery: {at, status, ok} | null}]} (never the secret)'
        '401':
          description: Missing, revoked or expired key

  /agent/webhooks/{id}:
    delete:
      summary: Delete a webhook
      operationId: deleteAgentWebhook
      tags: [Agent]
      security:
        - apiKeyAuth: []
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        '200':
          description: '{deleted: true, id}'
        '404':
          description: not_found (no such webhook on this key)

  /agent/webhooks/{id}/test:
    post:
      summary: Send a signed ping now
      operationId: testAgentWebhook
      tags: [Agent]
      security:
        - apiKeyAuth: []
      parameters:
        - { in: path, name: id, required: true, schema: { type: string } }
      responses:
        '200':
          description: '{deliveryId, delivered, status (receiver HTTP status or null), error}. A failed ping is retried like any delivery.'
        '404':
          description: not_found

  /analytics/posts/{tweetId}/topic:
    post:
      summary: Set a Post's Topic (owner only)
      description: |
        The owner's topic choice for a published post in Analytics (By topic). Stores it in users/{uid}/postTopics/{tweetId}
        as the owner's choice, which wins over an assistant's or the classifier's. {"topic": null} clears the owner's choice.
        The topic must be an active (not merged) id from topicCatalog/current. A topic never changes the post, its approved
        text or hash, its approval or sending. Requires a Firebase ID token for the signed-in owner. API keys and MCP/OAuth
        access tokens (any `Bearer pst_` token) are refused with 403 owner_only. There is no MCP tool for this yet.
      operationId: setAnalyticsPostTopic
      tags:
        - Analytics
      x-owner-only: true
      security:
        - bearerAuth: []
      parameters:
        - name: tweetId
          in: path
          required: true
          description: The published post's id on the network (the xPostMetrics document id)
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{1,64}$' }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [topic]
              properties:
                topic:
                  type: string
                  nullable: true
                  description: A topic id from the catalog, or null to clear the owner's choice
      responses:
        '200':
          description: Saved. topic is the post's resolved topic after the change (Untagged when nothing applies).
          content:
            application/json:
              schema:
                type: object
                properties:
                  tweetId: { type: string }
                  topic:
                    type: object
                    properties:
                      id: { type: string }
                      label: { type: string }
        '400':
          description: Missing tweetId, a bad body (invalid_request), or a topic not in the catalog or merged (unknown_topic)
        '401':
          description: Missing or invalid Firebase ID token
        '403':
          description: An API key or MCP token was used (owner_only)
        '404':
          description: The signed-in owner has no published post with this id (not_found)

  /agent/analytics/summary:
    get:
      summary: Analytics summary
      description: >-
        Read-only 𝕏 analytics for the key's connection, from the numbers PostalAi stores (read daily at 6:00 AM ET
        and hourly for posts under 48 hours old; this never calls 𝕏). For the last 7, 28 or 90 days: totals to date
        for posts published in the period, the previous period of the same length (null when it has no posts),
        followers, breakdowns by post type, by hour and weekday in Eastern Time and by creator, and the top and
        bottom 3 posts by impressions. Engagements is PostalAi's sum (likes + reposts + replies + quotes + bookmarks
        + profile visits + link clicks), not 𝕏's figure. null means 𝕏 did not return that number. Needs the
        x.calendar:read scope (API key issued with calendarRead true; MCP postal.x.read, tool get_analytics_summary).
      operationId: getAgentAnalyticsSummary
      tags: [Agent]
      security:
        - apiKeyAuth: []
      parameters:
        - { in: query, name: period, schema: { type: integer, enum: [7, 28, 90], default: 28 } }
        - { in: query, name: connectionId, schema: { type: string }, description: Defaults to the key's connection }
      responses:
        '200':
          description: >-
            {connectionId, username, period, from, to, updatedAt, notes, followers {latest, change} | null, current,
            previous | null, byKind[], byHourET[], byWeekdayET[], byCreator[] (createdBy owner, outside or an
            assistant id; byYou), reach {throughPostal, outside, ratio, lowSample, summary, note}, top[], bottom[]}. reach compares original posts made through PostalAi with posts made outside it (replies and quotes left out on both sides); ratio is PostalAi's average impressions per post over outside's, null when either side has no impressions. Each group has posts, impressions, engagements, engagementRate,
            avgImpressions, n (post count) and lowSample (true when n < 5, too few to trust). Each post has tweetId, url, postId, kind, source (postalai or outside_postalai), createdBy,
            byYou, publishedAt, textPreview and its metrics.
        '400':
          description: invalid_request (period not 7, 28 or 90)
        '401':
          description: Missing, revoked or expired key
        '403':
          description: scope_denied (key not issued with calendarRead)
        '404':
          description: connection_not_found
        '429':
          description: rate_limited (shares the read bucket: 300, refilling at 300 per hour)

  /agent/analytics/posts/{tweetId}:
    get:
      summary: One post's numbers
      description: >-
        Read-only latest numbers for one post on the key's connection, including posts made outside PostalAi, plus
        its readings 1 hour, 24 hours, 7 days and 28 days after publishing. Use /agent/analytics/posts?postId= to look
        a post up by its PostalAi id instead. Needs the x.calendar:read scope (MCP tool get_post_metrics).
      operationId: getAgentPostMetrics
      tags: [Agent]
      security:
        - apiKeyAuth: []
      parameters:
        - { in: path, name: tweetId, required: true, schema: { type: string, pattern: '^[0-9]{1,25}$' } }
      responses:
        '200':
          description: >-
            {post, poll, timeline[{mark (h1, h24, d7, d28), label, reached, readAt, impressions, engagements}],
            vsTypical{ratio, median, n, notEnoughPosts, summary}, notes}. A mark that has not passed, or was not read, has
            nulls. vsTypical compares the post's impressions with the median impressions of the same account's original
            posts (no replies or quotes) from the last 90 days; ratio and median are null when notEnoughPosts (n under 5).
            post.linkClicks includes the clicks on the thread's first reply (the only place a link is allowed);
            post.linkClicksSplit is {own, fromLinkReply, linkReplyTweetId} or null when there is no link reply.
            post.clickRate = linkClicks / impressions (null when either is unknown). post.privateMetricsFinal is true
            and post.privateMetricsFinalAt is passed 30 days after publishing: 𝕏 stops reporting link clicks, profile
            visits and private impressions then, so those numbers are final. The same clickRate and final fields are
            on the top/bottom posts of /agent/analytics/summary.
        '401':
          description: Missing, revoked or expired key
        '403':
          description: scope_denied (key not issued with calendarRead)
        '404':
          description: not_found (no numbers yet, or not on this key's connections)
        '429':
          description: rate_limited (shares the read bucket: 300, refilling at 300 per hour)

  /agent/analytics/posts:
    get:
      summary: One post's numbers, by PostalAi post id
      operationId: getAgentPostMetricsByPostId
      tags: [Agent]
      security:
        - apiKeyAuth: []
      parameters:
        - { in: query, name: postId, required: true, schema: { type: string } }
      responses:
        '200':
          description: Same as /agent/analytics/posts/{tweetId}.
        '400':
          description: invalid_request (send exactly one of tweetId or postId)
        '404':
          description: not_found

  /agent/calendar/open-slots:
    get:
      summary: Suggest open times to post (read-only)
      description: >-
        Next free times on a 30-minute grid in Eastern Time, inside startHour-endHour, on the given weekdays, at least
        minGapMinutes (default 120, never under 10) from every scheduled, pending and recently published post and from
        each other, with at most maxPerDay posts a day if set. Suggestions only; nothing is held. Needs x.calendar:read.
      parameters:
        - { name: from, in: query, schema: { type: string }, description: ISO 8601 or epoch ms; default now }
        - { name: to, in: query, schema: { type: string }, description: Default from + 7 days; at most 31 days }
        - { name: count, in: query, schema: { type: integer, minimum: 1, maximum: 20, default: 5 } }
        - { name: minGapMinutes, in: query, schema: { type: integer, minimum: 0, maximum: 1440, default: 120 } }
        - { name: startHour, in: query, schema: { type: integer, minimum: 0, maximum: 23, default: 8 } }
        - { name: endHour, in: query, schema: { type: integer, minimum: 1, maximum: 24, default: 21 } }
        - { name: weekdays, in: query, schema: { type: string, example: '1,2,3,4,5' }, description: Comma-separated 0-6, 0 = Sunday }
        - { name: maxPerDay, in: query, schema: { type: integer, minimum: 1, maximum: 50 } }
        - { name: connectionId, in: query, schema: { type: string } }
      responses:
        '200':
          description: slots [{at, local, reason}], rules, zone, note
        '400':
          description: invalid_query, invalid_range or range_too_long
        '403':
          description: insufficient_scope or connection_not_allowed
  /agent/calendar/suggested-times:
    get:
      summary: Suggest good times to post, with reasons (read-only)
      description: >-
        Open times (open-slots defaults: 8:00-21:00 Eastern Time, at least 2 h from other posts) ranked by a score that
        starts from general benchmarks and leans on the account's own views by hour as they build up: for each hour,
        own results weigh n / (n + 5), n = own posts from the last 90 days at that hour. Each suggestion lists its
        reasons. Suggestions only; nothing is held, posted or approved. Needs x.calendar:read.
      parameters:
        - { name: from, in: query, schema: { type: string }, description: ISO 8601 or epoch ms; default now }
        - { name: to, in: query, schema: { type: string }, description: Default from + 7 days; at most 31 days }
        - { name: count, in: query, schema: { type: integer, minimum: 1, maximum: 20, default: 5 } }
        - { name: connectionId, in: query, schema: { type: string } }
      responses:
        '200':
          description: suggestions [{at, local, score, basis (benchmark, blend or own), ownPosts, reasons[]}], ownPostsUsed, method, zone, note
        '400':
          description: invalid_query, invalid_range or range_too_long
        '403':
          description: insufficient_scope or connection_not_allowed
  /agent/calendar/cadence:
    get:
      summary: Posting cadence (read-only)
      description: >-
        PostalAi posts published and still on 𝕏 over the last 7, 28 or 90 days (per day, per week, days with and without
        a post, longest gap, by weekday and hour in Eastern Time) and what is lined up next. Times and counts only, never
        text. Needs x.calendar:read.
      parameters:
        - { name: days, in: query, schema: { type: integer, enum: [7, 28, 90], default: 28 } }
        - { name: connectionId, in: query, schema: { type: string } }
      responses:
        '200':
          description: Cadence
        '400':
          description: invalid_query
        '403':
          description: insufficient_scope or connection_not_allowed
  /agent/calendar:
    get:
      summary: See the calendar
      description: >-
        Every post on the key's connection with from <= scheduledAt < to, from any source (posts the owner wrote in
        the app included), so an assistant can avoid clashing times. Needs the x.calendar:read scope: an API key gets it
        only when issued with calendarRead true; an MCP connection gets it (postal.x.read, tool list_calendar) only
        when the owner ticks "See your whole calendar and analytics" on the consent card. Ordered by (scheduledAt, id). When status
        is set, filtering happens after the page read, so a page can hold fewer than limit posts; follow nextCursor
        until it is null.
      operationId: getAgentCalendar
      tags:
        - Agent
      security:
        - apiKeyAuth: []
      parameters:
        - { in: query, name: from, required: true, schema: { type: string }, description: 'Epoch ms or ISO 8601, inclusive' }
        - { in: query, name: to, required: true, schema: { type: string }, description: 'Epoch ms or ISO 8601, exclusive; at most 92 days after from' }
        - { in: query, name: status, schema: { type: string }, description: Comma-separated statuses to keep }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
        - { in: query, name: cursor, schema: { type: string }, description: nextCursor from the previous page }
        - { in: query, name: connectionId, schema: { type: string }, description: Defaults to the key's connection }
      responses:
        '200':
          description: >-
            {connectionId, posts, nextCursor}. Each post is the usual post view plus source (api or app), createdBy
            (key:<id>, grant:<id> or owner) and textPreview (first 80 characters).
        '400':
          description: invalid_range, range_too_long, invalid_cursor or invalid_request
        '401':
          description: Missing, revoked or expired key
        '403':
          description: scope_denied (key not issued with calendarRead)
        '404':
          description: connection_not_found
        '429':
          description: rate_limited (shares the read bucket: 300, refilling at 300 per hour)

  /agent/x-posts/{postId}:
    parameters:
      - in: path
        name: postId
        required: true
        schema:
          type: string
    get:
      summary: Read a post created by this API key
      description: Returns status, the X post id once published, and the sanitized error if it failed. Posts not created by this key return 404, the same as a missing post.
      operationId: getAgentXPost
      tags:
        - Agent
      security:
        - apiKeyAuth: []
      responses:
        '200':
          description: The post
          content:
            application/json:
              schema:
                type: object
                properties:
                  post:
                    $ref: '#/components/schemas/AgentXPost'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'
        '429':
          $ref: '#/components/responses/AgentRateLimited'
    patch:
      summary: Reschedule your post
      description: >-
        Moves a post this key created to a new time, or schedules or edits a draft. Only draft, pending_approval or scheduled posts that have not started
        publishing can move. Text and media do not change, so an existing approval is kept; the approval deadline
        becomes the earlier of 8 hours after the request and the new time. Retrying with the same time is safe.
        Scope x.posts:cancel_own. MCP tool reschedule_x_post. The new time (and, when scheduling a draft, its text) is
        checked like a create: 409 too_close when under 10 minutes from another pending or scheduled post on the
        connection, 409 duplicate_pending for the same text; both with hint and postId. The post is never compared with itself.
      operationId: rescheduleAgentXPost
      tags:
        - Agent
      security:
        - apiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              description: Send scheduledAt, text, or both. text is for drafts only (409 not_editable otherwise).
              properties:
                scheduledAt:
                  type: integer
                  description: Epoch milliseconds, at least 10 minutes and at most 90 days ahead. On a draft this schedules it - status becomes pending_approval with a fresh approval request (no earlier approval carries over) and the pending and create caps apply.
                text:
                  type: string
                  description: Drafts only. Replaces the draft text; no approval is needed while it is a draft.
      responses:
        '200':
          description: The post with its new time (rescheduledAt set)
        '400':
          description: schedule_too_soon, schedule_too_far or invalid_request
        '401':
          description: Missing, revoked or expired key
        '404':
          description: Not your post
        '409':
          description: not_reschedulable. The body carries the current status (publishing, published, failed, cancelled, skipped)
        '429':
          description: rate_limited (60 schedule changes per key, refilling at 60 per hour)
    delete:
      summary: Cancel a post created by this API key
      description: Cancels the post only while it is still scheduled and the worker has not claimed it. Posts not created by this key return 404.
      operationId: cancelAgentXPost
      tags:
        - Agent
      security:
        - apiKeyAuth: []
      responses:
        '200':
          description: Cancelled
          content:
            application/json:
              schema:
                type: object
                properties:
                  post:
                    type: object
                    properties:
                      id:
                        type: string
                      status:
                        type: string
                        enum: [cancelled]
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'
        '409':
          $ref: '#/components/responses/AgentError'
        '429':
          $ref: '#/components/responses/AgentRateLimited'

  /scheduled-posts/{postId}/approval:
    parameters:
      - { in: path, name: postId, required: true, schema: { type: string } }
    post:
      summary: Approve or reject a post an assistant created
      description: Owner only, with a Firebase ID token. Approval stores the SHA-256 of the text at that moment; the worker publishes only if the text still matches. API keys and MCP tokens are refused.
      operationId: decideScheduledPostApproval
      tags: [Agent]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [decision]
              properties:
                decision: { type: string, enum: [approve, reject] }
                reason: { type: string, maxLength: 500, description: 'Optional, reject only. Stored on the post and shown back to the creating API key only (its own get_x_post and its approval.rejected webhook).' }
      responses:
        '200': { description: 'Post is now scheduled (approved) or cancelled (rejected)' }
        '401': { description: 'Not signed in' }
        '404': { description: 'Not found' }
        '409': { description: 'approval_expired (post skipped) or not_pending' }

  /scheduled-posts/approvals:
    post:
      summary: Week approval - preview a week of assistant posts, then approve the ones you reviewed
      description: >-
        Owner only, with a Firebase ID token; API keys and MCP tokens are refused. action=preview returns the pending
        assistant posts due in the next `days` (default 7, at most 50) with textSha256 and mediaSha256 of exactly the
        content returned. action=approve is a batch of ordinary per-post approvals: each listed post is approved only if
        its current content still matches the hashes sent, in its own transaction, and stores that hash like a single
        approval. A post that changed, expired or is no longer pending is refused on its own; the others go ahead.
        Posts not listed are untouched. Articles are listed (hasArticle true) but never approved here
        (article_excluded); approve them one at a time. Each preview post carries text, replies, poll (options and
        durationMinutes), replySettings, paidPartnership, taggedUsers and taggedUserDetails, communityId, media
        (mediaId, kind, altText) and containsAiMedia, which covers every field in the approval hash.
      operationId: weekApproval
      tags: [Agent]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [action]
              properties:
                action: { type: string, enum: [preview, approve] }
                days: { type: integer, minimum: 1, maximum: 14, default: 7, description: preview only }
                items:
                  type: array
                  minItems: 1
                  maxItems: 50
                  description: approve only; each post at most once
                  items:
                    type: object
                    required: [postId, textSha256]
                    properties:
                      postId: { type: string }
                      textSha256: { type: string, pattern: '^[0-9a-f]{64}$', description: From the preview }
                      mediaSha256: { type: [string, 'null'], pattern: '^[0-9a-f]{64}$', description: From the preview; null or omitted when the post has no media }
      responses:
        '200': { description: 'preview - {from, to, posts[], more, note}; approve - {approved, refused, results[{postId, result approved|refused, code (text_mismatch, media_mismatch, approval_expired, not_pending, not_found, article_excluded, unavailable), message, postStatus}]}' }
        '400': { description: invalid_body }
        '401': { description: Not signed in }

  /api-keys:
    post:
      summary: Create an API key for Social Assistant
      description: |
        Creates a key scoped to the caller's account and X connections, with scopes x.posts:create, x.posts:read_own
        and x.posts:cancel_own. The key is returned once and only its peppered hash is stored. Only accounts listed
        in API_KEY_OWNER_UIDS may create keys, and at most 2 may be active. Keys expire after 90 days.
      operationId: createApiKey
      tags:
        - ApiKeys
      security:
        - bearerAuth: []
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                label:
                  type: string
                  maxLength: 80
                connectionIds:
                  type: array
                  items:
                    type: string
                  description: X connection ids the key may post to. Defaults to the default X connection.
                madeWithAi:
                  type: boolean
                  default: false
                  description: Deprecated and ignored. 𝕏's made_with_ai means AI-generated media; assistant posts are text only, so they always publish with madeWithAi false.
                calendarRead:
                  type: boolean
                  default: false
                  description: Adds the x.calendar:read scope so the key can call GET /agent/calendar, which shows every post on its connection, including ones you wrote in the app.
      responses:
        '201':
          description: Key created. Store it in the agent's secret store (POSTAL_API_KEY); it is not shown again.
          content:
            application/json:
              schema:
                type: object
                properties:
                  key:
                    type: string
                    example: pst_live_abcdefghijkl_<43 characters>
                  apiKey:
                    $ref: '#/components/schemas/ApiKey'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '403':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'
        '409':
          $ref: '#/components/responses/AgentError'
    get:
      summary: List API keys
      description: Key metadata only. Never the key or its hash.
      operationId: listApiKeys
      tags:
        - ApiKeys
      security:
        - bearerAuth: []
      responses:
        '200':
          description: Keys
          content:
            application/json:
              schema:
                type: object
                properties:
                  apiKeys:
                    type: array
                    items:
                      $ref: '#/components/schemas/ApiKey'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'

  /api-keys/{keyId}:
    parameters:
      - in: path
        name: keyId
        required: true
        schema:
          type: string
    delete:
      summary: Revoke an API key
      description: Takes effect on the next request; every agent request reads the key record.
      operationId: revokeApiKey
      tags:
        - ApiKeys
      security:
        - bearerAuth: []
      responses:
        '200':
          description: Revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  apiKey:
                    $ref: '#/components/schemas/ApiKey'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'
    patch:
      summary: Change an API key's AI label setting
      operationId: updateApiKey
      tags:
        - ApiKeys
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [madeWithAi]
              properties:
                madeWithAi:
                  type: boolean
      responses:
        '200':
          description: Updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  apiKey:
                    $ref: '#/components/schemas/ApiKey'
        '400':
          $ref: '#/components/responses/AgentError'
        '401':
          $ref: '#/components/responses/AgentError'
        '404':
          $ref: '#/components/responses/AgentError'

  /.well-known/oauth-protected-resource:
    get:
      summary: MCP protected resource metadata (RFC 9728)
      operationId: mcpResourceMetadata
      tags: [MCP]
      security: []
      responses:
        '200': { description: 'Resource metadata naming the authorization server' }
  /.well-known/oauth-authorization-server:
    get:
      summary: OAuth authorization server metadata (RFC 8414)
      operationId: oauthServerMetadata
      tags: [MCP]
      security: []
      responses:
        '200': { description: 'Endpoints, PKCE S256 only, public clients only' }
  /oauth/register:
    post:
      summary: Dynamic client registration (RFC 7591), public clients only
      description: redirect_uris must be https, loopback http, or a supported app scheme. Unverified registrations are limited to 10 per hour per IP and 300 per hour overall.
      operationId: oauthRegister
      tags: [MCP]
      security: []
      responses:
        '201': { description: 'Registered client' }
        '400': { description: 'Invalid redirect_uri or client metadata' }
        '429': { description: 'Registration rate limit' }
  /oauth/authorize:
    get:
      summary: Start authorization; redirects to the PostalAi consent page
      description: Requires response_type=code, a registered redirect_uri and a PKCE S256 code_challenge. Only owner accounts (API_KEY_OWNER_UIDS) can approve.
      operationId: oauthAuthorize
      tags: [MCP]
      security: []
      responses:
        '302': { description: 'Redirect to the consent page, or back to the client with an error' }
        '400': { description: 'Unknown client or redirect_uri mismatch' }
  /oauth/token:
    post:
      summary: Exchange an authorization code or rotate a refresh token
      description: Access tokens last 1 hour, refresh tokens 30 days and rotate on every use. Reusing a refresh token revokes the connection.
      operationId: oauthToken
      tags: [MCP]
      security: []
      requestBody:
        content:
          application/x-www-form-urlencoded:
            schema: { type: object }
      responses:
        '200': { description: 'Bearer access token and refresh token' }
        '400': { description: 'invalid_grant, unsupported_grant_type or invalid_target' }
        '401': { description: 'Unknown client' }
  /oauth/revoke:
    post:
      summary: Revoke a token (RFC 7009); revokes the whole connection
      operationId: oauthRevoke
      tags: [MCP]
      security: []
      responses:
        '200': { description: 'Always 200' }
  /oauth/requests/{requestId}:
    parameters:
      - { in: path, name: requestId, required: true, schema: { type: string } }
    get:
      summary: Describe a pending sign-in request for the consent page
      operationId: oauthDescribeRequest
      tags: [MCP]
      security:
        - bearerAuth: []
      responses:
        '200': { description: 'Client name, redirect host, Verified or Unverified, connected account' }
        '404': { description: 'Request expired' }
    post:
      summary: Allow or deny a pending sign-in request
      operationId: oauthDecideRequest
      tags: [MCP]
      security:
        - bearerAuth: []
      responses:
        '200': { description: 'Redirect URL back to the client' }
        '403': { description: 'This account cannot connect assistants' }
  /mcp:
    post:
      summary: MCP Streamable HTTP endpoint (JSON responses, stateless)
      description: Tools create_x_post, validate_x_post, check_duplicate, get_x_post, list_x_posts, cancel_x_post and whoami share the /agent/x-posts rules (8 hour minimum lead, approved text hash, duplicate guard, idempotency, limits). upload_media stores one image, GIF or video (base64, with optional altText and sensitive flags) and returns a mediaId; create_x_post takes mediaIds and containsAiMedia (true needs media). No length cap; links are refused with link_not_allowed, except one 𝕏 post link (x.com/<handle>/status/<id>) at the very end of the main text. approve_x_post (approval-scoped connections only) needs mediaSha256 for posts with media. There is no immediate-post tool. Without a valid token it returns 401 with WWW-Authenticate naming the resource metadata.
      operationId: mcp
      tags: [MCP]
      security:
        - mcpOAuth: []
      responses:
        '200': { description: 'JSON-RPC response' }
        '202': { description: 'Notification accepted' }
        '401': { description: 'Missing, expired or revoked access token' }
  /mcp-connections:
    get:
      summary: List connected assistants (Settings)
      operationId: listMcpConnections
      tags: [MCP]
      security:
        - bearerAuth: []
      responses:
        '200': { description: 'Active connections, no tokens' }
  /mcp-connections/{connectionId}:
    parameters:
      - { in: path, name: connectionId, required: true, schema: { type: string } }
    delete:
      summary: Revoke a connected assistant; its tokens stop working immediately
      operationId: revokeMcpConnection
      tags: [MCP]
      security:
        - bearerAuth: []
      responses:
        '200': { description: 'Revoked' }
        '404': { description: 'Not found' }

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: Firebase ID Token
      description: Firebase Authentication ID token
    apiKeyAuth:
      type: http
      scheme: bearer
      bearerFormat: pst_live API key
      description: Social Assistant API key, sent as Authorization Bearer. Only the /agent endpoints accept it.
    mcpOAuth:
      type: http
      scheme: bearer
      bearerFormat: pst_at OAuth access token
      description: OAuth 2.1 access token from /oauth/token. Only /mcp accepts it.

  parameters:
    IdempotencyKey:
      in: header
      name: Idempotency-Key
      required: true
      schema:
        type: string
        minLength: 8
        maxLength: 200
      description: Unique per intended post, for example a UUID. Reused within 24 hours it returns the original post.
    ScheduledPostId:
      in: path
      name: postId
      required: true
      schema:
        type: string


  responses:
    AgentError:
      description: Error with a machine-readable code
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/AgentError'
    AgentRateLimited:
      description: Rate limited. Hourly limits are token buckets that refill continuously: 60 creates (60 per hour), 300 reads, validates and cancels (300 per hour), 40 media uploads (40 per hour). Fixed UTC-day budgets: 50 creates per key and 50 per account. Also 100 pending. Retry-After is the honest wait for the next token or the next UTC midnight. Creates are charged only when they succeed; reads, validates and media uploads are charged before the work, even when it fails. Refused creates cost nothing, but 20 runaway refusals within 10 minutes (the same text refused again, or a request that cannot be valid) give 429 loop_detected for 15 minutes. An honest resend of a plan, refused as duplicate_pending or too_close, does not count.
      headers:
        Retry-After:
          schema:
            type: integer
          description: Seconds until the limit resets
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/AgentError'

  schemas:
    CreateAgentXPostRequest:
      type: object
      required: [text]
      additionalProperties: false
      description: scheduledAt is required unless draft is true.
      properties:
        connectionId:
          type: string
          description: Defaults to the first X connection on the key.
        text:
          type: string
          description: Published exactly as sent, never truncated. No PostalAi length cap; X enforces the account's limit at publish. Links are refused with 400 link_not_allowed.
        scheduledAt:
          type: integer
          format: int64
          description: Epoch milliseconds, at least 10 minutes and at most 90 days ahead. Required unless draft is true; must be omitted for a draft.
        draft:
          type: boolean
          description: Save as a draft (status draft). No scheduledAt and no approval; it never publishes or expires, sends no approval or failure webhooks, and does not count toward the pending or create caps (at most 100 drafts per key, else 429 too_many_drafts). Schedule it later with PATCH scheduledAt.
        containsAiMedia:
          type: boolean
          description: Optional. Contains AI-generated media. Sets X's made_with_ai at publish. true without mediaIds returns 400 media_required.
        poll:
          $ref: '#/components/schemas/XPoll'
        mediaIds:
          type: array
          maxItems: 20
          items:
            type: string
            pattern: '^med_[0-9a-f]{24}$'
          description: Ids from POST /agent/media. Up to 4 images, or 1 GIF, or 1 video. With article, up to 20 images, each placed in an image block or used as the cover.
        replySettings:
          type: string
          enum: [following, mentionedUsers, subscribers, verified]
          description: 'Optional. Who can reply to the main post (X reply_settings). Omit to let everyone reply. Shown on the approval card; set at create, not editable through the agent API. Not valid with article (400 invalid_request). When set, the approval hash is SHA-256 hex of JSON ["postal-reply-settings-v1", <content hash, after the poll when set>, replySettings] and the idempotency request hash includes it; when omitted both hashes are unchanged, so existing approvals keep working.'
        paidPartnership:
          type: boolean
          description: 'Optional, default false. Discloses the main post as a paid partnership on X (paid_partnership); replies never carry it. Shown on the approval card; set at create, not editable through the agent API. true with article returns 400 invalid_request. When true, the approval hash is SHA-256 hex of JSON ["postal-paid-partnership-v1", <hash after poll and replySettings>] and the idempotency request hash includes it; false or omitted leaves both hashes unchanged.'
        replies:
          $ref: '#/components/schemas/ThreadReplies'
        article:
          $ref: '#/components/schemas/XArticle'
        approval:
          type: object
          required: [textSha256]
          additionalProperties: false
          properties:
            textSha256:
              type: string
              pattern: '^[0-9a-f]{64}$'
            ref:
              type: string
              maxLength: 200
              description: Reference to the approval message in Social Assistant's chat.
            approvedAt:
              type: integer
              format: int64
    AgentXPost:
      type: object
      properties:
        rejectedAt: { type: integer, format: int64, nullable: true }
        rejectionReason: { type: string, nullable: true, description: "The owner's optional reason for rejecting. Only on the creating key's own reads and its approval.rejected webhook; null in other keys' calendar views." }
        id:
          type: string
        status:
          type: string
          enum: [scheduled, publishing, published, failed, cancelled]
        platform:
          type: string
          enum: [x]
        connectionId:
          type: string
        scheduledAt:
          type: integer
          format: int64
        xPostId:
          type: string
          nullable: true
        error:
          type: string
          nullable: true
        errorCode:
          type: string
          nullable: true
          description: On failed posts X refused, x_<status> plus X's problem type when present (for example x_403); media_unavailable when stored media couldn't be read.
        errorHint:
          type: string
          nullable: true
          description: The next step for errorCode, for example reconnect the X account or change the text. Null when there is no errorCode or no advice for it. Also sent in webhook post payloads.
        errorRetryable:
          type: boolean
          nullable: true
          description: True when the same post can succeed later unchanged (X rate limit or outage), so the owner can retry it in PostalAi. Null when there is no errorCode.
        textSha256:
          type: string
          description: The approval hash. A single post is SHA-256 hex of text. A thread is SHA-256 hex of the JSON array ["postal-thread-v1", text, reply1, reply2, ...], so one approval covers every post in order. With a poll, that hash is wrapped as SHA-256 of ["postal-poll-v1", hash, options, durationMinutes]; with replySettings set, the result is wrapped as SHA-256 of ["postal-reply-settings-v1", hash, replySettings]; with paidPartnership true, the result is wrapped again as SHA-256 of ["postal-paid-partnership-v1", hash]. Posts without them keep the plain hash.
        replies:
          type: array
          items:
            type: object
            properties:
              position: { type: integer }
              text: { type: string }
              xPostId: { type: string, nullable: true }
        threadStatus:
          type: string
          nullable: true
          enum: [complete, partial, null]
          description: Set after publishing a thread. partial means the main post is live but a reply failed (errorCode thread_partial); the owner should be told.
        linkCheck:
          $ref: '#/components/schemas/LinkCheck'
        media:
          type: array
          items:
            $ref: '#/components/schemas/MediaItem'
        mediaSha256:
          type: string
          nullable: true
          description: SHA-256 over the post's media (each file's sha256, alt text and sensitive flags, in order). Send it as approval.mediaSha256 when approving a post with media in chat. null without media.
        madeWithAi:
          type: boolean
          description: Whether X's made_with_ai (AI-generated media) is sent. True only for posts with media flagged containsAiMedia.
        poll:
          type: object
          nullable: true
          description: The post's poll, or null.
          allOf: [{ $ref: '#/components/schemas/XPoll' }]
        replySettings:
          type: string
          nullable: true
          enum: [following, mentionedUsers, subscribers, verified, null]
          description: Who can reply to the main post. null means everyone.
        paidPartnership:
          type: boolean
          description: Whether the main post is disclosed as a paid partnership on X.
    XPoll:
      type: object
      required: [options, durationMinutes]
      additionalProperties: false
      description: 'Optional poll on the main post, sent to X as poll {options, duration_minutes}. Replies never carry it. Not combinable with mediaIds (400 poll_with_media) or article (400 invalid_request); bad options or duration return 400 poll_invalid. Set at create and shown on the approval card. When present, approval.textSha256 is SHA-256 hex of JSON ["postal-poll-v1", <post or thread hash>, options, durationMinutes] (then wrapped by replySettings, then paidPartnership, when set) and the idempotency request hash includes it; without a poll both hashes are unchanged.'
      properties:
        options:
          type: array
          minItems: 2
          maxItems: 4
          items: { type: string, minLength: 1, maxLength: 25 }
        durationMinutes:
          type: integer
          minimum: 5
          maximum: 10080
    XArticle:
      type: object
      required: [blocks]
      additionalProperties: false
      description: "Optional. Publishes an X Article (long-form) instead of a post: text is the title (100 characters max), blocks are the body. No links anywhere. Images come from mediaIds and every one must be placed. approval.textSha256 is sha256 of JSON ['postal-article-v1', title, [[type, text or '', mediaId or ''] per block], coverMediaId or '']. Not combinable with replies or containsAiMedia. Needs an X account that can publish Articles."
      properties:
        blocks:
          type: array
          minItems: 1
          maxItems: 300
          items:
            type: object
            required: [type]
            additionalProperties: false
            properties:
              type: { type: string, enum: [paragraph, heading, subheading, bullet, numbered, quote, image] }
              text: { type: string, description: 'Block text; the caption for an image block' }
              mediaId: { type: string, description: 'Image blocks only: an id from mediaIds' }
        coverMediaId: { type: string, description: 'Optional cover image: an id from mediaIds' }
    OwnerSettings:
      type: object
      properties:
        timeZone: { type: string, example: America/New_York }
        digestHour: { type: integer, example: 8, description: Local hour the daily digest goes out (first hourly run at or after it) }
    WebhookEvent:
      type: string
      description: |
        digest.daily is opt-in and never in the default subscription (events omitted = every other event): list it to get one ping a day shortly after 8 AM in the owner's time zone (Settings, default America/New_York) summarising the posts this webhook may see
        (the key's own posts, plus the connection's calendar with x.calendar:read). data has date, window {from, to}, counts
        (date is the owner's local date; timeZone names the zone) {pendingApproval, scheduledNext24h, publishedLast24h, failedLast24h} and up to 20 ids per list (failed items carry
        errorCode, errorHint, errorRetryable). No post text. No ping on a day with nothing to report; at most one per local day.
      enum: [approval.requested, approval.approved, approval.rejected, post.scheduled, post.published, post.failed, post.skipped, post.cancelled, post.x_deleted, post.preflight_failed, x.outage, digest.daily]
    ThreadReplies:
      type: array
      maxItems: 9
      description: Optional self-thread replies, posted in order right after the main post. Each answers the previous post of this thread; there is no reply-to parameter. Only the first may contain a link.
      items:
        type: object
        required: [text]
        additionalProperties: false
        properties:
          text: { type: string }
    LinkCheck:
      type: object
      nullable: true
      description: Pre-approval check of the link reply's destination. Warn only.
      properties:
        url: { type: string }
        domain: { type: string }
        owned: { type: boolean }
        checkedAt: { type: integer, format: int64 }
        httpStatus: { type: integer }
        ok: { type: boolean, description: The destination answered 2xx }
        hasPreview: { type: boolean, description: og or twitter preview meta present }
        warning: { type: string }
    UploadMediaRequest:
      type: object
      required: [mimeType]
      description: Send exactly one of data or url (400 invalid_request otherwise).
      additionalProperties: false
      properties:
        mimeType:
          type: string
          enum: [image/jpeg, image/png, image/webp, image/gif, video/mp4, video/quicktime]
        data:
          type: string
          format: byte
          description: The file, base64.
        url:
          type: string
          format: uri
          maxLength: 2048
          description: |
            Media import from a URL. A public https URL (port 443, no credentials) that PostalAi downloads once, then checks
            exactly like data. Every DNS answer must be public and the connection is pinned to it; at most 3 redirects, each
            re-checked; 20 seconds; stops past 20 MB. Errors (400, with hint): media_url_invalid, media_url_blocked
            (private or reserved address), media_url_unreachable (non-2xx, too many redirects, timeout), media_too_large.
            Takes one of the 40 upload tokens before the download starts.
        altText:
          type: string
          maxLength: 1000
          description: Sent to X as alt text.
        sensitive:
          type: array
          items:
            type: string
            enum: [adult_content, graphic_violence, other]
          description: Sent to X as the sensitive-media warning.
    MediaItem:
      type: object
      properties:
        mediaId:
          type: string
        kind:
          type: string
          enum: [image, gif, video]
        mimeType:
          type: string
        bytes:
          type: integer
        sha256:
          type: string
        durationMs:
          type: integer
        altText:
          type: string
          nullable: true
        sensitive:
          type: array
          items:
            type: string
    AgentBulkCreateResponse:
      type: object
      required: [created, rejected, results]
      properties:
        created:
          type: integer
        rejected:
          type: integer
        notAttempted:
          type: integer
          description: Items skipped because a limit stopped the batch. Resend them after retryAfterSeconds.
        results:
          type: array
          items:
            type: object
            required: [index, result]
            properties:
              index:
                type: integer
              result:
                type: string
                enum: [created, rejected, not_attempted]
              post:
                $ref: '#/components/schemas/AgentXPost'
              replayed:
                type: boolean
              code:
                type: string
                description: rejected and not_attempted; same codes as POST /agent/x-posts
              message:
                type: string
              hint:
                type: string
              retryable:
                type: boolean
              retryAfterSeconds:
                type: integer
              repeatedText:
                type: boolean
                description: True when the same text was refused 3 or more times in a row. Change the item instead of resending it.
    CreateAgentXPostResponse:
      type: object
      properties:
        post:
          $ref: '#/components/schemas/AgentXPost'
        cancelUrl:
          type: string
          example: /agent/x-posts/abc123
          description: DELETE this path to cancel while the post is still scheduled.
        replayed:
          type: boolean
    AgentError:
      type: object
      properties:
        error:
          type: string
        code:
          type: string
          example: approval_mismatch
          description: Machine-readable code. 409 duplicate_pending and too_close are the 𝕏 compliance checks (see POST /agent/x-posts).
        hint:
          type: string
          description: The next step to fix the error. Omitted for codes without advice.
          example: Call validate_x_post with the exact final post and send its textSha256 in approval.
        retryable:
          type: boolean
          description: True when sending the same request again, unchanged, can succeed later (rate limits, temporary outages). Retry with backoff and the same Idempotency-Key.
        repeatedText:
          type: boolean
          description: True when the same text was refused 3 or more times in a row. Change the request instead of resending it.
        postId:
          type: string
          description: The post the error is about. For duplicate_text, duplicate_pending and too_close, the other post it clashes with.
        status:
          type: string
    ShareLink:
      type: object
      properties:
        linkId:
          type: string
        postId:
          type: string
        createdAt:
          type: integer
          description: Milliseconds since the epoch
        expiresAt:
          type: integer
          nullable: true
          description: Milliseconds since the epoch; null when the owner chose "never"
        revokedAt:
          type: integer
          nullable: true
        showAccount:
          type: boolean
        commentCount:
          type: integer
        active:
          type: boolean
    ApiKey:
      type: object
      properties:
        keyId:
          type: string
        uid:
          type: string
        scopes:
          type: array
          items:
            type: string
        connectionIds:
          type: array
          items:
            type: string
        madeWithAi:
          type: boolean
        label:
          type: string
        createdAt:
          type: integer
          format: int64
        expiresAt:
          type: integer
          format: int64
        revokedAt:
          type: integer
          format: int64
          nullable: true
        lastUsedAt:
          type: integer
          format: int64
          nullable: true
    HealthResponse:
      type: object
      properties:
        success:
          type: boolean
        firebase:
          type: object
          properties:
            firestore:
              type: string
              example: connected
            timestamp:
              type: integer
              format: int64
        functions:
          type: object
          properties:
            region:
              type: string
              example: us-central1
            status:
              type: string
              example: ok
        timestamp:
          type: integer
          format: int64

    PinterestCallbackResponse:
      type: object
      properties:
        success:
          type: boolean
        username:
          type: string
        profileImage:
          type: string
          format: uri

    PinterestBoard:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        description:
          type: string
        privacy:
          type: string
          enum: [public, protected, secret]
        pin_count:
          type: integer

    CreatePinRequest:
      type: object
      required:
        - boardId
        - imageUrl
      properties:
        boardId:
          type: string
          description: ID of the board to pin to
        title:
          type: string
          description: Pin title
        description:
          type: string
          description: Pin description
        link:
          type: string
          format: uri
          description: Link URL for the pin
        imageUrl:
          type: string
          format: uri
          description: Image URL for the pin

    CreatePinResponse:
      type: object
      properties:
        success:
          type: boolean
        pin:
          type: object
          properties:
            id:
              type: string
            title:
              type: string
            description:
              type: string
            link:
              type: string
            board_id:
              type: string

    SocialConnection:
      type: object
      properties:
        id:
          type: string
        platform:
          type: string
        username:
          type: string
        profileImage:
          type: string
          format: uri
        isDefault:
          type: boolean
        connectedAt:
          type: integer
          format: int64
        expiresAt:
          type: integer
          format: int64
          description: Access token expiry (ms). Tokens themselves are never returned.

    XUser:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        username:
          type: string
        profile_image_url:
          type: string
        public_metrics:
          type: object
          properties:
            followers_count:
              type: integer
            following_count:
              type: integer
            tweet_count:
              type: integer
            listed_count:
              type: integer
            like_count:
              type: integer

    ScheduledPostStatus:
      type: string
      enum: [draft, scheduled, publishing, published, failed]

    ScheduledPost:
      type: object
      properties:
        id:
          type: string
        userId:
          type: string
        connectionId:
          type: string
        platform:
          type: string
          enum: [pinterest, x]
        status:
          $ref: '#/components/schemas/ScheduledPostStatus'
        scheduledAt:
          type: integer
          format: int64
        publishedAt:
          type: integer
          format: int64
        pinterest:
          type: object
          properties:
            boardId:
              type: string
            boardName:
              type: string
            title:
              type: string
            description:
              type: string
            link:
              type: string
            imageUrl:
              type: string
            pinId:
              type: string
        x:
          type: object
          properties:
            text:
              type: string
            mediaUrls:
              type: array
              items:
                type: string
            containsAiMedia:
              type: boolean
              description: Contains AI-generated media. Only allowed when the post has media (400 media_required otherwise). Sets X's made_with_ai at publish; text-only posts never carry it.
            media:
              type: array
              items:
                $ref: '#/components/schemas/MediaItem'
            tweetId:
              type: string
        createdAt:
          type: integer
          format: int64
        updatedAt:
          type: integer
          format: int64
        error:
          type: string
        retryCount:
          type: integer

    NearDuplicates:
      type: array
      description: |
        Near-duplicate wording, a warning only (never blocks, never changes ok). Up to 3 posts on the same account whose
        wording reads at least 70% the same (word-pair overlap after lowercasing and dropping links and punctuation;
        texts under 6 words are never flagged): active posts, PostalAi posts published in the last 30 days and, for keys
        with x.calendar:read, stored posts made outside PostalAi. textPreview is only returned with x.calendar:read.
        Also returned on create_x_post (empty for drafts).
      items:
        type: object
        properties:
          postId: { type: string, nullable: true }
          xPostId: { type: string, nullable: true }
          status: { type: string, enum: [active, published] }
          source: { type: string, enum: [postalai, outside_postalai] }
          similarity: { type: number, description: 0.7 to 1 }
          textPreview: { type: string }

    ScheduledPostResponse:
      type: object
      properties:
        success:
          type: boolean
        post:
          $ref: '#/components/schemas/ScheduledPost'

    CreateScheduledPostRequest:
      type: object
      required: [connectionId, platform]
      properties:
        connectionId:
          type: string
        platform:
          type: string
          enum: [pinterest, x]
        scheduledAt:
          type: integer
          format: int64
          description: Publish time in ms since the epoch. Omit to publish on the next worker run.
        pinterest:
          type: object
          required: [boardId, boardName, title, description, link, imageUrl]
          properties:
            boardId:
              type: string
            boardName:
              type: string
            title:
              type: string
            description:
              type: string
            link:
              type: string
            imageUrl:
              type: string
        x:
          type: object
          required: [text]
          properties:
            text:
              type: string
            mediaUrls:
              type: array
              items:
                type: string
            containsAiMedia:
              type: boolean
              description: Contains AI-generated media. Only allowed when mediaUrls is not empty (400 otherwise). Sets 𝕏's made_with_ai at publish; text-only posts never carry it.

    UpdateScheduledPostRequest:
      type: object
      properties:
        scheduledAt:
          type: integer
          format: int64
        pinterest:
          type: object
          additionalProperties: true
        x:
          type: object
          properties:
            text:
              type: string
            mediaUrls:
              type: array
              items:
                type: string
            containsAiMedia:
              type: boolean
              description: Contains AI-generated media. Only allowed when mediaUrls is not empty (400 otherwise). Sets 𝕏's made_with_ai at publish; text-only posts never carry it.

  tags:
    - name: System
      description: System health and status endpoints
    - name: Pinterest
      description: Pinterest integration endpoints
    - name: X
      description: X (Twitter) integration endpoints
    - name: Connections
      description: General social media connection management
    - name: Agent
      description: Social Assistant endpoints, authenticated with a scoped API key
    - name: ApiKeys
      description: Create, list and revoke Social Assistant API keys (Firebase ID token)
    - name: ScheduledPosts
      description: Create, read, update and cancel scheduled posts. These endpoints are the only write path.
