openapi: 3.1.0
info:
  title: Slop Monkey API
  version: "1.0.0"
  summary: Rewrite AI drafts so they read like a person wrote them, keeping facts and quotations intact.
  description: |
    One endpoint rewrites text; two more report usage and check a key.

    * Authenticate with `Authorization: Bearer sm_live_...` (or `sm_test_...` for test mode).
    * Send JSON (UTF-8). Every response has a `Request-Id` header.
    * Every error has the same shape (`ErrorResponse`). Errors are never charged.
    * Send an `Idempotency-Key` with every rewrite: a repeat within 24 hours is never charged twice.
    * Within v1 we only add fields, events, error codes and endpoints. Ignore what you don't recognise.
    * API words are a balance of their own, bought in packs on https://slopmonkey.app/api/keys. They are
      separate from the words used in the Slop Monkey app, and the two can't be swapped.
    * Test keys (`sm_test_...`) are free for any signed-in account. Live keys (`sm_live_...`) can be made
      at once by any signed-in account; their requests spend API words, bought on the keys page through
      Stripe Checkout with nothing to fill in first. A live key with no words answers 402 insufficient_words.
  contact:
    email: support@slopmonkey.app
    url: https://slopmonkey.app/api/docs
  termsOfService: https://slopmonkey.app/api/terms
servers:
  - url: https://slopmonkey.app/api/v1
security:
  - bearerAuth: []
tags:
  - name: Rewrites
  - name: Account

paths:
  /rewrites:
    post:
      tags: [Rewrites]
      operationId: createRewrite
      summary: Rewrite text
      description: |
        Rewrites `text` so it reads like a person wrote it. Text over about 370 words is split into
        sections at paragraph or sentence breaks and the sections are rewritten in parallel, then joined
        with the original whitespace.

        Charged `max(words_in, 100)` words, reserved when the request is admitted and settled when it
        finishes: sections returned unchanged are not charged, and any error is fully refunded.

        With `"stream": true` the answer is `text/event-stream`. Errors found before the stream opens
        (auth, validation, balance, limits) are ordinary JSON errors with their HTTP status. After that,
        events are, in order: `rewrite.started`, then `text.delta` / `section.reset` / `section.done` /
        `ping` (sections strictly in order), then exactly one of `rewrite.completed` or `error`. Each
        event is `event: <name>` + `data: <one line of JSON>` + a blank line. Payload schemas:
        `StreamStarted`, `StreamDelta`, `StreamSectionReset`, `StreamSectionDone`, `StreamPing`,
        `Rewrite` (for `rewrite.completed`) and `ErrorResponse` (for `error`). A stream that ends without
        either final event was cut off: retry with the same `Idempotency-Key`.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
        - $ref: '#/components/parameters/TestScenario'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RewriteRequest'
            examples:
              simple:
                summary: Just text
                value:
                  text: In the ever-evolving landscape of remote work, it is important to note that clear communication plays a pivotal role in fostering collaboration.
              protected:
                summary: With protected terms and the fact check
                value:
                  text: In the ever-evolving landscape of remote work, it is important to note that clear communication plays a pivotal role in fostering collaboration. Acme Corp found that teams who wrote things down shipped 23% faster.
                  protect: [Acme Corp]
                  include: [checks]
              streaming:
                summary: Streamed
                value:
                  text: In the ever-evolving landscape of remote work, it is important to note that clear communication plays a pivotal role in fostering collaboration.
                  stream: true
      responses:
        '200':
          description: The rewrite (JSON), or a stream of server-sent events when `stream` is true.
          headers:
            Request-Id: { $ref: '#/components/headers/RequestId' }
            RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Rewrite'
              examples:
                protected:
                  value:
                    id: req_5bT2wQ9mXc7KdLz0RfVa1p
                    object: rewrite
                    created: 1767225600
                    livemode: true
                    replayed: false
                    output: Remote work runs on clear communication. At Acme Corp, teams that wrote things down shipped 23% faster.
                    words_in: 34
                    words_out: 17
                    sections: 1
                    warnings: []
                    usage: { words_charged: 100, balance: 48212 }
                    checks: { facts_checked: 2, facts_kept: 2, missing: [], added_numbers: [] }
            text/event-stream:
              schema:
                type: string
                description: Server-sent events; see the operation description and the Stream* schemas.
              example: |
                event: rewrite.started
                data: {"id":"req_5bT2wQ9mXc7KdLz0RfVa1p","object":"rewrite","livemode":true,"words_in":22,"sections":1,"usage":{"words_reserved":100,"balance":48212}}

                event: text.delta
                data: {"section":0,"text":"Remote work runs on clear communication."}

                event: section.done
                data: {"section":0,"status":"rewritten"}

                event: rewrite.completed
                data: {"id":"req_5bT2wQ9mXc7KdLz0RfVa1p","object":"rewrite","created":1767225600,"livemode":true,"replayed":false,"output":"Remote work runs on clear communication.","words_in":22,"words_out":6,"sections":1,"warnings":[],"usage":{"words_charged":100,"balance":48212}}
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '402': { $ref: '#/components/responses/PaymentRequired' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/NotFound' }
        '405': { $ref: '#/components/responses/MethodNotAllowed' }
        '409': { $ref: '#/components/responses/Conflict' }
        '413': { $ref: '#/components/responses/TooLarge' }
        '415': { $ref: '#/components/responses/UnsupportedMediaType' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }
        '503': { $ref: '#/components/responses/Unavailable' }
        '504': { $ref: '#/components/responses/Timeout' }

  /usage:
    get:
      tags: [Account]
      operationId: getUsage
      summary: Balance and this month's use
      description: The word balance, and this calendar month's (UTC) API use for the account and for the calling key. Free. Call it at most once a minute.
      responses:
        '200':
          description: Usage.
          headers:
            Request-Id: { $ref: '#/components/headers/RequestId' }
            RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Usage'
              example:
                object: usage
                livemode: true
                balance: { words: 48212, plan_words: 0, purchased_words: 48212 }
                period: { start: 1764547200, end: 1767225600 }
                account: { api_words: 21400, api_requests: 133, monthly_cap: null }
                key: { id: key_3hVq8ZtR1mWc, name: Production, hint: Qz9X, api_words: 18600, api_requests: 120, monthly_cap: 50000 }
                limits: { requests_per_minute: 60, concurrent_requests: 2, words_per_request: 5000, minimum_words_per_request: 100 }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
        '500': { $ref: '#/components/responses/ServerError' }

  /ping:
    get:
      tags: [Account]
      operationId: ping
      summary: Check the API and, optionally, a key
      description: Never wakes the model and never charges. Without a key, answers `authenticated false`. With a bad key, answers 401.
      security:
        - {}
        - bearerAuth: []
      responses:
        '200':
          description: The API is up.
          headers:
            Request-Id: { $ref: '#/components/headers/RequestId' }
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Ping'
              examples:
                anonymous:
                  value: { object: ping, ok: true, authenticated: false }
                withKey:
                  value: { object: ping, ok: true, authenticated: true, livemode: true, key: { id: key_3hVq8ZtR1mWc, name: Production, hint: Qz9X } }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        An API key from https://slopmonkey.app/api/keys, matching `^sm_(live|test)_[0-9A-Za-z]{38}$`
        (32 random base62 characters and a 6-character base62 CRC32 checksum). Server-side only:
        requests from browsers are refused.

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: |
        1 to 255 printable ASCII characters; a UUID is ideal. Remembered for 24 hours per account and mode.
        A repeat of a finished or cut-off request is rewritten again at no charge (`replayed: true`, up to 3 times);
        a repeat while the first is running gets 409; the same key with a different body gets 422.
      schema:
        type: string
        minLength: 1
        maxLength: 255
        pattern: '^[\x21-\x7E]+$'
    TestScenario:
      name: Slopmonkey-Test
      in: header
      required: false
      description: |
        Test keys only (ignored with a live key). Forces a path: any `ErrorCode` value, or
        `section_reset`, `mid_stream_error`, `slow`.
      schema:
        type: string

  headers:
    RequestId:
      description: Unique id of this request, `req_` and 22 base62 characters. Also in the body as `id` or `request_id`.
      schema: { type: string, pattern: '^req_[0-9A-Za-z]{22}$' }
    RateLimitLimit:
      description: Requests allowed per minute for this account (and mode).
      schema: { type: integer }
    RateLimitRemaining:
      description: Requests left in the current minute.
      schema: { type: integer }
    RateLimitReset:
      description: Seconds until the current minute's count resets.
      schema: { type: integer }
    RetryAfter:
      description: Seconds to wait before retrying.
      schema: { type: integer }
    Allow:
      description: Methods the path accepts.
      schema: { type: string }

  schemas:
    RewriteRequest:
      type: object
      additionalProperties: false
      required: [text]
      properties:
        text:
          type: string
          minLength: 1
          description: |
            The draft. 1 to 5,000 words, counted as in the app: each run of letters or digits (with inner
            apostrophes and hyphens) is one word, and each Chinese, Japanese or Korean character is one word.
            Any Unicode except NUL and unpaired surrogates. `\r\n` is read as `\n`. Leading and trailing
            whitespace is dropped. The whole body is at most 128 KiB.
        protect:
          type: array
          maxItems: 50
          default: []
          description: Exact strings (case-sensitive) to keep character for character wherever they occur.
          items:
            type: string
            minLength: 1
            maxLength: 400
        protect_quotes:
          type: boolean
          default: true
          description: Also keep quotations of 3 or more words (or 6 or more Chinese characters) in double quotation marks on one line, up to 400 characters.
        include:
          type: array
          default: []
          uniqueItems: true
          description: Optional extras. Only `checks` is available in v1; `score` is reserved and answers 400 invalid_parameter.
          items:
            type: string
            enum: [checks, score]
        stream:
          type: boolean
          default: false
          description: Answer with server-sent events.

    Rewrite:
      type: object
      required: [id, object, created, livemode, replayed, output, words_in, words_out, sections, warnings, usage]
      properties:
        id:
          type: string
          description: The request id (same as the Request-Id header). Not retrievable in v1.
          pattern: '^req_[0-9A-Za-z]{22}$'
        object:
          type: string
          const: rewrite
        created:
          type: integer
          description: Unix seconds.
        livemode:
          type: boolean
        replayed:
          type: boolean
          description: True when this answers a repeated Idempotency-Key. The text was rewritten again and nothing was charged.
        output:
          type: string
        words_in:
          type: integer
          minimum: 1
        words_out:
          type: integer
          minimum: 0
        sections:
          type: integer
          minimum: 1
          description: How many sections the text was split into and rewritten separately.
        warnings:
          type: array
          items:
            $ref: '#/components/schemas/Warning'
        usage:
          $ref: '#/components/schemas/RewriteUsage'
        checks:
          $ref: '#/components/schemas/Checks'
        score:
          $ref: '#/components/schemas/Score'

    Warning:
      type: object
      required: [code, message]
      properties:
        code:
          type: string
          description: New codes may be added within v1.
          enum: [section_unchanged, section_truncated, protect_not_found]
        message:
          type: string
        section:
          type: [integer, 'null']
          description: Zero-based section index, or null when the warning is about the whole request.

    RewriteUsage:
      type: object
      required: [words_charged, balance]
      properties:
        words_charged:
          type: integer
          minimum: 0
          description: Words taken from the API balance by this request. 0 on a replay. For a test key, what a live request would have charged (nothing is taken).
        balance:
          type: integer
          minimum: 0
          description: API words left in the account after this request (for a test key, the live API balance, unchanged).

    Checks:
      type: object
      description: The fact check, over the whole text. Protected passages are excluded (they are guaranteed).
      required: [facts_checked, facts_kept, missing, added_numbers]
      properties:
        facts_checked:
          type: integer
        facts_kept:
          type: integer
        missing:
          type: array
          items:
            type: object
            required: [kind, value, section]
            properties:
              kind:
                type: string
                enum: [number, range, link, quote, name]
              value:
                type: string
              section:
                type: integer
        added_numbers:
          type: array
          description: Numbers in the rewrite that were not in the draft.
          items:
            type: string

    Score:
      type: object
      description: |
        Our own estimate from one open-source detector, the figure the app shows as "% human". Other
        detectors disagree; it is not a promise about any detector.
      required: [human_percent, method, sentences]
      properties:
        human_percent:
          type: integer
          minimum: 0
          maximum: 100
        method:
          type: string
          examples: [slopmonkey-detector-1, test]
        sentences:
          type: array
          items:
            type: object
            required: [start, end, ai_probability]
            properties:
              start:
                type: integer
                description: Offset into `output`, in Unicode code points.
              end:
                type: integer
              ai_probability:
                type: number
                minimum: 0
                maximum: 1

    StreamStarted:
      type: object
      description: Data of `event rewrite.started`.
      required: [id, object, livemode, words_in, sections, usage]
      properties:
        id: { type: string }
        object: { type: string, const: rewrite }
        livemode: { type: boolean }
        words_in: { type: integer }
        sections: { type: integer }
        usage:
          type: object
          required: [words_reserved, balance]
          properties:
            words_reserved: { type: integer }
            balance: { type: integer, description: Balance after the reservation. }

    StreamDelta:
      type: object
      description: Data of `event text.delta`. Append `text` to section `section`. Never contains a placeholder.
      required: [section, text]
      properties:
        section: { type: integer, minimum: 0 }
        text: { type: string }

    StreamSectionReset:
      type: object
      description: Data of `event section.reset`. Discard what you have for that section; it is being written again.
      required: [section, reason]
      properties:
        section: { type: integer, minimum: 0 }
        reason: { type: string, enum: [language, protected_text] }

    StreamSectionDone:
      type: object
      description: Data of `event section.done`.
      required: [section, status]
      properties:
        section: { type: integer, minimum: 0 }
        status: { type: string, enum: [rewritten, unchanged, truncated] }

    StreamPing:
      type: object
      description: Data of `event ping`, sent every 15 seconds when nothing else is.
      additionalProperties: false

    Usage:
      type: object
      required: [object, livemode, balance, period, account, key, limits]
      properties:
        object: { type: string, const: usage }
        livemode: { type: boolean }
        balance:
          type: object
          required: [words, plan_words, purchased_words]
          properties:
            words: { type: integer, description: API words left. }
            plan_words: { type: integer, description: Always 0 in v1 (there are no API subscriptions). Kept so the shape can grow. }
            purchased_words: { type: integer, description: API words bought in packs (or credited by Slop Monkey). They do not expire. }
        period:
          type: object
          required: [start, end]
          description: The current calendar month, UTC, in unix seconds.
          properties:
            start: { type: integer }
            end: { type: integer }
        account:
          type: object
          required: [api_words, api_requests, monthly_cap]
          properties:
            api_words: { type: integer }
            api_requests: { type: integer }
            monthly_cap: { type: [integer, 'null'] }
        key:
          type: object
          required: [id, name, hint, api_words, api_requests, monthly_cap]
          properties:
            id: { type: string, pattern: '^key_[0-9A-Za-z]{12}$' }
            name: { type: string }
            hint: { type: string, description: Last 4 characters of the key. }
            api_words: { type: integer }
            api_requests: { type: integer }
            monthly_cap: { type: [integer, 'null'] }
        limits:
          type: object
          required: [requests_per_minute, concurrent_requests, words_per_request, minimum_words_per_request]
          properties:
            requests_per_minute: { type: integer }
            concurrent_requests: { type: integer }
            words_per_request: { type: integer }
            minimum_words_per_request: { type: integer }

    Ping:
      type: object
      required: [object, ok, authenticated]
      properties:
        object: { type: string, const: ping }
        ok: { type: boolean }
        authenticated: { type: boolean }
        livemode: { type: boolean }
        key:
          type: object
          properties:
            id: { type: string }
            name: { type: string }
            hint: { type: string }

    ErrorType:
      type: string
      enum:
        - invalid_request_error
        - authentication_error
        - permission_error
        - billing_error
        - idempotency_error
        - rate_limit_error
        - api_error
        - overloaded_error

    ErrorCode:
      type: string
      description: Stable. Branch on this, not on `message`. New codes may be added within v1.
      enum:
        - https_required
        - invalid_json
        - missing_parameter
        - invalid_parameter
        - unknown_parameter
        - text_empty
        - text_too_long
        - too_many_protected
        - idempotency_key_invalid
        - missing_api_key
        - invalid_api_key
        - revoked_api_key
        - insufficient_words
        - spend_cap_reached
        - browser_not_allowed
        - account_suspended
        - not_found
        - method_not_allowed
        - idempotency_in_progress
        - idempotency_key_exhausted
        - request_too_large
        - unsupported_media_type
        - idempotency_key_reused
        - rate_limited
        - concurrency_limited
        - internal_error
        - overloaded
        - model_unavailable
        - timeout

    Error:
      type: object
      required: [type, code, message, param, doc_url]
      properties:
        type: { $ref: '#/components/schemas/ErrorType' }
        code: { $ref: '#/components/schemas/ErrorCode' }
        message:
          type: string
          description: For a developer reading a log. May change.
        param:
          type: [string, 'null']
          description: The request field at fault, if any.
        doc_url:
          type: string
          format: uri

    ErrorResponse:
      type: object
      required: [error, request_id]
      properties:
        error: { $ref: '#/components/schemas/Error' }
        request_id: { type: string }

  responses:
    BadRequest:
      description: |
        Invalid request: https_required, invalid_json, missing_parameter, invalid_parameter,
        unknown_parameter, text_empty, text_too_long, too_many_protected, idempotency_key_invalid.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
          example:
            error:
              type: invalid_request_error
              code: text_too_long
              message: "`text` is 6,240 words. The limit is 5,000 a request. Split it at a paragraph break and send the parts as separate requests."
              param: text
              doc_url: https://slopmonkey.app/api/docs#text_too_long
            request_id: req_9KcV3pWm2TqZx8Ld1RbNa4
    Unauthorized:
      description: missing_api_key, invalid_api_key, revoked_api_key.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
          example:
            error:
              type: authentication_error
              code: missing_api_key
              message: "No API key was sent. Send it as `Authorization: Bearer sm_live_...`. Create one at https://slopmonkey.app/api/keys."
              param: null
              doc_url: https://slopmonkey.app/api/docs#missing_api_key
            request_id: req_9KcV3pWm2TqZx8Ld1RbNa4
    PaymentRequired:
      description: insufficient_words, spend_cap_reached. Do not retry until a person acts in the account.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
          example:
            error:
              type: billing_error
              code: insufficient_words
              message: This request needs 1,240 words and the account has 800 API words. Buy more at https://slopmonkey.app/api/keys. Nothing was charged.
              param: null
              doc_url: https://slopmonkey.app/api/docs#insufficient_words
            request_id: req_9KcV3pWm2TqZx8Ld1RbNa4
    Forbidden:
      description: browser_not_allowed, account_suspended (the account is suspended, or its API access is paused).
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    NotFound:
      description: not_found.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    MethodNotAllowed:
      description: method_not_allowed.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
        Allow: { $ref: '#/components/headers/Allow' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    Conflict:
      description: idempotency_in_progress (retry after Retry-After), idempotency_key_exhausted (use a new key).
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    TooLarge:
      description: request_too_large (body over 128 KiB).
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    UnsupportedMediaType:
      description: unsupported_media_type.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    Unprocessable:
      description: idempotency_key_reused (the key was used with a different body).
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    TooManyRequests:
      description: rate_limited, concurrency_limited. Wait Retry-After seconds.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
        RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
        RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
        RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    ServerError:
      description: internal_error. Nothing was charged. Retry with backoff.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    Unavailable:
      description: overloaded, model_unavailable. Nothing was charged. Wait Retry-After seconds.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
    Timeout:
      description: timeout (over 280 seconds). Nothing was charged.
      headers:
        Request-Id: { $ref: '#/components/headers/RequestId' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/ErrorResponse' }
