openapi: 3.1.0
info:
  title: Yappr API
  description: >
    Create and manage AI voice agents, purchase phone numbers, configure tools, and initiate calls — all via REST.
  version: 1.0.0
  contact:
    url: https://goyappr.com

servers:
  - url: https://api.goyappr.com
    description: Production

security:
  - apiKey: []

components:
  securitySchemes:
    mcpOAuth:
      type: oauth2
      description: >-
        OAuth account authorization for the remote MCP server, using authorization code flow with PKCE S256.
        A workspace owner or admin chooses the workspace and explicitly approves the permissions.
        Call content is a separate consent choice. Older connections do not gain workspace management.
      flows:
        authorizationCode:
          authorizationUrl: https://mcp.goyappr.com/authorize
          tokenUrl: https://mcp.goyappr.com/token
          scopes:
            yappr.read: Read workspace setup and call statistics
            yappr.build: Create agents and edit drafts
            yappr.manage: Manage live workspace operations after explicit approval
            offline_access: Continue access using a rotating refresh token
    apiKey:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: >-
        Your Yappr API key (e.g. `ypr_live_...`). Generate one in the dashboard under **Settings → API Keys**.
        No key is `401 MISSING_KEY`; a key that is not one of ours, or is revoked, is `401 INVALID_KEY`; an
        expired one is `401 EXPIRED_KEY`. A valid key without the scope an operation needs is
        `403 INSUFFICIENT_SCOPE` on every operation, and the message names the scope. Every response,
        a 401 included, carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset: the budget
        is 60 requests a minute per API key. Every 429, whatever its code, carries Retry-After (whole
        seconds, never zero): the per-key budget's `RATE_LIMIT` asks for what is left of the minute, a
        route's daily cap (`RATE_LIMITED`) for the time until that cap resets. All four headers are listed
        in Access-Control-Expose-Headers, so a browser can read them.
        A path the API does not serve (an unknown sub-path, an id left empty) is
        `404 ROUTE_NOT_FOUND`, and a method a served path does not take is `405 METHOD_NOT_ALLOWED`
        with an `Allow` header; both are answered before any scope check, and nothing is read or changed.
        A trailing slash is ignored where it cannot be an id left empty (`POST /calls/` is `POST /calls`)
        and refused where it can (`GET /calls/`). A doubled slash inside a path is merged into one before
        the request reaches the API (`GET //calls` is `GET /calls`).

  headers:
    RetryAfter:
      description: Whole seconds to wait before sending the request again. Never zero.
      schema: { type: integer, minimum: 1 }

  responses:
    CarrierAccountsNotEnabled:
      description: |
        `CARRIER_ACCOUNTS_NOT_ENABLED` — Yappr has switched calling out through your own
        Telnyx account off for this workspace. It is available in every workspace, so this
        is only the emergency-off answer; contact Yappr support. Every carrier-accounts
        route answers this while it is off (check with
        [GET /carrier-accounts/status](/api-reference/carrier-accounts/status)). An API key
        without the route's scope gets a 403 of its own.
      content:
        application/json:
          schema:
            allOf:
              - { $ref: "#/components/schemas/Error" }
              - type: object
                properties:
                  enabled: { type: boolean, example: false }
          example:
            error: Calling out through your own Telnyx account is switched off for this workspace. Contact Yappr support.
            code: CARRIER_ACCOUNTS_NOT_ENABLED
            enabled: false
  parameters:
    ExecutionLimit:
      in: query
      name: execution_limit
      required: false
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
      description: How many execution-history rows one page holds. Only read when the `execution` block is returned.
    ExecutionCursor:
      in: query
      name: execution_cursor
      required: false
      schema: { type: string }
      description: >
        The next page of execution history. Do not build it: follow `execution.history.next_url`
        (or `refresh_url`), which carries it with the limit and filters it was issued for. A cursor
        this read did not issue, or sent with different filters, is `422 EXECUTION_CURSOR_INVALID`;
        one older than the retained history is `410 EXECUTION_RETENTION_EXPIRED`.
    ExecutionPhase:
      in: query
      name: execution_phase
      required: false
      schema: { type: string, enum: [before, during, after, platform] }
      description: Only execution-history rows from this phase of the call.
    ExecutionKind:
      in: query
      name: execution_kind
      required: false
      schema: { type: string, enum: [execution, request, physical_call, phase, action, attempt, receipt, sequence, control, producer, readiness, legacy_webhook, dnc_webhook, lead_stage, recovery] }
      description: Only execution-history rows of this kind.
    ExecutionStatus:
      in: query
      name: execution_status
      required: false
      schema: { type: string, enum: [waiting, running, succeeded, failed, pending_external, unknown, skipped, cancelled, validation_blocked] }
      description: >
        Only execution-history rows in this status - a filter on the rows of `execution.history`.
        Not the response member of the same name, which says what `execution` is on the read
        (included, omitted, pending or none).

  schemas:
    ExtractedDatePrecision:
      type: object
      description: >
        How precisely a caller gave one date parameter's answer. day - they named a day, and
        extracted_data holds it. month - they named a month and no day ("sometime in November",
        "mid-November", "next month"); extracted_data holds null, because a month is not a day and
        storing its 1st would be a guess, and month says which month. unknown - nothing that is a
        day or a month ("after the holidays"), or nothing at all. A date the caller said already
        happened is counted back ("I arrived on the 5th of March", "נכנסתי ביוני"); a date after a past
        verb that is the day of something still to come stays ahead ("I got a letter for my hearing on
        the 12th of November"), and so does the day of an event that a letter, message or call told
        the caller about ("I got a letter about my surgery on the 12th of November", "קיבלתי מכתב על
        הניתוח ב-12 בנובמבר"); the day results, a copy or an application were received stays past
        ("I received the results of my MRI on the 5th of March"). Which day a letter names - the
        event's or its own - is the reader's judgement, returned as role (below), and it decides the
        direction of a day or month said with no year. A date parameter whose description is about
        something upcoming ("upcoming appointment", "הניתוח המתוכנן") is never counted back.
      required: [precision, month]
      properties:
        precision: { type: string, enum: [day, month, unknown] }
        month:
          type: string
          nullable: true
          description: The year and month of the day or month named, as YYYY-MM; null when precision is unknown.
          example: "2026-11"
        approximate:
          type: boolean
          enum: [true]
          description: >
            Present, and true, only on a month worked out from a length of time ago in months or years
            ("a month ago", "three months ago", "לפני חודשיים וחצי", "two and a half years ago") - that
            length back from the call's month, as near as it can put it; a range of lengths ("six to seven
            months ago") is its middle. Absent on a month the caller named ("last month").
        role:
          type: string
          enum: [event, message]
          description: >
            What the day belongs to, as the reader judged it from the caller's words. event - the day of
            the thing itself: a surgery, test, hearing, appointment, flight, arrival or expiry, and the day
            a payment or refund falls due, results are ready or a lease or approval ends ("I got a letter
            about my knee replacement on the 3rd of December" is the knee replacement's day, 2026-12-03 for
            a call in September 2026, and "I got an email that my payment is due on the 5th of March" is
            2027-03-05; an event the caller had stays in the past). message - the day a letter, message,
            call, form or notice was sent or received, or a result, approval, refund or payment was
            already received or paid, which has passed ("I got a letter about my lease on the 5th of
            March" is 2026-03-05). Absent when the reader could not say, when the caller's own words settle it
            the other way (a letter about a flight or a surgery is that event's day; a letter answering
            an appeal or a claim, or about a surgery's approval or cost, is the letter's), and on calls
            analysed before it was recorded; the date is then read from the caller's words alone.
          example: event
        ambiguity:
          type: array
          items: { type: string, enum: [weekday_mismatch] }
          description: >
            Present only when the caller's own words disagreed about the day and one reading was kept.
            weekday_mismatch - they gave a weekday with a day of the month that falls on another weekday
            ("next Tuesday the 14th" when the 14th is a Wednesday, "ביום שלישי ה-14"): the day of the
            month they stated is kept (2026-10-14), not the weekday. Confirm the day before booking it.
          example: [weekday_mismatch]
    ExtractedNumberRange:
      type: object
      description: >
        A number parameter's answer that was the middle of a range the caller gave ("between six and
        seven", "בין שש לשבע", "3-4"): extracted_data holds the middle (6.5), and this the two ends.
      required: [low, high]
      properties:
        low: { type: number, example: 6 }
        high: { type: number, example: 7 }
    WorkflowDocument:
      additionalProperties: false
      properties:
        schema_version:
          const: '1'
          default: '1'
          title: Schema Version
          type: string
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        name:
          maxLength: 200
          minLength: 1
          title: Name
          type: string
        strict_mode:
          default: false
          title: Strict Mode
          type: boolean
        global_instructions:
          default: ''
          description: 'Prose may read a Before-call step''s output as {{before.<step_id>.<dotted.path>}}, optionally
            ending with |text used when the value is missing. The publisher validates the step and the path; the value
            is substituted once, at session start. {{option one|option two}} - two or more plain-text options separated
            by |, the first not starting with before. or call. - is a random variation: one option is said, picked once
            per call.'
          maxLength: 100000
          title: Global Instructions
          type: string
        channels:
          items:
            enum:
            - phone
            - web
            type: string
          minItems: 1
          title: Channels
          type: array
        request_schema:
          additionalProperties:
            $ref: '#/components/schemas/WorkflowV1JsonValue'
          title: Request Schema
          type: object
        stored_schema:
          additionalProperties:
            $ref: '#/components/schemas/WorkflowV1JsonValue'
          title: Stored Schema
          type: object
        bindings:
          items:
            $ref: '#/components/schemas/WorkflowV1ToolBinding'
          maxItems: 512
          title: Bindings
          type: array
        before:
          $ref: '#/components/schemas/WorkflowV1BeforePhase'
        conversation:
          $ref: '#/components/schemas/WorkflowV1ConversationGraph'
        after:
          items:
            $ref: '#/components/schemas/WorkflowV1AfterTrigger'
          maxItems: 64
          title: After
          type: array
        sequences:
          items:
            $ref: '#/components/schemas/WorkflowV1ToolSequence'
          maxItems: 64
          title: Sequences
          type: array
        editor:
          $ref: '#/components/schemas/WorkflowV1EditorMetadata'
        integrations:
          description: 'Tools & integrations this agent may use on every step: connected apps (one entry per connected
            account, at most 8) and saved webhooks or call transfers (one entry per tool, at most 8). Each action names
            a binding in bindings; the save path offers every one of them on every conversation step. Manage them with
            /agents/{id}/integrations rather than by hand.'
          items:
            anyOf:
            - $ref: '#/components/schemas/WorkflowV1IntegrationGrant'
            - $ref: '#/components/schemas/WorkflowV1ToolGrant'
          maxItems: 16
          title: Integrations
          type: array
      required:
      - id
      - name
      - conversation
      title: WorkflowDefinition
      type: object
    WorkflowV1ActionNode:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        label:
          maxLength: 200
          minLength: 1
          title: Label
          type: string
        type:
          const: action
          title: Type
          type: string
        binding_id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Binding Id
          type: string
        hold_line:
          anyOf:
          - maxLength: 28
            minLength: 1
            type: string
          - type: 'null'
          default: null
          description: 'A short fixed sentence the caller hears while this step''s tool runs, such as "One moment please."
            It starts when the tool starts, in the agent''s voice, and the agent''s next words wait until it has been
            said. At most about 2.5 seconds of speech: up to 28 characters, about 25 in Hebrew or Arabic, fewer in Chinese,
            Japanese or Korean, and a digit counts as about three. Fixed text: no {{...}} references. Not on a transfer
            step, which has its own announcement.'
          title: Hold Line
      required:
      - id
      - label
      - type
      - binding_id
      title: ActionNode
      type: object
    WorkflowV1AfterTrigger:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        event:
          enum:
          - call.answered
          - call.ended
          - call.failed
          - call.no_answer
          - ai_session.ended
          - transfer.accepted
          - transfer.answered
          - transfer.failed
          - transcript.ready
          - analysis.ready
          - recording.ready
          - lead.ready
          - billing.ready
          - any_end
          - request.failed
          title: Event
          type: string
        steps:
          items:
            $ref: '#/components/schemas/WorkflowV1SequenceStep'
          maxItems: 256
          title: Steps
          type: array
        when:
          anyOf:
          - discriminator:
              mapping:
                all_of: '#/$defs/AllOf'
                any_of: '#/$defs/AnyOf'
                compare: '#/$defs/Comparison'
                not: '#/$defs/NotCondition'
              propertyName: kind
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1Comparison'
            - $ref: '#/components/schemas/WorkflowV1AllOf'
            - $ref: '#/components/schemas/WorkflowV1AnyOf'
            - $ref: '#/components/schemas/WorkflowV1NotCondition'
          - type: 'null'
          default: null
          description: 'Optional. An "Only if" on this follow-up: the steps run only when the condition holds for the
            call. Reads the call itself ({"kind": "call", "path": "/status"}) and fixed values, and only the facts this
            trigger''s event guarantees: how the call ended (result, who ended it, duration) on an ending, the disposition
            and collected fields on analysis.ready, direction and channel on any event. When it does not hold, every
            step is recorded as skipped (guard_false) and the follow-up counts as done.'
          title: When
      required:
      - id
      - event
      title: AfterTrigger
      type: object
    WorkflowV1AllOf:
      additionalProperties: false
      properties:
        kind:
          const: all_of
          title: Kind
          type: string
        conditions:
          items:
            discriminator:
              mapping:
                all_of: '#/$defs/AllOf'
                any_of: '#/$defs/AnyOf'
                compare: '#/$defs/Comparison'
                not: '#/$defs/NotCondition'
              propertyName: kind
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1Comparison'
            - $ref: '#/components/schemas/WorkflowV1AllOf'
            - $ref: '#/components/schemas/WorkflowV1AnyOf'
            - $ref: '#/components/schemas/WorkflowV1NotCondition'
          maxItems: 16
          minItems: 1
          title: Conditions
          type: array
      required:
      - kind
      - conditions
      title: AllOf
      type: object
    WorkflowV1AnyOf:
      additionalProperties: false
      properties:
        kind:
          const: any_of
          title: Kind
          type: string
        conditions:
          items:
            discriminator:
              mapping:
                all_of: '#/$defs/AllOf'
                any_of: '#/$defs/AnyOf'
                compare: '#/$defs/Comparison'
                not: '#/$defs/NotCondition'
              propertyName: kind
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1Comparison'
            - $ref: '#/components/schemas/WorkflowV1AllOf'
            - $ref: '#/components/schemas/WorkflowV1AnyOf'
            - $ref: '#/components/schemas/WorkflowV1NotCondition'
          maxItems: 16
          minItems: 1
          title: Conditions
          type: array
      required:
      - kind
      - conditions
      title: AnyOf
      type: object
    WorkflowV1ArtifactSource:
      additionalProperties: false
      properties:
        kind:
          const: artifact
          title: Kind
          type: string
        artifact:
          enum:
          - transcript
          - analysis
          - recording
          - lead
          - billing
          title: Artifact
          type: string
        path:
          pattern: ^(|/.*)$
          title: Path
          type: string
        fallback:
          anyOf:
          - $ref: '#/components/schemas/WorkflowV1Fallback'
          - type: 'null'
          default: null
      required:
      - kind
      - artifact
      - path
      title: ArtifactSource
      type: object
    WorkflowV1BeforePhase:
      additionalProperties: false
      properties:
        steps:
          items:
            $ref: '#/components/schemas/WorkflowV1SequenceStep'
          maxItems: 256
          title: Steps
          type: array
        on_failure:
          default: stop_admission
          enum:
          - stop_admission
          - continue_with_available
          title: On Failure
          type: string
      title: BeforePhase
      type: object
    WorkflowV1CallSource:
      additionalProperties: false
      description: 'A fact the platform recorded about the call itself, in the call package''s

        own names (`/status`, `/ended_by`, `/disposition/id`, ...).


        Read-only and only for a follow-up''s "Only if": a trigger filter may read

        the call facts its event guarantees (`trigger_filter.py`), and the

        publisher refuses it anywhere else.'
      properties:
        kind:
          const: call
          title: Kind
          type: string
        path:
          maxLength: 300
          pattern: ^/.+$
          title: Path
          type: string
      required:
      - kind
      - path
      title: CallSource
      type: object
    WorkflowV1Comparison:
      additionalProperties: false
      description: 'One declarative comparison. `value` is itself a source, so an absent

        right-hand side stays distinguishable from an explicit JSON null.'
      properties:
        kind:
          const: compare
          title: Kind
          type: string
        source:
          discriminator:
            mapping:
              call: '#/$defs/CallSource'
              literal: '#/$defs/LiteralSource'
              request: '#/$defs/ContextSource'
              sequence: '#/$defs/ContextSource'
              step: '#/$defs/StepSource'
              stored: '#/$defs/ContextSource'
            propertyName: kind
          oneOf:
          - $ref: '#/components/schemas/WorkflowV1LiteralSource'
          - $ref: '#/components/schemas/WorkflowV1ContextSource'
          - $ref: '#/components/schemas/WorkflowV1StepSource'
          - $ref: '#/components/schemas/WorkflowV1CallSource'
          title: Source
        op:
          enum:
          - exists
          - not_exists
          - eq
          - neq
          - gt
          - gte
          - lt
          - lte
          - contains
          - not_contains
          - in
          - not_in
          - is_true
          - is_false
          - is_empty
          - is_not_empty
          title: Op
          type: string
        value:
          anyOf:
          - discriminator:
              mapping:
                call: '#/$defs/CallSource'
                literal: '#/$defs/LiteralSource'
                request: '#/$defs/ContextSource'
                sequence: '#/$defs/ContextSource'
                step: '#/$defs/StepSource'
                stored: '#/$defs/ContextSource'
              propertyName: kind
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1LiteralSource'
            - $ref: '#/components/schemas/WorkflowV1ContextSource'
            - $ref: '#/components/schemas/WorkflowV1StepSource'
            - $ref: '#/components/schemas/WorkflowV1CallSource'
          - type: 'null'
          default: null
          title: Value
      required:
      - kind
      - source
      - op
      title: Comparison
      type: object
    WorkflowV1ContextSource:
      additionalProperties: false
      properties:
        kind:
          enum:
          - request
          - stored
          - sequence
          title: Kind
          type: string
        path:
          pattern: ^(|/.*)$
          title: Path
          type: string
        fallback:
          anyOf:
          - $ref: '#/components/schemas/WorkflowV1Fallback'
          - type: 'null'
          default: null
      required:
      - kind
      - path
      title: ContextSource
      type: object
    WorkflowV1ConversationEdge:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        source:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Source
          type: string
        target:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Target
          type: string
        kind:
          const: conversation
          title: Kind
          type: string
        condition:
          maxLength: 10000
          minLength: 1
          title: Condition
          type: string
      required:
      - id
      - source
      - target
      - kind
      - condition
      title: ConversationEdge
      type: object
    WorkflowV1ConversationGraph:
      additionalProperties: false
      properties:
        entry_node_id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Entry Node Id
          type: string
        nodes:
          items:
            discriminator:
              mapping:
                action: '#/$defs/ActionNode'
                conversation: '#/$defs/ConversationNode'
                end: '#/$defs/EndNode'
                sequence: '#/$defs/SequenceNode'
              propertyName: type
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1ConversationNode'
            - $ref: '#/components/schemas/WorkflowV1ActionNode'
            - $ref: '#/components/schemas/WorkflowV1SequenceNode'
            - $ref: '#/components/schemas/WorkflowV1EndNode'
          maxItems: 256
          minItems: 1
          title: Nodes
          type: array
        edges:
          items:
            discriminator:
              mapping:
                conversation: '#/$defs/ConversationEdge'
                result: '#/$defs/ResultEdge'
              propertyName: kind
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1ConversationEdge'
            - $ref: '#/components/schemas/WorkflowV1ResultEdge'
          maxItems: 1024
          title: Edges
          type: array
        global_edges:
          items:
            $ref: '#/components/schemas/WorkflowV1GlobalEdge'
          maxItems: 128
          title: Global Edges
          type: array
      required:
      - entry_node_id
      - nodes
      title: ConversationGraph
      type: object
    WorkflowV1ConversationNode:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        label:
          maxLength: 200
          minLength: 1
          title: Label
          type: string
        type:
          const: conversation
          title: Type
          type: string
        instructions:
          description: 'Prose may read a Before-call step''s output as {{before.<step_id>.<dotted.path>}}, optionally
            ending with |text used when the value is missing. The publisher validates the step and the path; the value
            is substituted once, at session start. {{option one|option two}} - two or more plain-text options separated
            by |, the first not starting with before. or call. - is a random variation: one option is said, picked once
            per call.'
          maxLength: 100000
          title: Instructions
          type: string
        available_binding_ids:
          items:
            pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
            type: string
          maxItems: 128
          title: Available Binding Ids
          type: array
        binding_overrides:
          anyOf:
          - additionalProperties:
              pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
              type: string
            propertyNames:
              pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
            type: object
          - type: 'null'
          default: null
          description: 'Optional. This step''s own settings for an action the whole agent has: maps the binding id an
            integration (or a tool for every step) owns to a binding of this document that runs the same tool with this
            step''s inputs.'
          title: Binding Overrides
      required:
      - id
      - label
      - type
      - instructions
      title: ConversationNode
      type: object
    WorkflowV1EditorMetadata:
      additionalProperties: false
      properties:
        positions:
          additionalProperties:
            $ref: '#/components/schemas/WorkflowV1Position'
          title: Positions
          type: object
      title: EditorMetadata
      type: object
    WorkflowV1EndNode:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        label:
          maxLength: 200
          minLength: 1
          title: Label
          type: string
        type:
          const: end
          title: Type
          type: string
      required:
      - id
      - label
      - type
      title: EndNode
      type: object
    WorkflowV1ExtractSource:
      additionalProperties: false
      properties:
        kind:
          const: extract
          title: Kind
          type: string
        instruction:
          description: 'A value the finished call is asked for by description, such as "the time slot the caller agreed
            to". Only on an After-call step. `type` is worked out from the tool input when left out. When the call does
            not say it: `fallback` is used, else `on_missing` decides - "skip" skips the step (the default for a required
            input), "fail" fails it. `fallback` and `on_missing` are not written together. Never sent as a guess.'
          maxLength: 500
          minLength: 1
          title: Instruction
          type: string
        type:
          anyOf:
          - enum:
            - text
            - number
            - yes_no
            - date
            - datetime
            type: string
          - type: 'null'
          default: null
          title: Type
        on_missing:
          anyOf:
          - enum:
            - skip
            - fail
            type: string
          - type: 'null'
          default: null
          title: On Missing
        fallback:
          anyOf:
          - $ref: '#/components/schemas/WorkflowV1Fallback'
          - type: 'null'
          default: null
      required:
      - kind
      - instruction
      title: ExtractSource
      type: object
    WorkflowV1Fallback:
      additionalProperties: false
      properties:
        value:
          $ref: '#/components/schemas/WorkflowV1JsonValue'
      required:
      - value
      title: Fallback
      type: object
    WorkflowV1GlobalEdge:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        target:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Target
          type: string
        condition:
          maxLength: 10000
          minLength: 1
          title: Condition
          type: string
      required:
      - id
      - target
      - condition
      title: GlobalEdge
      type: object
    WorkflowV1IntegrationAction:
      additionalProperties: false
      properties:
        action:
          pattern: ^[A-Z0-9_]{1,200}$
          title: Action
          type: string
        binding_id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Binding Id
          type: string
      required:
      - action
      - binding_id
      title: IntegrationAction
      type: object
    WorkflowV1IntegrationGrant:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        connection_id:
          pattern: ^[a-f0-9-]{36}$
          title: Connection Id
          type: string
        app:
          pattern: ^[a-z0-9_]{1,100}$
          title: App
          type: string
        actions:
          items:
            $ref: '#/components/schemas/WorkflowV1IntegrationAction'
          maxItems: 24
          minItems: 1
          title: Actions
          type: array
      required:
      - id
      - connection_id
      - app
      - actions
      title: IntegrationGrant
      type: object
    WorkflowV1JsonValue:
      anyOf:
      - type: 'null'
      - type: boolean
      - type: number
      - type: string
      - type: array
        items:
          $ref: '#/components/schemas/WorkflowV1JsonValue'
      - type: object
        additionalProperties:
          $ref: '#/components/schemas/WorkflowV1JsonValue'
    WorkflowV1LiteralSource:
      additionalProperties: false
      properties:
        kind:
          const: literal
          title: Kind
          type: string
        value:
          $ref: '#/components/schemas/WorkflowV1JsonValue'
      required:
      - kind
      - value
      title: LiteralSource
      type: object
    WorkflowV1ModelOption:
      additionalProperties: false
      properties:
        value:
          maxLength: 500
          minLength: 1
          title: Value
          type: string
        label:
          maxLength: 120
          minLength: 1
          title: Label
          type: string
      required:
      - value
      - label
      title: ModelOption
      type: object
    WorkflowV1ModelSource:
      additionalProperties: false
      properties:
        kind:
          const: model
          title: Kind
          type: string
        path:
          pattern: ^/[^/]+$
          title: Path
          type: string
        options:
          anyOf:
          - items:
              $ref: '#/components/schemas/WorkflowV1ModelOption'
            maxItems: 20
            minItems: 1
            type: array
          - type: 'null'
          default: null
          description: Optional. The values the agent may choose from for this input, each with the label it reads.
            Only on a During-call binding; string values only.
          title: Options
      required:
      - kind
      - path
      title: ModelSource
      type: object
    WorkflowV1NotCondition:
      additionalProperties: false
      properties:
        kind:
          const: not
          title: Kind
          type: string
        condition:
          discriminator:
            mapping:
              all_of: '#/$defs/AllOf'
              any_of: '#/$defs/AnyOf'
              compare: '#/$defs/Comparison'
              not: '#/$defs/NotCondition'
            propertyName: kind
          oneOf:
          - $ref: '#/components/schemas/WorkflowV1Comparison'
          - $ref: '#/components/schemas/WorkflowV1AllOf'
          - $ref: '#/components/schemas/WorkflowV1AnyOf'
          - $ref: '#/components/schemas/WorkflowV1NotCondition'
          title: Condition
      required:
      - kind
      - condition
      title: NotCondition
      type: object
    WorkflowV1Position:
      additionalProperties: false
      properties:
        x:
          title: X
          type: number
        y:
          title: Y
          type: number
      required:
      - x
      - y
      title: Position
      type: object
    WorkflowV1ResultEdge:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        source:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Source
          type: string
        target:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Target
          type: string
        kind:
          const: result
          title: Kind
          type: string
        outcome:
          enum:
          - succeeded
          - failed
          title: Outcome
          type: string
        when:
          anyOf:
          - discriminator:
              mapping:
                all_of: '#/$defs/AllOf'
                any_of: '#/$defs/AnyOf'
                compare: '#/$defs/Comparison'
                not: '#/$defs/NotCondition'
              propertyName: kind
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1Comparison'
            - $ref: '#/components/schemas/WorkflowV1AllOf'
            - $ref: '#/components/schemas/WorkflowV1AnyOf'
            - $ref: '#/components/schemas/WorkflowV1NotCondition'
          - type: 'null'
          default: null
          description: 'Optional, and only on a `succeeded` route in Strict mode. The route is taken only when this
            condition holds for what the step''s tool answered: it reads fixed values and that step''s own answer ({"kind":
            "step", "scope": "during", "step_id": <this edge''s source>, "path": "/status"}). A step''s guarded routes
            are tried in the order they are written; the one `succeeded` route with no condition is taken when none
            of them holds, so a step that has guarded routes must have exactly one. A `failed` route never has a condition.'
          title: When
      required:
      - id
      - source
      - target
      - kind
      - outcome
      title: ResultEdge
      type: object
    WorkflowV1SequenceNode:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        label:
          maxLength: 200
          minLength: 1
          title: Label
          type: string
        type:
          const: sequence
          title: Type
          type: string
        sequence_id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Sequence Id
          type: string
      required:
      - id
      - label
      - type
      - sequence_id
      title: SequenceNode
      type: object
    WorkflowV1SequenceStep:
      additionalProperties: false
      description: 'A step that may carry a guard and route its outcome.


        Sequence children use all three members. Before and After steps are the same

        shape so that a before-call step can route to `#decline`, and the publisher

        refuses every other use of them outside a sequence with its own code — the

        model is wide enough to state the mistake, not wide enough to run it. The

        serializer drops the three members whenever they hold their v1 default, so a

        step that declares no branching compiles and hashes to exactly the bytes it

        did before they existed.'
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        label:
          maxLength: 200
          minLength: 1
          title: Label
          type: string
        binding_id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Binding Id
          type: string
        depends_on:
          items:
            pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
            type: string
          maxItems: 256
          title: Depends On
          type: array
        requires:
          items:
            enum:
            - transcript
            - analysis
            - recording
            - lead
            - billing
            type: string
          title: Requires
          type: array
        on_failure:
          default: stop
          enum:
          - stop
          - continue
          title: On Failure
          type: string
        when:
          anyOf:
          - discriminator:
              mapping:
                all_of: '#/$defs/AllOf'
                any_of: '#/$defs/AnyOf'
                compare: '#/$defs/Comparison'
                not: '#/$defs/NotCondition'
              propertyName: kind
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1Comparison'
            - $ref: '#/components/schemas/WorkflowV1AllOf'
            - $ref: '#/components/schemas/WorkflowV1AnyOf'
            - $ref: '#/components/schemas/WorkflowV1NotCondition'
          - type: 'null'
          default: null
          title: When
        on_succeeded:
          anyOf:
          - pattern: ^(#end|#decline|[A-Za-z0-9][A-Za-z0-9_-]{0,63})$
            type: string
          - type: 'null'
          default: null
          title: On Succeeded
        on_failed:
          anyOf:
          - pattern: ^(#end|#decline|[A-Za-z0-9][A-Za-z0-9_-]{0,63})$
            type: string
          - type: 'null'
          default: null
          title: On Failed
      required:
      - id
      - label
      - binding_id
      title: SequenceStep
      type: object
    WorkflowV1StepSource:
      additionalProperties: false
      properties:
        kind:
          const: step
          title: Kind
          type: string
        scope:
          default: local
          enum:
          - local
          - before
          - during
          title: Scope
          type: string
        step_id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Step Id
          type: string
        path:
          pattern: ^(|/.*)$
          title: Path
          type: string
        fallback:
          anyOf:
          - $ref: '#/components/schemas/WorkflowV1Fallback'
          - type: 'null'
          default: null
      required:
      - kind
      - step_id
      - path
      title: StepSource
      type: object
    WorkflowV1ToolBinding:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        tool_revision_id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Tool Revision Id
          type: string
        tool_revision_policy:
          default: follow_current
          enum:
          - follow_current
          - pinned
          title: Tool Revision Policy
          type: string
        inputs:
          additionalProperties:
            discriminator:
              mapping:
                artifact: '#/$defs/ArtifactSource'
                extract: '#/$defs/ExtractSource'
                literal: '#/$defs/LiteralSource'
                model: '#/$defs/ModelSource'
                request: '#/$defs/ContextSource'
                sequence: '#/$defs/ContextSource'
                step: '#/$defs/StepSource'
                stored: '#/$defs/ContextSource'
              propertyName: kind
            oneOf:
            - $ref: '#/components/schemas/WorkflowV1LiteralSource'
            - $ref: '#/components/schemas/WorkflowV1ModelSource'
            - $ref: '#/components/schemas/WorkflowV1ContextSource'
            - $ref: '#/components/schemas/WorkflowV1StepSource'
            - $ref: '#/components/schemas/WorkflowV1ArtifactSource'
            - $ref: '#/components/schemas/WorkflowV1ExtractSource'
          title: Inputs
          type: object
      required:
      - id
      - tool_revision_id
      title: ToolBinding
      type: object
    WorkflowV1ToolGrant:
      additionalProperties: false
      description: 'A saved webhook or call transfer the agent may use on every conversation step.


        Lives in the same `integrations` list as the app grants (the two shapes

        share no member, so the list stays unambiguous). `binding_id` names one

        binding in `bindings` that runs `tool_id`; the save path offers it on every

        conversation step, as it does an app grant''s actions.'
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        tool_id:
          pattern: ^[a-f0-9-]{36}$
          title: Tool Id
          type: string
        binding_id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Binding Id
          type: string
      required:
      - id
      - tool_id
      - binding_id
      title: ToolGrant
      type: object
    WorkflowV1ToolSequence:
      additionalProperties: false
      properties:
        id:
          pattern: ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$
          title: Id
          type: string
        name:
          maxLength: 200
          minLength: 1
          title: Name
          type: string
        description:
          default: ''
          maxLength: 10000
          title: Description
          type: string
        input_schema:
          additionalProperties:
            $ref: '#/components/schemas/WorkflowV1JsonValue'
          title: Input Schema
          type: object
        output_schema:
          additionalProperties:
            $ref: '#/components/schemas/WorkflowV1JsonValue'
          title: Output Schema
          type: object
        output_mapping:
          additionalProperties:
            $ref: '#/components/schemas/WorkflowV1StepSource'
          title: Output Mapping
          type: object
        steps:
          items:
            $ref: '#/components/schemas/WorkflowV1SequenceStep'
          maxItems: 128
          minItems: 1
          title: Steps
          type: array
      required:
      - id
      - name
      - steps
      title: ToolSequence
      type: object
    WorkflowRevisionSummary:
      type: object
      required: [id, version, content_hash, published_at]
      properties:
        id: { type: string, format: uuid }
        version: { type: integer, minimum: 1 }
        content_hash: { type: string, pattern: '^[a-f0-9]{64}$' }
        published_at: { type: string, format: date-time }
        environment:
          type: string
          enum: [local, testing, production]
          readOnly: true
          description: >
            The deployment plane that compiled and stored this revision. Decided by the
            deployment, never sent by the caller; the hosted API stores as production. A call
            loads only a version stored on the plane it runs on, and publishing and calling
            through the same API are the same plane. See the List workflow versions page.
    WorkflowVersionProvenance:
      type: object
      properties:
        source:
          type: [string, 'null']
          enum: [teach, restore, null]
          description: How the version came to be. `teach` - published by Teach from a test call; `restore` - published by a restore (including an undo of a Teach run); null - published by a person from the editor or the API.
        source_run_id: { type: [string, 'null'], format: uuid, description: The Teach run that published this version. Null unless source is teach. }
        restored_from_version: { type: [integer, 'null'], minimum: 1, description: The version number this one is a copy of. Null unless source is restore. }
    WorkflowVersionDetail:
      allOf:
        - $ref: '#/components/schemas/WorkflowRevisionSummary'
        - $ref: '#/components/schemas/WorkflowVersionProvenance'
        - type: object
          required: [document, is_current]
          properties:
            draft_version: { type: integer, minimum: 1 }
            compiler_version: { type: string }
            document: { $ref: '#/components/schemas/WorkflowDocument' }
            is_current: { type: boolean, description: True when callers reach this version now. }
    WorkflowRestoreRequest:
      type: object
      additionalProperties: false
      description: Name the version with exactly one of version_id and version.
      properties:
        version_id: { type: string, format: uuid, description: "The id of the version to restore, from GET /agents/{id}/workflow/versions." }
        version: { type: integer, minimum: 1, description: The number of the version to restore. }
        expected_version: { type: integer, minimum: 1, maximum: 9007199254740991, description: "The saved draft's version you last read. Refused with 409 WORKFLOW_CONFLICT when the draft has moved since. Optional." }
        discard_draft: { type: boolean, default: false, description: "True replaces a saved draft that holds unpublished changes with the restored workflow. False (default) refuses with 409 WORKFLOW_DRAFT_HAS_UNPUBLISHED_CHANGES instead of losing them." }
    WorkflowRestoreResponse:
      type: object
      required: [revision, execution_version, restored_from, draft_version, discarded_draft]
      properties:
        revision: { $ref: '#/components/schemas/WorkflowRevisionSummary' }
        execution_version: { const: workflow_v1, readOnly: true }
        restored_from:
          type: object
          required: [id, version]
          properties:
            id: { type: string, format: uuid }
            version: { type: integer, minimum: 1 }
        draft_version: { type: integer, minimum: 1, description: The saved draft's version after the restore. }
        discarded_draft: { type: boolean, description: True when unpublished draft changes were replaced. }
        settings_updated_at: { type: string, format: date-time, readOnly: true, description: "The agent settings token as of this restore, as POST /agents/{id}/workflow/publish answers it. Send it as expected_updated_at on your next PATCH /agents/{id}." }
    WorkflowTrainRequest:
      type: object
      additionalProperties: false
      required: [call_id]
      properties:
        call_id: { type: string, format: uuid, description: "The finished web test call to teach from, the call's id." }
        retry: { type: boolean, default: false, description: "True starts a run that ended held or failed again (up to 5 times per run)." }
    WorkflowTrainChange:
      type: object
      required: [op_index, op, target, target_label, before, after, directive, evidence]
      properties:
        op_index: { type: integer, minimum: 0 }
        op: { type: string, enum: [add, remove, replace, edit, move] }
        target:
          type: object
          description: 'Where the change is: {"kind":"global"} for the global instructions, or {"kind":"node","node_id":"..."} for one conversation step.'
          required: [kind]
          properties:
            kind: { type: string, enum: [global, node] }
            node_id: { type: string }
        target_label: { type: string, description: The step's label, or "Global instructions". }
        title: { type: [string, 'null'], description: The heading of the section changed, when it has one. }
        before: { type: [string, 'null'], description: The section as it read before. Null for an addition. }
        after: { type: [string, 'null'], description: The section as it reads now. Null for a removal. }
        directive: { type: string, description: What the person asked for, in one sentence. }
        evidence:
          type: array
          description: Words the person said on the call that this change rests on.
          items:
            type: object
            required: [turn, quote]
            properties:
              turn: { type: integer, minimum: 0 }
              quote: { type: string }
        sensitive:
          type: array
          description: Present when the change touches a prohibition, a number, a link or phone number, or the text about a tool; such a change is applied only after a second check.
          items: { type: string, enum: [prohibition_removed, number_changed, url_or_phone_changed, tool_text_changed] }
    WorkflowTrainRun:
      type: object
      required: [id, call_id, agent_id, status, reasons, can_undo, can_retry, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        call_id: { type: string, format: uuid }
        agent_id: { type: string, format: uuid }
        status:
          type: string
          enum: [claimed, waiting_transcript, running, put_done, applied, no_change, held, failed, reverted]
          description: >
            `claimed`, `waiting_transcript`, `running` and `put_done` are in progress (poll again).
            `applied` - the new instructions are live. `no_change` - nothing to change (see reason).
            `held` - refused on purpose, nothing live changed (see reason). `failed` - something
            went wrong; retry may help. `reverted` - the change was undone.
        step: { type: [string, 'null'], enum: [gates, wait_transcript, llm, validate, entail, put, publish, rollback, undo, done, null] }
        attempt: { type: integer }
        reason:
          type: [string, 'null']
          description: The first reason a run ended without a change, or null. The full list is in reasons.
          enum:
            - no_instruction
            - roleplay_only
            - ambiguous
            - too_short
            - out_of_scope
            - call_too_short
            - call_not_completed
            - transcript_unreliable
            - transcript_empty
            - draft_has_unpublished_changes
            - stale_base
            - conflict
            - validation_failed
            - limits_exceeded
            - tool_reference_lost
            - token_mismatch
            - evidence_unverified
            - needs_confirmation
            - publish_refused
            - rollback_skipped_draft_changed
            - teach_disabled
            - transcript_timeout
            - model_unavailable
            - model_output_unreadable
            - model_truncated
            - publish_unavailable
            - abandoned
            - internal_error
            - null
        reasons:
          type: array
          items:
            type: object
            required: [code]
            properties:
              code: { type: string }
              op_index: { type: integer }
              detail: { type: string }
        summary: { type: [string, 'null'], description: One sentence on what changed, or null when none could be written (read changes). }
        changes:
          type: [array, 'null']
          items: { $ref: '#/components/schemas/WorkflowTrainChange' }
        base_revision:
          type: [object, 'null']
          description: The version that was live before the run. Restore it to undo the run.
          properties: { id: { type: string, format: uuid }, version: { type: integer } }
        result_revision:
          type: [object, 'null']
          description: The version the run published. Null unless applied.
          properties: { id: { type: string, format: uuid }, version: { type: integer } }
        can_undo: { type: boolean, description: True while the run's version is still the live one and the draft has not moved. }
        can_retry: { type: boolean, description: True for a held or failed run the caller may retry (the person who requested it, with retries left). }
        retry_after_ms: { type: [integer, 'null'], description: While the run is in progress, when to ask again. }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        finished_at: { type: [string, 'null'], format: date-time }
    WorkflowTrainResponse:
      type: object
      required: [run]
      properties:
        run: { oneOf: [{ type: 'null' }, { $ref: '#/components/schemas/WorkflowTrainRun' }] }
        wait: { type: string, const: call_running, description: "Present with run null while the call has not ended; ask again after retry_after_ms." }
        retry_after_ms: { type: integer }
    TeachError:
      allOf:
        - $ref: '#/components/schemas/Error'
        - type: object
          properties:
            reason: { type: string, description: A finer reason beside code, when there is one. }
            retry_after_ms: { type: integer }
    WorkflowState:
      type: object
      required: [agent_id, execution_version, draft, published]
      properties:
        agent_id: { type: string, format: uuid }
        execution_version: { type: string, enum: [legacy, workflow_v1], readOnly: true }
        draft:
          oneOf:
            - type: 'null'
            - type: object
              required: [version, document, updated_at]
              properties:
                version: { type: integer, minimum: 1 }
                document: { $ref: '#/components/schemas/WorkflowDocument' }
                updated_at: { type: string, format: date-time }
        published:
          oneOf:
            - type: 'null'
            - $ref: '#/components/schemas/WorkflowRevisionSummary'
    WorkflowExpectedVersion:
      type: object
      additionalProperties: false
      required: [expected_version]
      properties:
        expected_version: { type: integer, minimum: 1, maximum: 9007199254740991 }
    WorkflowSave:
      type: object
      additionalProperties: false
      required: [expected_version, document]
      properties:
        expected_version:
          type: [integer, 'null']
          minimum: 1
          maximum: 9007199254740991
          description: Exact saved draft version. Null is accepted only when no draft exists; New Agent already creates version1.
        document: { $ref: '#/components/schemas/WorkflowDocument' }
    WorkflowValidation:
      type: object
      required: [valid, issues, warnings]
      properties:
        valid:
          type: boolean
          description: >
            True on the 200. A draft with issues answers 422 WORKFLOW_VALIDATION_FAILED instead,
            exactly as publish does - including binding_phase_unsupported and the
            extracted_field_* refusals, which are raised beside the compiler rather than by it
            and used to arrive as valid false on a 200. That 422 carries valid false too, and
            the same warnings[] a passing Check carries.
        content_hash:
          type: string
          pattern: '^[a-f0-9]{64}$'
          description: The compiled artifact's hash. Present only when valid is true.
        issues:
          type: array
          maxItems: 100
          description: >
            Empty when valid is true. Otherwise the refusals, in the same shape publish sends
            them in, so one renderer serves both.
          items:
            type: object
            required: [code, path, message]
            properties:
              code: { type: string, maxLength: 100 }
              path: { type: string, maxLength: 1000 }
              message: { type: string, maxLength: 2000 }
              node_id:
                type: string
                maxLength: 64
                description: Present when the refusal belongs to one step; that step's id.
              label:
                type: string
                maxLength: 200
                description: >
                  That step's label, as the workflow document spells it - on every code. Present
                  only with node_id. The tool a binding issue is about is tool_name.
              tool_name:
                type: string
                maxLength: 200
                description: On an issue about a binding, the name of the tool it runs. `label` is never the tool's name.
              field:
                type: string
                maxLength: 200
                description: On an issue about one input of a binding (`/bindings/{n}/inputs/{field}`), that input's name.
        warnings:
          type: array
          items:
            type: object
            additionalProperties: false
            required: [code, message]
            properties:
              message: { type: string, description: 'What the advisory means and what to change, in words. The dashboard writes its own copy from code.' }
              code: { type: string, enum: [strict_off_guidance, during_output_advisory, sequence_branch_advisory, before_reference_missing_fallback, override_needs_strict, after_ending_coverage, after_any_end_waits, before_budget_inbound, workflow_warning, binding_channel_unsupported, binding_phase_unsupported, stored_context_has_no_writer, input_constant_placeholder, missing_request_field, tool_values_missing] }
              header_names: { type: array, items: { type: string }, description: 'With tool_values_missing - the bound tool''s headers whose value is empty. Names only.' }
              query_names: { type: array, items: { type: string }, description: 'With tool_values_missing - the query parameters on its URL written name= with no value. Names only.' }
              path:
                type: string
                maxLength: 1000
                description: >
                  Pointer to the binding an advisory is about. Sent with
                  binding_channel_unsupported and tool_values_missing, each raised once per binding; absent on
                  every compiler advisory. stored_context_has_no_writer,
                  input_constant_placeholder and missing_request_field (an optional input reading a
                  request path request_schema does not declare) point one level deeper, at the
                  input itself (/bindings/{n}/inputs/{field}, RFC 6901 escaped).
              label:
                type: string
                maxLength: 200
                description: The label of the step that uses that binding, as on an issue. Present only with node_id.
              tool_name:
                type: string
                maxLength: 200
                description: The name of the tool that binding runs. Present with `path`.
              field:
                type: string
                maxLength: 200
                description: On stored_context_has_no_writer, input_constant_placeholder and missing_request_field, the input's name.
              node_id:
                type: string
                maxLength: 64
                description: >
                  On an advisory with `path`, the id of the step that uses the binding - for
                  binding_channel_unsupported, the step a caller on the unsupported channel
                  reaches and gets nothing from - so an editor can open it. Absent when no step
                  uses the binding.
    WorkflowError:
      allOf:
        - { $ref: "#/components/schemas/Error" }
        - type: object
          required: [code]
          properties:
            error: { type: string }
            code: { type: string }
            warnings:
              type: array
              description: >
                On WORKFLOW_VALIDATION_FAILED from Check or publish, the advisories beside the issues, in
                the shape of WorkflowValidation's warnings - strict_off_guidance when strict_mode is off,
                and every advisory about a binding or an input. The compiler's own graph advisories
                (during_output_advisory, sequence_branch_advisory, before_reference_missing_fallback, override_needs_strict,
                after_ending_coverage, after_any_end_waits, before_budget_inbound)
                arrive once the document compiles.
              items:
                type: object
                required: [code, message]
                properties:
                  code: { type: string }
                  message: { type: string }
                  path: { type: string, maxLength: 1000 }
                  node_id: { type: string, maxLength: 64 }
                  label: { type: string, maxLength: 200, description: The step's label. Present only with node_id. }
                  tool_name: { type: string, maxLength: 200 }
                  field: { type: string, maxLength: 200 }
            issues:
              type: array
              maxItems: 100
              items:
                type: object
                required: [code, path, message]
                properties:
                  code: { type: string, maxLength: 100 }
                  path: { type: string, maxLength: 1000 }
                  message: { type: string, maxLength: 2000 }
                  node_id:
                    type: string
                    maxLength: 64
                    description: The step the issue belongs to - a conversation step, a before-call step, a follow-up or a step inside a sequence, by its `id`. An issue about a binding names the first step that runs or offers it; absent only when no single step is concerned (a binding no step uses, a schema).
                  label:
                    type: string
                    maxLength: 200
                    description: That step's label, as the workflow document spells it - on every code. Present only with `node_id`.
                  tool_name:
                    type: string
                    maxLength: 200
                    description: On an issue about a binding, the name of the tool it runs. `label` is never the tool's name.
                  field:
                    type: string
                    maxLength: 200
                    description: On an issue about one input of a binding (`/bindings/{n}/inputs/{field}`), that input's name.
    WorkflowCatalogRevision:
      type: object
      required: [id, tool_id, revision, name, description, kind, input_schema, output_schema, allowed_phases, allowed_channels, is_current, available]
      properties:
        id: { type: string, format: uuid }
        tool_id: { type: string, format: uuid }
        revision: { type: integer, minimum: 1 }
        name: { type: string }
        description: { type: string }
        kind: { type: string, enum: [http, app, transfer] }
        input_schema: { type: object, additionalProperties: true }
        output_schema: { type: object, additionalProperties: true }
        allowed_phases: { type: array, items: { type: string, enum: [before, during, after] } }
        allowed_channels: { type: array, items: { type: string, enum: [phone, web] } }
        is_current: { type: boolean }
        available: { type: boolean }
        archived:
          type: boolean
          description: On a revision with `available` false only. True when its tool is archived (restore it with POST /tools/{id}/restore); false when the tool is not archived and an app tool's connected account is what is no longer usable. Absent when it could not be read.
        connection:
          type: object
          required: [id, label, ready]
          properties:
            id: { type: string, format: uuid }
            label: { type: string }
            ready: { type: boolean }
    Agent:
      type: object
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        execution_version:
          type: string
          enum: [legacy, workflow_v1]
          readOnly: true
          description: Authoring ownership assigned by Yappr. workflow_v1 can be an unpublished draft; this field does not prove call readiness.
        published_workflow_revision_id:
          type: string
          format: uuid
          nullable: true
          readOnly: true
          description: Null until explicit workflow publication. Cannot be set by agent create or PATCH.
        live:
          type: boolean
          readOnly: true
          description: >
            On GET /agents and GET /agents/{id}: whether callers reach this agent right now. A
            workflow_v1 agent is live when it is active and a version of its workflow is
            published; a saved draft that was never published is not live. A legacy agent
            (type prompt or flow) has nothing to publish and is live whenever it is active, with
            published_workflow_revision_id null. A deactivated agent is never live. For a
            workflow_v1 agent the dashboard's "Live · version N" badge is the same fact; N is
            published.version on GET /agents/{id}/workflow.
        inbound:
          type: object
          readOnly: true
          description: >
            On GET /agents and GET /agents/{id}: what routes inbound calls to this agent - active
            phone numbers that answer with it (as the number's agent or the other half of its A/B
            split) and active SIP endpoints. Empty lists mean no inbound route reaches it; the
            member is absent when the routes could not be read. A key reads each route as its
            scopes allow: without `phone_numbers:search` a number's `number` and `friendly_name`
            are null, and without `sip_endpoints:read` an endpoint's `name` is null.
          properties:
            phone_numbers:
              type: array
              items:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  number: { type: string, nullable: true, example: "+972501234567" }
                  friendly_name: { type: string, nullable: true }
            sip_endpoints:
              type: array
              items:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  name: { type: string, nullable: true }
        type:
          type: string
          enum: [workflow, prompt, flow]
          description: >
            `workflow` on every agent with `execution_version: workflow_v1` — the only kind that
            can be created. Such an agent also **omits** `system_prompt`, `flow_config`,
            `webhook_url`, `webhook_events`, `webhook_headers` and `tools`: it has no such
            things, and returning them as nulls read as the retired kind. Its instructions,
            graph and tool bindings are its workflow document — `GET /agents/{id}/workflow`.

            `prompt` and `flow` appear only on agents created before the workflow engine, which
            keep their old response shape unchanged. `prompt` (legacy): a single `system_prompt`
            drives the call; the LLM decides when to call attached tools. `flow`: the call is
            driven by a `flow_config` graph. `type` is **immutable** post-create.
        flow_config:
          oneOf:
            - $ref: "#/components/schemas/FlowConfig"
            - type: "null"
          description: >
            Legacy agents only, and absent from a `workflow` agent's response. The flow graph.
            Required when `type='flow'`, must be omitted/null when `type='prompt'`.
        system_prompt: { type: string, nullable: true, description: "Legacy agents only, and absent from a `workflow` agent's response — read its workflow document instead. {{VariableName}} is filled in from the call's variables. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations)." }
        description: { type: string, nullable: true }
        voice:
          type: string
          enum: [Michal, Yonatan, David, Rachel, Gil, Noa, Maya, Adam, Shira, Avigail, Amir, Liat, Omer,
                 Tamar, Tom, Benny, Nir, Natan, Yael, Dvora, Yosef, Shir, Anat, Ariel, Roi, Shlomo, Dana, Alon, Ruth, Yuval,
                 Keren, Eitan, Hila, Ido, Boaz, Tali, Erez, Efrat]
          description: >
            The persona the agent speaks in. A voice belongs to one of Yappr's two voice families,
            so naming a voice on its own still chooses the family — and with it the model family
            (`model` below) — and no existing client has to change. There is no separate engine
            field, and `engine` / `engine_voice` are rejected if you send them.

            `Keren, Eitan, Hila, Ido, Boaz, Tali, Erez, Efrat` are the voices of `gpt-live`, available
            to every workspace. Agents on these voices handle their own turn-taking and
            expressiveness, so `temperature`, `vad_stop_secs`, `vad_start_secs` and
            `vad_confidence` are rejected on them, and they cannot be used on a `type='flow'`
            agent. The other thirty are the voices of both Gemini models. Any other name returns
            `400` listing every voice you may use.

            Always the name the agent actually speaks in, whichever family it is on.
        model:
          type: string
          nullable: true
          enum: [gemini-3.1-flash-live, gemini-3.8-live, gpt-live]
          description: >
            The voice model the agent runs on, as you chose it; null means **automatic**, where Yappr
            picks by the agent's language (see `resolved_model`). See the models page for what each
            model is and how to choose.

            A `gpt-live` agent always reads `gpt-live`: GPT Live is chosen through its voices, never
            automatically.
        resolved_model:
          type: string
          readOnly: true
          enum: [gemini-3.1-flash-live, gemini-3.8-live, gpt-live]
          description: >
            The model the agent's calls run on: `model` when it is set, and otherwise what automatic
            chooses today for the agent's language (Hebrew and multilingual run `gemini-3.1-flash-live`,
            every other language `gemini-3.8-live`). Read-only, and it can change for an automatic agent when
            Yappr moves a language to a better model; a pinned `model` never moves.
        background_sound:
          type: string
          nullable: true
          enum: [call_center, open_office, cafe, outdoor]
          description: Ambient background sound mixed under the agent's voice during calls. Null means silent (default).
        background_sound_volume:
          type: number
          minimum: 0.0
          maximum: 0.6
          default: 0.3
          description: Volume of the background sound, 0.0–0.6. Capped to protect turn-taking.
        language:
          type: string
          enum: [he, en, ar, ru, fr, es, de, it, pt, nl, tr, pl, uk, hi, ja, ko, zh, multi]
          description: >
            The language the agent speaks and listens for on calls, as its short code, or `multi`
            for a multilingual agent that answers in the caller's language and switches when they
            do. Each language gets its own speaking rules (politeness, gender, how numbers, dates
            and prices are said). See the Languages page.
        temperature: { type: number, minimum: 0, maximum: 2, description: "How varied the agent's wording is. On the Gemini voices a value below 0.3 is stored and returned as you sent it, and the agent speaks as if it were 0.3: lower values sometimes made a call open on a word or two and a pause. The expressive voices do not take it." }
        greeting_message: { type: string, nullable: true, description: "The line the agent opens the call with when agent_speaks_first is true, said word for word in the agent's language (a second-family voice can still word it slightly differently). On the standard voices a caller's brief hello in the first few seconds of the line does not interrupt it; a caller who keeps talking over it does. {{FirstName}} is filled in from the call's variables or the lead's name, or left out with the space before it when there is none. Send null to clear it and let the agent open in its own words. Editable here and on PATCH /agents/{id}; on a flow agent the start node's own opening overrides it. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations). On a workflow agent it may read a Before-call step's result, {{before.<step_id>.<field>|<fallback>}}, said word for word: the value, else the fallback, else the rest of the line; Check and Publish refuse a step the workflow does not have. See [Opening line from a Before step](/api-reference/workflows/greeting-from-before)." }
        agent_speaks_first: { type: boolean }
        vad_stop_secs:
          type: number
          minimum: 0.05
          maximum: 5.0
          default: 0.5
          description: >
            Seconds of silence that end the caller's turn. Lower answers sooner and cuts a caller
            who pauses mid-thought; higher waits longer before replying. Below 0.5 s the agent may
            start answering half a sentence.
        vad_start_secs:
          type: number
          minimum: 0.05
          maximum: 2.0
          default: 0.2
          description: >
            Seconds of speech that count as the caller starting to talk. It also sets how much of
            the moment before that is kept, so an interruption does not lose the caller's first
            word.
        vad_confidence:
          type: number
          minimum: 0.0
          maximum: 1.0
          default: 0.7
          description: >
            How sure the agent must be that it is hearing speech. Below the 0.7 default the agent
            reacts more eagerly — useful for quiet callers, and more likely to react to background
            noise on a noisy line. Two things read it, and they read it differently. How readily
            the caller can cut the agent off mid-sentence follows the number continuously, so any
            change moves it. Where the caller's turn begins and ends is a two-position switch
            either side of the 0.7 default: at or above it the agent is deliberate about deciding
            the caller has started or stopped, below it eager. For that half, 0.05 and 0.69 behave
            identically, and so do 0.70 and 1.00 — tune it by moving across the default, not by
            nudging it.
        silence_timeout_secs: { type: number, minimum: 10, maximum: 900, default: 60, description: "Seconds of caller silence before auto-hangup. Prevents idle calls wasting credits." }
        idle_reminder_count:
          type: integer
          minimum: 0
          maximum: 3
          default: 0
          description: >
            How many times the agent asks a silent caller whether they are still there before
            `silence_timeout_secs` hangs up. Each reminder is said when the silence timeout runs out,
            and the timer starts again after it; the caller speaking resets the count. 0 (the default)
            hangs up at the first timeout without asking. See
            [Idle reminders](/api-reference/agents/idle-reminders).
        idle_reminder_text:
          type: string
          nullable: true
          maxLength: 200
          description: >
            What the agent says as each reminder, word for word. Null (the default) is a short line in
            the call's language ("Hello, are you still there?" in English); for a language without a
            fixed line, the agent asks in its own words in the call's language. A blank string is stored
            as null.
        max_continuous_speech_secs: { type: number, minimum: 0, maximum: 300, default: 120, description: "Max seconds one party can speak non-stop before auto-hangup. Catches answering machines. 0 = disabled." }
        max_call_duration_secs: { type: number, minimum: 0, maximum: 3600, default: 600, description: "Hard cap on total call duration regardless of activity. 0 = no cap of the agent's own; the platform still ends the call after 65 minutes (3900 s), with the disconnect reason `Platform call limit reached`. A call is never billed for more than this plus 60 seconds; with 0, or once a call is transferred to a person, billing stops at 4 hours." }
        lead_memory_enabled: { type: boolean, default: true, description: "When true, the matched lead's long-term memory context is injected into the system prompt at call time." }
        noise_cancellation_enabled: { type: boolean }
        is_active: { type: boolean }
        webhook_url:
          type: string
          format: uri
          nullable: true
          description: >
            Legacy agents only. Read whole by a key with `tools:read` (or `tools:update`), the
            rule GET /deliveries/{id} applies to the same destination; for any other key, and in
            a campaign or eval-case embed, it is `scheme://host[:port]` and
            `webhook_url_path_withheld` is true. Send the whole URL to change it.
        webhook_url_path_withheld:
          type: boolean
          readOnly: true
          description: >
            Legacy agents only. True when `webhook_url` is shortened to `scheme://host[:port]`
            because the reading key holds neither `tools:read` nor `tools:update`.
        webhook_events:
          type: array
          description: |
            Events posted to `webhook_url` as `{event, timestamp, agent_id, company_id, call_id, data}`.
            `data` on every call event carries `direction`, `status`, `from_number`, `to_number`,
            `duration_seconds`, `started_at` (when the call was placed), `answered_at` (when its audio
            came up; absent until it did) and `recording_started_at` (when its recording began - a
            transcript's `start` and `end` are milliseconds from here; null until the recording is saved,
            on a browser call, and on older calls recorded before the field was added), all ISO 8601 with a `+00:00`
            offset as GET /calls/{id} writes them; plus `disposition`, `summary`, `transcript` and
            `extracted_data` once they exist. `transcript.ready` and `call.analyzed` are sent after the
            recording is saved, so they carry `recording_started_at` on a phone call. No event carries the
            conversation while the call is still going.
            `call.failed` and `call.no_answer` carry `data.hangup_cause` when the cause is known. For a call
            from a number in [your own Telnyx account](/concepts/bring-your-own-carrier) that Telnyx
            refused while it rang, `call.failed` has `data.hangup_cause`:

            - `carrier_rejected` — Telnyx refused the call (SIP 401, 403 or 407).
            - `carrier_number_invalid` — Telnyx could not route the number called (SIP 404, 484 or 604).

            The SIP code is not in the webhook; the carrier account keeps the last one in `last_error.sip_code`.
            One Telnyx refused before it rang sends no webhook when `POST /calls` was placing it (the
            request answers `422`); from the queue it sends `call.failed` with `data.error_reason` instead.
          items:
            type: string
            enum: [call.started, call.answered, call.ended, call.failed, call.no_answer, call.dnc_blocked, transcript.ready, call.analyzed]
        webhook_headers:
          type: object
          nullable: true
          writeOnly: true
          additionalProperties: { type: string }
          description: |
            Legacy agents only. Write-only: set it on PATCH /agents/{id}; no response carries it —
            every read answers `configured_webhook_header_names` instead, and a PATCH that leaves
            it out keeps the stored headers.
            Custom HTTP headers sent with every webhook delivery for this agent (e.g. an auth token).
            Flat name → string-value map, or null to clear. Headers that would override request routing
            or HTTP framing (Host, Content-Length, Transfer-Encoding, Connection, Expect, Keep-Alive,
            TE, Trailer, Upgrade, Proxy-*) are rejected with 400.
          example: { "Authorization": "Bearer sk_live_…", "X-Source": "yappr" }
        configured_webhook_header_names:
          type: array
          readOnly: true
          items: { type: string }
          example: ["Authorization", "X-Source"]
          description: >
            Legacy agents only, and absent from a `workflow` agent's response. The names of the
            stored `webhook_headers`, sorted; the values are never returned, to any key.
        tools:
          type: array
          readOnly: true
          description: >
            Legacy agents only, and absent from a `workflow` agent's response. The agent's tools in
            execution order, each as GET /tools/{id} answers it plus `execution_order`, for a key
            that holds `tools:read`; without it each is `{id, name}` only.
          items: { type: object }
        extraction_parameters:
          type: array
          description: >
            AI extraction parameters — after each call, values are extracted from the transcript,
            stored on the call log and included in the call.analyzed webhook payload. Read them
            back on a call as `extracted_data` in GET /calls/{id}.
          items:
            type: object
            required: [name, description]
            properties:
              name: { type: string, example: "customerName", description: "Parameter key in the extracted_data output" }
              description: { type: string, example: "The caller's full name as mentioned during the conversation", description: "Instructions for the AI on what to extract" }
              type:
                type: string
                enum: [text, number, yes_no, date]
                default: text
                example: "number"
                description: >
                  The kind of value this parameter asks for, which decides what the stored value is:
                  `text` a string, `number` a JSON number, `yes_no` a JSON boolean, `date` a `YYYY-MM-DD`
                  string, read from the day the call started in the workspace's time zone - a day and
                  month with no year is the next time it comes round, "tomorrow" and "next Sunday" are
                  counted from the call day, something the caller says already happened ("three months
                  ago", "it ended in June") is counted back from it, never forward, and a year the caller
                  said is kept. Optional — a parameter saved without one behaves exactly as it always has,
                  as `text`. A value the conversation never supplied is `null` whatever the kind, and a
                  value that cannot be read as the declared kind is `null` rather than a string that
                  only looks like one. Any other value is rejected: `422
                  WORKFLOW_SETTINGS_REQUEST_INVALID` for a workflow agent, `400 BAD_REQUEST` for a
                  prompt or flow agent.
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    AgentTestCallCaller:
      type: object
      required: [agent_id, available, caller_line, from]
      properties:
        agent_id: { type: string, format: uuid }
        available: { type: boolean, description: "false when the workspace has no number and no Yappr test line is available." }
        caller_line:
          type: string
          nullable: true
          enum: [workspace, yappr]
          description: workspace — one of the workspace's own numbers calls. yappr — a Yappr test line calls (it places calls only). null when available is false.
        from: { type: string, nullable: true, description: "The number that would call, E.164." }
    AgentTestCall:
      type: object
      required: [agent_id, to, from, caller_line, status]
      properties:
        id: { type: string, format: uuid, description: "The call's id (agents that do not run a workflow)." }
        call_id: { type: string, format: uuid, nullable: true, description: "The call's id; null on a workflow agent's request until the call is placed." }
        request_id: { type: string, format: uuid, nullable: true, description: "A workflow agent's call request; follow it with GET /call-requests/{id}." }
        status: { type: string, description: "ringing, queued or scheduled." }
        agent_id: { type: string, format: uuid }
        to: { type: string }
        from: { type: string, description: "The number that calls." }
        caller_line: { type: string, enum: [workspace, yappr] }
    DuplicatedAgent:
      description: The copy, as POST /agents answers with it; tool_fork is present only when fork_tools was true.
      allOf:
        - $ref: "#/components/schemas/CreatedAgent"
        - type: object
          properties:
            tool_fork: { $ref: "#/components/schemas/ToolFork" }
    CreatedAgent:
      description: An agent as the two requests that create one answer it.
      allOf:
        - $ref: "#/components/schemas/Agent"
        - type: object
          properties:
            idempotency_key: { type: [string, 'null'], description: "The Idempotency-Key that made this agent, echoed back. Only on the answers of POST /agents and POST /agents/{id}/duplicate." }
    ToolFork:
      type: object
      description: >
        What fork_tools did. status complete — the copy shares no tool with another agent any more;
        partial — some tools are still shared (listed in shared); failed — none could be forked.
        Repeat the same request with the same Idempotency-Key to finish a partial or failed fork.
      required: [status, forked, kept, shared]
      properties:
        status: { type: string, enum: [complete, partial, failed] }
        forked:
          type: array
          description: Tools made for the copy by this request, each already bound in the copy's draft.
          items:
            type: object
            required: [tool_id, name, source_tool_id, source_name, header_names, url_private_part_removed, needs_values]
            properties:
              tool_id: { type: string, format: uuid }
              name: { type: string, description: 'The source name plus " (copy)", or " (copy N)" when that name is taken.' }
              source_tool_id: { type: string, format: uuid }
              source_name: { type: string }
              header_names:
                type: array
                items: { type: string }
                description: Headers carried over by name with an empty value. Enter each value with PATCH /tools/{id} before the copy takes calls.
              url_private_part_removed: { type: boolean, description: "true when the source's address had a private query, which is not carried: send the full configuration.url with PATCH /tools/{id}." }
              needs_values: { type: boolean, description: true when header_names is not empty or url_private_part_removed is true. }
        kept:
          type: array
          description: Tools the copy already had of its own (an earlier fork), left as they are.
          items: { $ref: "#/components/schemas/ToolForkRef" }
        shared:
          type: array
          description: Tools still shared with another agent because they could not be forked. tool_id and name are null when the tool could not be identified.
          items: { $ref: "#/components/schemas/ToolForkRef" }
    ToolForkRef:
      type: object
      properties:
        tool_id: { type: string, format: uuid, nullable: true }
        name: { type: string, nullable: true }
    AgentSettings:
      type: object
      additionalProperties: false
      required: [id, execution_version, updated_at, name]
      description: Ordinary settings only. The original updated_at is the compare-and-swap token for a subsequent workflow-owned agent PATCH; it is not a workflow draft version.
      properties:
        id: { type: string, format: uuid }
        execution_version: { type: string, enum: [workflow_v1] }
        updated_at: { type: string, format: date-time }
        name: { $ref: '#/components/schemas/Agent/properties/name' }
        description: { $ref: '#/components/schemas/Agent/properties/description' }
        voice: { $ref: '#/components/schemas/Agent/properties/voice' }
        model: { $ref: '#/components/schemas/Agent/properties/model' }
        resolved_model: { $ref: '#/components/schemas/Agent/properties/resolved_model' }
        language: { $ref: '#/components/schemas/Agent/properties/language' }
        is_active: { type: boolean }
        temperature: { $ref: '#/components/schemas/Agent/properties/temperature' }
        greeting_message: { $ref: '#/components/schemas/Agent/properties/greeting_message' }
        agent_speaks_first: { type: boolean }
        vad_stop_secs: { $ref: '#/components/schemas/Agent/properties/vad_stop_secs' }
        vad_start_secs: { $ref: '#/components/schemas/Agent/properties/vad_start_secs' }
        vad_confidence: { $ref: '#/components/schemas/Agent/properties/vad_confidence' }
        silence_timeout_secs: { $ref: '#/components/schemas/Agent/properties/silence_timeout_secs' }
        idle_reminder_count: { $ref: '#/components/schemas/Agent/properties/idle_reminder_count' }
        idle_reminder_text: { $ref: '#/components/schemas/Agent/properties/idle_reminder_text' }
        max_continuous_speech_secs: { $ref: '#/components/schemas/Agent/properties/max_continuous_speech_secs' }
        max_call_duration_secs: { $ref: '#/components/schemas/Agent/properties/max_call_duration_secs' }
        lead_memory_enabled: { type: boolean }
        noise_cancellation_enabled: { type: boolean }
        background_sound: { $ref: '#/components/schemas/Agent/properties/background_sound' }
        background_sound_volume: { $ref: '#/components/schemas/Agent/properties/background_sound_volume' }
        extraction_parameters: { $ref: '#/components/schemas/Agent/properties/extraction_parameters' }

    Tool:
      oneOf:
        - $ref: '#/components/schemas/LegacyTool'
        - $ref: '#/components/schemas/WorkflowTool'
        - $ref: '#/components/schemas/ArchivedWorkflowTool'

    ArchivedWorkflowTool:
      type: object
      description: >-
        The short form of an archived workflow tool: what GET /tools/{id} answers for it, and each
        row of a status=archived list. Restore it with POST /tools/{id}/restore.
      required: [id, name, workflow_version, workflow, archived, archived_at]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        description: { type: [string, 'null'] }
        workflow_version: { const: workflow_v1 }
        is_active: { const: false }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        archived: { const: true }
        archived_at: { type: string, format: date-time, description: When the tool was archived. }
        workflow:
          type: object
          required: [kind]
          properties:
            kind: { type: string, enum: [http, app, transfer] }

    LegacyTool:
      type: object
      required: [id, type]
      description: Temporary legacy webhook/function migration boundary. New tools use the workflow variant.
      properties:
        id: { type: string, format: uuid }
        name: { type: string, description: "Normalized to camelCase (e.g. 'capture_lead' → 'captureLead')" }
        description: { type: string, nullable: true }
        type: { type: string, enum: [webhook, function, system], description: "system is a built-in tool from before the workflow engine. POST /tools creates webhook and function legacy tools only." }
        config:
          type: object
          additionalProperties: true
          description: >
            Webhook configuration. Request header values are never returned: a read omits
            `config.headers` entirely and reports the names in `config.configured_header_names`.
            Writes are per header, the same rule a workflow tool follows — omitting `headers`
            keeps every stored header, an explicit empty object clears them all, a string sets
            one, `null` keeps the value already stored under that exact name, and a stored name
            you leave out of a `headers` you did send is removed. On `POST /tools` nothing is
            stored yet, so `null` is refused with `400`.

            A legacy transfer tool (made in the dashboard) carries `destination`,
            `announce_transfer` and `announce_message`, and may carry `transfer_method`,
            `pbx_feature_code` and `pbx_feature_code_hangup_after_secs`: the same keys,
            values and rules as on a flow's TransferNode, with `destination` in place of
            `transfer_to`.
          properties:
            configured_header_names:
              type: array
              readOnly: true
              items: { type: string }
              description: Names of the request headers this tool sends, sorted. Values are never returned.
        is_active: { type: boolean }
        idempotency_key: { type: [string, 'null'], description: The Idempotency-Key the legacy row was created with; null when none was sent. }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    WorkflowToolDefinition:
      oneOf:
        - type: object
          additionalProperties: false
          required: [kind, input_schema, output_schema, configuration]
          properties:
            kind: { const: http }
            input_schema: { type: object, additionalProperties: true, description: Full JSON Schema with an object root. Preserve exact JSON numbers. }
            output_schema: { type: object, additionalProperties: true }
            configuration:
              type: object
              additionalProperties: false
              properties:
                url: { type: string, format: uri, description: Fixed final public HTTP(S) URL. Required on create; omission on update preserves the private accepted URL. Never submit url_display here. }
                method: { type: string, enum: [GET, POST, PUT, PATCH, DELETE], description: "Omitted on create: POST. Omitted on update: keeps the stored value." }
                headers: { type: object, additionalProperties: { type: [string, 'null'] }, description: "Private fixed headers, updated per header. Omitting the whole object on update preserves every stored header; an explicit empty object clears them all. Inside the object, a string sets that header and null keeps the value already stored under that exact name. null is refused outright on create; on update a null under a name with no stored value fails while the revision is built, returning 422 with workflow.status failed and error_code tool_contract_invalid rather than an issues array. A stored header whose name you leave out is removed. Routing and framing headers are rejected." }
            effect: { type: string, enum: [read, write], description: "read for a lookup that changes nothing, write for one that does. Omitted on create: write. Omitted on update: keeps the stored value." }
            timeout_ms: { type: integer, minimum: 1, maximum: 60000, description: "Omitted on create: 30000. Omitted on update: keeps the stored value." }
            include_call_context:
              type: boolean
              description: >
                Whether every request this tool makes carries the call under `call` (see CallPackage).
                Send false for an endpoint that wants nothing but the arguments you mapped; the
                arguments themselves still read the call through {{call.field}} either way.
                Omitted on create: true. Omitted on update: keeps the stored value, so a tool that
                was switched off stays off until a change sends true.
        - type: object
          additionalProperties: false
          required: [kind, metadata_id, connection_id]
          properties:
            kind: { const: app }
            metadata_id: { type: string, format: uuid, description: Local identity returned by the exact dated action-detail endpoint. }
            connection_id: { type: string, format: uuid, description: Exact ready labeled account in the current workspace and environment. Never a provider account ID. }
            fixed_inputs: { type: object, maxProperties: 128, additionalProperties: true, description: "Typed values for the action's reviewed fixed_fields only. These fields are removed from the model input schema and cannot be overridden at execution. Omitted on create: {}. Omitted on update: keeps the stored value." }
            timeout_ms: { type: integer, minimum: 1, maximum: 60000, description: "Omitted on create: 30000. Omitted on update: keeps the stored value." }
        - type: object
          additionalProperties: false
          required: [kind, destination]
          properties:
            kind: { const: transfer }
            destination:
              type: string
              maxLength: 256
              pattern: '^(\+[1-9][0-9]{6,14}|[Ss][Ii][Pp][Ss]?:[^\s?<>",\\:;@]+@[^\s?<>",\\@]+)$'
              description: |
                Either a phone number in international form (`+972501234567`), or a SIP address
                of the caller's own phone system, `sip:extension@pbx.example.com` (`sips:` and a
                port, `sip:101@pbx.example.com:5061`, are accepted). A number is dialled by the
                carrier as before. A SIP address hands the caller back to their phone system,
                which places the new call itself: it works only on calls that arrive through your
                [SIP trunk](/concepts/sip-trunks#transfers). Your phone system has about nine
                seconds to have the new call answered, and if the transfer fails the call
                ends (Yappr cannot take the caller back). The address needs the extension
                before the `@`; a password (`sip:101:secret@...`) and `?headers` are refused, as
                is any value that is neither a number nor a well-formed SIP address (`422`
                `WORKFLOW_TOOL_REQUEST_INVALID`, at `/workflow/destination`). The `pattern` is the coarse
                shape; the full rule is checked when the tool is saved. On a call that arrived through
                an [extension endpoint](/concepts/sip-trunks#transfers-on-extension-calls) the same
                SIP address works differently: Yappr hands the caller to the extension before the `@`
                with your phone system's transfer code when the endpoint has one, and otherwise places
                a new call to it through the extension.
            announce_transfer: { type: boolean, description: "Omitted on create: false. Omitted on update: keeps the stored value." }
            announce_message: { type: string, maxLength: 2000, description: "The short holding line the agent may say before a transfer. Omitted on create: empty. Omitted on update: keeps the stored value. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations)." }
            transfer_method:
              type: string
              enum: [auto, pbx_feature_code]
              description: |
                Only for a transfer that needs a transfer code of its own. Leave it out and, on a call
                that arrived through an extension endpoint, this tool uses the
                [transfer code set on the endpoint](/concepts/sip-trunks#hand-the-call-to-your-phone-system-with-its-transfer-code)
                (`register.pbx_feature_code`), which covers every transfer on its calls.
                `pbx_feature_code` makes the tool use its own `pbx_feature_code` and
                `pbx_feature_code_hangup_after_secs` instead, as a pair: nothing from the endpoint is
                mixed in. `auto` removes the tool's own code and hang-up time, so the endpoint's apply
                again. With `pbx_feature_code`, `destination` must be a SIP address whose extension a
                keypad can dial (up to 32 digits, `*` or `#` before the `@`, such as
                `sip:400@pbx.example.com`), or the save is refused with
                `transfer_extension_not_dialable` at `/workflow/destination`; any other value is
                `transfer_method_invalid`. Ignored on calls that didn't arrive through an extension
                endpoint. Omitted on create: none, so the endpoint's code applies. Omitted on update:
                keeps the stored value, and a kept code lapses when the new `destination` no longer
                names such an extension.
            pbx_feature_code:
              type: string
              examples: ["##", "*2", "*2{extension}#"]
              description: |
                The tool's own transfer code, sent as key presses, with `transfer_method`
                `pbx_feature_code` (`pbx_feature_code_missing` without one). The same rule as the
                endpoint's `register.pbx_feature_code`: 1 to 32 characters of `0`-`9`, `*`, `#`,
                `A`-`D` and the pauses `w` (half a second) and `W` (one second), with at least one
                key. `{extension}` may appear once and is replaced by the extension; without it the
                extension is sent right after the code (`##` and `sip:400@pbx.example.com` send
                `##400`). Surrounding spaces are trimmed before these checks, and the code is stored
                trimmed. Anything else is `pbx_feature_code_invalid`. Omitted on create: none.
                Omitted on update: keeps the stored value.
            pbx_feature_code_hangup_after_secs:
              type: [integer, 'null']
              minimum: 1
              maximum: 10
              examples: [4]
              description: |
                Set it when the tool's own code starts an attended transfer that your phone system
                completes when the extension that typed it hangs up: Yappr hangs up this many seconds
                after the code (counted once its key presses have played), and until then the agent
                is off the line. That hang-up is the hand-off, so there is no fallback dial-back:
                test it once. 4 is a good start. A whole number from 1 to 10
                (`pbx_feature_code_hangup_after_secs_invalid`), only with `transfer_method`
                `pbx_feature_code` and a code (`pbx_feature_code_hangup_after_secs_without_code`).
                Omitted on create: none, so Yappr waits for your phone system to take the call, with
                the dial-back as the fallback. Omitted on update: keeps the stored value; `null`
                removes it.
    WorkflowToolChange:
      type: object
      additionalProperties: false
      required: [name, workflow]
      properties:
        name: { type: string, minLength: 1, maxLength: 200 }
        description: { type: string, maxLength: 10000, description: "What an agent picks this tool by. Omitted on create: empty. Omitted on update: keeps the stored value; send an empty string to clear it." }
        workflow: { $ref: '#/components/schemas/WorkflowToolDefinition' }
        expected_head_revision_id: { type: string, format: uuid }
        expected_head_generation: { type: integer, minimum: 1 }
    WorkflowToolCreate:
      allOf:
        - $ref: '#/components/schemas/WorkflowToolChange'
        - not:
            anyOf:
              - required: [expected_head_revision_id]
              - required: [expected_head_generation]
        - if:
            properties:
              workflow:
                properties:
                  kind: { const: http }
          then:
            properties:
              workflow:
                properties:
                  configuration:
                    required: [url]
    WorkflowToolUpdate:
      allOf:
        - $ref: '#/components/schemas/WorkflowToolChange'
        - required: [expected_head_revision_id, expected_head_generation]
    WorkflowToolRetry:
      description: >-
        PATCH of a tool whose creation failed (workflow.status failed, workflow.current null). It has
        no head, so the whole tool is sent again with neither expected-head field and is built under the
        same id. It is validated as a creation, and needs tools:create as well as tools:update.
      allOf:
        - $ref: '#/components/schemas/WorkflowToolCreate'
    WorkflowToolRevision:
      type: object
      description: Safe authoring projection. Raw execution contracts, provider IDs, URL queries, and header values are never included.
      required: [revision_id, revision, kind, name, description, input_schema, output_schema, allowed_phases, allowed_channels]
      properties:
        revision_id: { type: string, format: uuid }
        revision: { type: integer, minimum: 1 }
        kind: { type: string, enum: [http, app, transfer] }
        name: { type: string }
        description: { type: string }
        input_schema: { type: object, additionalProperties: true }
        output_schema: { type: object, additionalProperties: true }
        allowed_phases: { type: array, items: { type: string, enum: [before, during, after] } }
        allowed_channels: { type: array, items: { type: string, enum: [phone, web] } }
        timeout_ms: { type: integer }
        include_call_context: { type: boolean, description: "HTTP tools. Whether every request this revision makes carries the call under `call`." }
        effect: { type: string, enum: [read, write, terminal] }
        configuration:
          type: object
          description: HTTP display only. Never use this projection as the replacement execution configuration.
          properties:
            method: { type: string }
            url_display: { type: string, description: "Non-executable URL display label without userinfo, query, or fragment." }
            url_redacted: { type: boolean, description: True when the saved URL carries a query string that this projection strips. }
            url_replacement_required:
              const: true
              description: >
                Always true, for every HTTP tool, on every read. It states a rule rather than a
                condition - because this projection is lossy, a revision that changes the URL must
                send the whole URL again, query string included; omit the field to keep the saved
                one. Never send url_display back as the replacement URL.
            configured_query_names:
              type: array
              items: { type: string }
              description: Names of the query parameters configured on the saved URL. Values are never returned.
            configured_header_names: { type: array, items: { type: string } }
            empty_header_names:
              type: array
              items: { type: string }
              description: Present only when some are - the headers whose saved value is empty. A tool a Duplicate with fork_tools made for the copy has every header this way until the values are sent with PATCH /tools/{id}. Values are never returned.
            empty_query_names:
              type: array
              items: { type: string }
              description: Present only when some are - the query parameters on the saved URL written name= with nothing after the =. A forked tool keeps the source's query names this way. Send the whole URL with PATCH /tools/{id} to fill them.
        metadata_id: { type: string, format: uuid }
        connection_id: { type: string, format: uuid }
        connection_label: { type: string }
        connection_ready: { type: boolean }
        toolkit: { type: string }
        action: { type: string }
        version: { type: string, pattern: '^\d{8}_\d{2}$' }
        fixed_inputs: { type: object, additionalProperties: true }
        destination: { type: string }
        announce_transfer: { type: boolean }
        announce_message: { type: string }
        transfer_method:
          type: string
          enum: [pbx_feature_code]
          description: >-
            A transfer tool only, and present only when it carries a
            [transfer code](/concepts/sip-trunks#hand-the-call-to-your-phone-system-with-its-transfer-code)
            of its own, which it uses instead of the one set on the extension endpoint: one set with
            workflow.transfer_method on a create or an update, or one a transfer tool brought with it
            when its agent moved to a workflow. Comes with pbx_feature_code. Absent when the tool uses
            the endpoint's code.
        pbx_feature_code:
          type: string
          description: >-
            Present with transfer_method: the tool's own in-call transfer code, for example ## or *2, sent
            as key presses before the extension.
        pbx_feature_code_hangup_after_secs:
          type: integer
          minimum: 1
          maximum: 10
          description: >-
            Present only with transfer_method and pbx_feature_code, when the tool's own code starts an
            attended transfer: Yappr hangs up this many seconds after the code.
    WorkflowTool:
      type: object
      required: [id, name, workflow_version, workflow]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        description: { type: [string, 'null'] }
        workflow_version: { const: workflow_v1, readOnly: true }
        is_active: { type: boolean }
        created_at:
          type: string
          format: date-time
          description: >-
            When the tool was made. On a creation that has not built, when it was first asked for; a retry
            does not move it.
        integration:
          type: object
          readOnly: true
          required: [connection_id, action]
          description: >-
            Present only on a tool an integration runs one of its actions through: the tool made for a
            connected account's action when that account is given to an agent (POST /agents/{id}/integrations).
            It names the account and the action. Such a tool belongs to the integration and is shared by
            every agent the account is given to: PATCH /tools/{id} answers 409 INTEGRATION_ACTION_MANAGED,
            DELETE /tools/{id} does too while any agent still uses it, and GET /tools leaves it out. Change
            which actions an agent uses with PATCH /agents/{id}/integrations/{integration_id}.
          properties:
            connection_id: { type: string, format: uuid, description: 'The connected account (GET /tool-connections/{id}).' }
            action: { type: string, description: 'The action the tool runs, as GET /tool-connections/{id}/actions lists it.', example: GOOGLECALENDAR_FIND_FREE_SLOTS }
        workflow:
          type: object
          required: [kind, status, request_id, current]
          properties:
            kind: { type: string, enum: [http, app, transfer] }
            status: { type: string, enum: [accepted, claimed, current, queued, compiling, ready, promoted, failed, conflict] }
            request_id: { type: string, format: uuid }
            error_code: { type: [string, 'null'] }
            head_revision_id: { type: [string, 'null'], format: uuid }
            head_generation: { type: [integer, 'null'] }
            current: { oneOf: [{ $ref: '#/components/schemas/WorkflowToolRevision' }, { type: 'null' }] }
            candidate: { oneOf: [{ $ref: '#/components/schemas/WorkflowToolRevision' }, { type: 'null' }] }
            requested:
              type: [object, 'null']
              description: >-
                Only on a creation that has not built (current is null and there is no head_revision_id):
                what it asked for, so it can be sent again with PATCH /tools/{id}. An app tool carries
                metadata_id, connection_id, toolkit, action, version, fixed_inputs and timeout_ms; a transfer
                tool carries destination, announce_transfer and announce_message. An http tool carries
                everything but its credentials: url_display (the address without its query, fragment or
                user:password), url_redacted (true when one of those was taken off, so the full address has
                to be sent again), method, effect, timeout_ms, include_call_context, input_schema,
                output_schema and configured_header_names (names only). Header values are never echoed;
                send them again with the retry.
        warnings:
          type: array
          description: >-
            Present only on a create that went through with something worth saying about it - today,
            only that another tool in this workspace already carries the same name. Never a refusal:
            the tool in the same response exists. Absent when there is nothing to say.
          items:
            type: object
            required: [code, message]
            properties:
              code: { type: string, enum: [tool_name_in_use] }
              message: { type: string }
              tools:
                type: array
                description: The tools already holding the name, at most twenty.
                items:
                  type: object
                  properties:
                    id: { type: string, format: uuid }
                    name: { type: string }
    ToolApp:
      type: object
      required: [slug, name, description, version]
      properties:
        slug: { type: string }
        name: { type: string }
        description: { type: string }
        version: { type: [string, 'null'], description: May be absent from toolkit-list metadata; retrieve toolkit detail to select an available dated version. }
        available_versions: { type: array, items: { type: string, pattern: '^\d{8}_\d{2}$' }, description: Returned by toolkit detail. }
    ToolAction:
      type: object
      required: [slug, toolkit, version, name, description]
      properties:
        slug: { type: string }
        toolkit: { type: string }
        version: { type: string, pattern: '^\d{8}_\d{2}$' }
        name: { type: string }
        description: { type: string }
    ToolActionDetail:
      allOf:
        - $ref: '#/components/schemas/ToolAction'
        - type: object
          required: [id, eligible, effect, policy_basis, input_schema, output_schema, required_scopes, fixed_fields, required_fixed_fields]
          properties:
            id: { type: string, format: uuid }
            eligible: { type: boolean, description: Whether the exact metadata version has an execution policy. Every action gets one automatically from its own metadata unless a person has reviewed it or switched it off; a reviewed or switched-off policy always wins. False actions cannot be saved as executable tools. }
            effect: { type: string, nullable: true, enum: [read, write], description: 'The policy the action runs under. read - may be refreshed automatically, safe to repeat. write - runs at most once and is never retried automatically. Anything not clearly a read is a write. Null when not eligible.' }
            policy_basis: { type: string, nullable: true, enum: [reviewed, automatic], description: 'automatic - derived from the action''s own metadata, because no person has reviewed it. reviewed - a person approved this exact content. A review replaces an automatic policy. Null when not eligible.' }
            input_schema: { type: object, additionalProperties: true, description: "Complete authoritative dated schema, not a CLI or model projection." }
            output_schema: { type: object, additionalProperties: true }
            required_scopes:
              type: object
              properties:
                all_of: { type: array, items: { type: string } }
                any_of: { type: array, items: { type: array, items: { type: string } }, description: At least one scope from each alternative group is required. }
            fixed_fields: { type: array, items: { type: string } }
            required_fixed_fields: { type: array, items: { type: string } }

    WorkflowToolTestRequest:
      type: object
      additionalProperties: false
      required: [phase, channel, inputs]
      properties:
        phase: { type: string, enum: [before, during, after], description: "Validation placement only, never live-call authority." }
        channel: { type: string, enum: [phone, web], description: Must be allowed by the pinned tool. Does not place a call. }
        inputs: { type: object, additionalProperties: true, description: "Exact typed JSON inputs, maximum 256 KiB. Fixed app fields cannot be overridden." }
        mock_output: { description: "Typed output used by mock execution, maximum 256 KiB. Must validate against the frozen output schema. Left out, the mock answers the output schema's minimal value ({} for {type: object}); a schema with required members needs it (400 field_required at /mock_output otherwise)." }
        policy: { type: string, enum: [mock, allowlist], default: mock }
        allowed_binding_ids: { type: array, items: { const: test_tool }, maxItems: 1, default: [], description: 'The one binding a saved-tool test has, whose id is always the literal test_tool - a binding id out of a workflow is refused. ["test_tool"] with policy allowlist permits that binding''s single real effect; [] (the default, and the only value a mock test may send) keeps the test mocked; [] with policy allowlist grants nothing and is refused 422 at /allowed_binding_ids. Transfer effects are always forbidden in saved-tool tests.' }
        revision_id: { type: [string, 'null'], format: uuid, description: Optional exact revision of this tool. Omission freezes the current head at initial acceptance; same-key replay retains that original revision. }
    WorkflowToolTest:
      type: object
      required: [test_id, run_id, tool_id, revision_id, phase, channel, policy, status, redaction]
      properties:
        test_id: { type: string, format: uuid }
        run_id: { type: string, format: uuid, description: Shared journal identity only; this ID does not grant access to call history. }
        tool_id: { type: string, format: uuid }
        revision_id: { type: string, format: uuid }
        phase: { type: string, enum: [before, during, after] }
        channel: { type: string, enum: [phone, web] }
        policy: { type: string, enum: [mock, allowlist] }
        status:
          type: string
          enum: [accepted, prepared, running, succeeded, failed, blocked, pending, unknown, cancelled]
          description: >
            `blocked` — nothing was sent. `failed` — the endpoint refused it, or answered 2xx
            with a body the tool could not use; its delivery reads `failed` too. `unknown` — no
            answer came back; its delivery reads `unknown` too.
        created_at: { type: string, format: date-time }
        deadline_at: { type: string, format: date-time }
        completed_at: { type: [string, 'null'], format: date-time }
        error_code:
          type: [string, 'null']
          description: Why a settled test did not succeed — the same code as `outcome.error_code` once its request has settled.
        invocation_id: { type: [string, 'null'] }
        attempt_id: { type: [string, 'null'], format: uuid }
        receipt_id: { type: [string, 'null'] }
        receipt_settled_test: { type: boolean, description: Distinguishes the receipt that settled this test from a later receipt. }
        resolution: { type: [string, 'null'], enum: [manual_reconciliation_required, null], description: Set only when no answer came back (a timeout or dropped connection); an endpoint that answered with an error settles failed with no resolution. }
        replayed: { type: boolean }
        delivery_id: { type: [string, 'null'], format: uuid, description: 'The delivery this real HTTP test''s request made (GET /deliveries/{id}), with the same verdict; POST /deliveries/{id}/retry sends it again. Null when no request left (mock, connected-app action, refused before sending) and on tests settled before 2026-09-25.' }
        outcome:
          type: [object, 'null']
          description: Bounded redacted display projection, never raw vendor evidence or an execution input. A late outcome does not rewrite settled test status. An endpoint that answered with an error (4xx or 5xx) reads status and effect_status failed with error_code downstream_http_error and its http_status. One that answered 2xx with a body the tool could not use reads status failed, effect_status succeeded, and error_code output_schema_invalid, invalid_json_response or response_too_large (a body over 256 KB, or one with more values than Yappr holds that no cut can fit). `blocked` means nothing was sent.
          properties:
            status: { type: string, enum: [succeeded, failed, blocked, pending, unknown] }
            effect_status: { type: string, enum: [not_dispatched, succeeded, failed, pending, unknown] }
            output: { description: Redacted typed JSON display value. }
            error_code: { type: [string, 'null'] }
            http_status: { type: [integer, 'null'] }
            retryable: { const: false, description: "Yappr never sends a tool's request again on its own. To send it again, retry the delivery named by delivery_id." }
            output_fields:
              type: array
              maxItems: 10
              description: >
                Only on `output_schema_invalid`, and only when the engine could name them: each
                Output field the tool declares that the answer left out (`missing`) or did not match
                (`mismatched`) - the name from the tool's own schema, never a value from the answer.
                Absent when the answer as a whole was wrong (not an object).
              items:
                type: object
                required: [name, problem]
                properties:
                  name: { type: string }
                  problem: { type: string, enum: [missing, mismatched] }
            output_trimmed:
              type: array
              maxItems: 10
              description: >
                Only when the answer was larger than Yappr can hold (more than 4,096 values, or a
                list of more than 256 items) and was cut instead of refused: each list that shows
                only its first items. The agent is told the same, so it says there is more rather
                than reading a partial list as the whole, and a rule or a later step never reads a
                cut list, or an item past the cut, as if it were whole. Structure only, never a value
                from the answer; absent when the answer was held whole. Only a tool the agent calls
                during the conversation is cut: an answer to a step before or after the call, to a
                step inside a sequence, or to the calendar availability check is refused as before.
              items:
                type: object
                required: [path, kept, of]
                properties:
                  path: { type: string, description: 'JSON Pointer to the list inside `output`; the empty string when `output` itself is the list. A key that is not a plain identifier (letters, digits, `_`, `-`) is shown as `*`.' }
                  kept: { type: integer, minimum: 1, description: 'How many items the agent receives - the first ones, unedited. The `output` a test displays is shortened separately for display (its lists show at most 64 items), so it can show fewer.' }
                  of: { type: integer, minimum: 2, description: How many items the endpoint or app sent. }
        redaction:
          type: object
          required: [version, redacted, truncated]
          properties:
            version: { const: execution-outcome-v1 }
            redacted: { type: boolean }
            truncated: { type: boolean }
    WorkflowToolContractRevision:
      type: object
      description: >
        One immutable contract revision of a saved tool. Private endpoint configuration
        (URL, header values, transfer destination) is never included: it stays on the tool
        itself and is supplied by Yappr at call time.
      required: [id, tool_id, revision, name, kind, input_schema, output_schema]
      properties:
        id: { type: string, format: uuid }
        tool_id: { type: string, format: uuid }
        revision: { type: integer, minimum: 1, description: Increments by one per revision of this tool. Use the highest value as expected_revision for the next write. }
        created_at: { type: string, format: date-time, description: When this revision was made. On every row of the list. }
        name: { type: string, description: Copied from the saved tool. It cannot be set through this endpoint. }
        description: { type: string }
        kind: { type: string, enum: [http, transfer], description: Derived from the saved tool's own type; it cannot be set through this endpoint. }
        input_schema: { type: object, additionalProperties: true }
        output_schema: { type: object, additionalProperties: true }
        allowed_phases:
          type: array
          items: { type: string, enum: [before, during, after] }
          description: Defaults to all three. Transfer tools are always ["during"], whatever you send.
        allowed_channels:
          type: array
          items: { type: string, enum: [phone, web] }
          description: Defaults to both. Transfer tools are always ["phone"], whatever you send.
        timeout_ms: { type: integer, default: 30000 }
        effect: { type: string, description: "Defaults to \"write\". Transfer tools are always \"terminal\", whatever you send." }
        replay_safe: { type: boolean, default: false, description: "Transfer tools are always false, whatever you send." }
        include_call_context:
          type: boolean
          default: true
          description: >
            Whether every request this tool makes carries the call under `call` (see CallPackage).
            Returned only when it is false, because true is what every tool does unless you say
            otherwise. Turn it off for an endpoint that wants nothing but the inputs you mapped;
            the inputs themselves still read the call through {{call.field}} either way.
    CallPackage:
      type: object
      description: >
        Everything Yappr knows about one call, sent as the `call` member of every request Yappr
        makes to your own endpoint for a workflow tool - a before-call request, a tool the agent
        calls mid-call, and a tool test alike. One definition, one version, so the connected-app
        actions, transfers and After-call posts that do not carry it yet will carry this same
        object rather than one of their own.

        Members are graded by phase, and a member the phase cannot know is absent rather than
        null: a before-call request has no `call_id` because the call does not exist yet, and
        nothing before the call ends carries the transcript. `phase` tells you which grade you
        are reading. The nine members Yappr's webhook tools have always sent - `company_id`,
        `agent_id`, `agent_name`, `call_id`, `call_direction`, `caller_number`,
        `callee_number`, `call_metadata`, `call_variables` - keep their names and their
        empty-string/empty-object convention, so an endpoint written against that payload
        keeps parsing. A declared input of your own named `call` wins over this member.
      required: [version, phase]
      properties:
        version: { type: string, enum: ['1'], description: "The package's own version, independent of the API version." }
        phase: { type: string, enum: [before, during, after], description: Which grade of the package this is. }
        test: { type: boolean, description: Present and true only for a tool test. Absent on a real call. }
        company_id: { type: string, description: 'Phase: before onwards.' }
        agent_id: { type: [string, 'null'], description: 'Phase: before onwards. Null in a tool test, which serves no agent.' }
        agent_name: { type: string, description: 'Phase: before onwards.' }
        call_direction: { type: string, description: 'inbound, outbound or web_call. Phase: before onwards.' }
        caller_number: { type: string, description: 'E.164, or "" on a browser call. Phase: before onwards.' }
        callee_number: { type: string, description: 'E.164, or "" on a browser call. Phase: before onwards.' }
        call_metadata: { type: object, additionalProperties: true, description: 'The metadata the call request carried. Phase: before onwards.' }
        call_variables: { type: object, additionalProperties: true, description: 'The variables the call request carried. Phase: before onwards.' }
        channel: { type: string, enum: [phone, web], description: 'Phase: before onwards.' }
        phone_number_id: { type: string, description: 'Present when the call is bound to one of your numbers. Phase: during onwards - it lives on the call row, which does not exist before the call.' }
        lead_id: { type: string, description: 'Present when the call has a lead. Phase: during onwards - it lives on the call row, which does not exist before the call.' }
        call_id: { type: [string, 'null'], description: 'Phase: during onwards - there is no call before the call. Null in a tool test, which serves no call.' }
        started_at: { type: string, format: date-time, description: 'Phase: during onwards.' }
        ended_at: { type: string, format: date-time, description: 'Phase: after.' }
        duration_seconds: { type: integer, description: 'Phase: after.' }
        status: { type: string, description: 'The call''s current status - a live state such as ringing or in_progress while the call is up, then how it ended. Phase: during onwards; not the signal that a call has stopped.' }
        ended_by: { type: string, description: 'Who ended it - caller, agent, system, operator or unknown. Phase: after.' }
        close_reason: { type: string, description: 'Phase: after.' }
        transcript: { description: 'Phase: after, once the transcript is ready.' }
        analysis: { description: 'Phase: after, once the analysis is ready.' }
        recording_url: { type: string, description: 'Phase: after, once the recording is ready. A signed link on the API host that lasts 7 to 8 days and can be revoked (POST /calls/{id}/recording/revoke), the same link GET /calls/{id} returns.' }
        lead: { description: 'Phase: after, once the lead is ready.' }
        disposition: { description: 'Phase: after.' }
        billing: { description: 'Phase: after, once billing is ready.' }
    WorkflowToolContractRevisionList:
      type: object
      required: [data]
      properties:
        data:
          type: array
          maxItems: 100
          description: Newest revision first, capped at the 100 most recent.
          items: { $ref: '#/components/schemas/WorkflowToolContractRevision' }
    WorkflowToolContractRevisionCreate:
      type: object
      additionalProperties: false
      required: [expected_revision, contract]
      description: >
        Exactly these two properties are accepted; any other property is rejected.
        Identity, description and private endpoint configuration are read from the saved
        tool and cannot be supplied here.
      properties:
        expected_revision:
          type: [integer, 'null']
          minimum: 1
          description: The highest revision you last read for this tool, or null when the tool has no revision yet. A mismatch is a conflict and nothing is written.
        contract:
          type: object
          additionalProperties: false
          required: [input_schema, output_schema]
          properties:
            input_schema: { type: object, additionalProperties: true }
            output_schema: { type: object, additionalProperties: true }
            allowed_phases: { type: array, items: { type: string, enum: [before, during, after] } }
            allowed_channels: { type: array, items: { type: string, enum: [phone, web] } }
            timeout_ms: { type: integer }
            effect: { type: string }
            replay_safe: { type: boolean }
            include_call_context:
              type: boolean
              default: true
              description: >
                Send false to stop this tool's requests carrying the call under `call`. Anything
                other than true or false is rejected; sending true is the same as not sending it,
                and the revision records nothing.
    ExecutionSettlement:
      type: object
      description: >
        AI37: the three members of the execution block a poller stops on, at the block's own paths,
        worked out from the call itself - it has ended, its analysis and cost_status are not pending, and
        no stage, step, follow-up or delivery on its timeline is pending. Carried by GET /calls/{id} when
        `execution_status` is `omitted` or `pending`.
      required: [summary, refresh_after_ms]
      properties:
        summary:
          type: object
          required: [settlement, is_settled]
          properties:
            settlement: { type: string, enum: [settled, unsettled, unavailable], description: "unavailable when the call's timeline could not be read either." }
            is_settled: { type: boolean, nullable: true, description: "null exactly when settlement is unavailable." }
        refresh_after_ms: { type: integer, nullable: true, description: "Milliseconds to wait before reading again; null once settled." }
    CallExecution:
      type: object
      additionalProperties: false
      description: |
        **Execution history — how the platform carried the call out**, beside the
        conversation itself. Returned on `GET /calls/{id}` and `GET /call-requests/{id}`
        when execution history is enabled for the workspace; absent otherwise. Ask for a
        page of it with the `execution_limit` and `execution_cursor` query parameters.

        This is an investigation view, not an authority: it is read-only, it is retained
        for a limited window, and it never carries the platform's own plumbing.

        **The members below are the whole of this block.** They are written down
        because the API projects onto exactly this list before the response is written:
        anything else the platform knows about a call — delivery row ids, internal job
        and journal counts, storage-retention flags, internal hostnames, its own
        diagnostic notes — is dropped rather than published, and every URL here is
        rewritten onto the public API base whatever the platform recorded. A field you
        do not see below will not appear, and a field you do see will not change shape.
      properties:
        version: { type: string, const: execution-visibility-v1 }
        audience: { type: string, const: company, description: Whose view this is. A company-authorized read is the only one this API returns. }
        subject: { type: string, enum: [call, tool_test] }
        run_id: { type: [string, 'null'], format: uuid, description: Shared lifecycle identity of the request and the call it became. }
        request_id: { type: [string, 'null'], format: uuid }
        call_id: { type: [string, 'null'], format: uuid }
        tool_id: { type: [string, 'null'], format: uuid, description: Tool tests only. }
        test_id: { type: [string, 'null'], format: uuid, description: Tool tests only. }
        workflow_revision_id: { type: [string, 'null'], format: uuid, description: The published version of the agent this run was frozen on. }
        strict: { type: [boolean, 'null'], description: Whether the run was admitted under the agent's strict setting. }
        owner: { type: string, enum: [workflow_v1, legacy], description: "Which authoring model owns the run - `workflow_v1` for a workflow agent; `legacy` for a call of an agent that runs no workflow (a prompt agent, and every call from before workflows), whose history is what the call itself recorded (history.coverage legacy_best_effort). Such a call reads execution_status included, not none." }
        channel: { type: [string, 'null'], enum: [phone, web, null] }
        direction: { type: [string, 'null'], enum: [inbound, outbound, web, null] }
        refresh_after_ms: { type: [integer, 'null'], description: "How long to wait before asking again while work is still running. On GET /calls/{id}, null once the call has settled (summary.is_settled true): nothing on it will change." }
        supplementary: { type: string, enum: [complete, partial, not_loaded], description: Whether the conversation-side records beside this block were loaded for this response. }
        supplementary_errors:
          type: array
          description: Reason codes for anything the read beside this block could not load. Empty when `supplementary` is `complete`.
          items: { type: string }
        links:
          type: object
          additionalProperties: false
          description: >
            Public API URLs for the related records, and the only three link members there
            are. Each one is rewritten onto this API's own base before it is published.
          properties:
            request: { type: string, format: uri }
            call_detail: { type: string, format: uri }
            tool_test: { type: string, format: uri }
        summary:
          type: object
          additionalProperties: false
          description: Where the call got to, rolled up.
          properties:
            revision: { type: string, description: "Monotonic revision of this snapshot, as a string so a large value survives JavaScript." }
            as_of: { type: string, format: date-time }
            run_status:
              type: [string, 'null']
              enum: [accepted, materialized, cancelled, failed, completed, null]
              description: >
                Where the call's run is. `materialized` while its window is open - a call's
                follow-ups can still start until the window closes, which is hours after the
                call is accepted - and `completed` once the window has closed and every phase
                of the run, its post-call jobs and its call attempts have ended. A follow-up
                that failed does not make the run `failed`: read that on the follow-up's own
                row. `failed` and `cancelled` mean the call was refused, abandoned or
                cancelled before it ran.
            call_state: { type: string }
            physical_end_observed: { type: [boolean, 'null'], description: "Whether the carrier confirmed the line was down, rather than the platform inferring it." }
            follow_up_state: { type: string, enum: [not_started, running, succeeded, failed, unknown, cancelled, unavailable], description: 'On GET /calls/{id}, one word for the call''s follow_ups member and its trigger timeline rows together: failed, running, not_started (follow_ups waiting), cancelled (follow_ups skipped), unknown, succeeded - the first that fits. unavailable when nothing ran and nothing is explained, and on a call request (read the call).' }
            settlement: { type: string, enum: [unsettled, settled, unavailable] }
            is_settled:
              type: [boolean, 'null']
              description: >
                On GET /calls/{id}, true (with settlement `settled`) once the call has ended, its
                analysis and cost are final, and nothing of its own is still running, waiting or
                due; a browser session that ended before anyone connected reads the same. Stop
                polling then. Null while that cannot be said yet.
            settlement_reasons:
              type: array
              description: Reason codes for an unsettled call.
              items: { type: string }
            counts:
              type: object
              additionalProperties: false
              description: >
                Counts by phase and then by status, for the customer's own work only -
                `invocations` (steps the agent ran) and `attempts` (tries those took).
                Internal platform job and journal counts are not included. Phase and
                status keys are lowercase identifiers and the values are whole numbers;
                a bucket holding no counts is omitted rather than sent empty.
              properties:
                invocations:
                  type: object
                  propertyNames: { pattern: '^[a-z][a-z_]{0,39}$' }
                  additionalProperties:
                    type: object
                    propertyNames: { pattern: '^[a-z][a-z_]{0,39}$' }
                    additionalProperties: { type: integer }
                attempts:
                  type: object
                  propertyNames: { pattern: '^[a-z][a-z_]{0,39}$' }
                  additionalProperties:
                    type: object
                    propertyNames: { pattern: '^[a-z][a-z_]{0,39}$' }
                    additionalProperties: { type: integer }
            active_work:
              type: array
              description: Work still running or waiting at the moment of this snapshot.
              items:
                type: object
                additionalProperties: false
                properties:
                  id: { type: string, format: uuid }
                  phase: { type: string, enum: [before, during, after, platform] }
                  kind: { type: string }
                  status: { type: string }
                  reason_code: { type: [string, 'null'] }
                  deadline_at: { type: [string, 'null'], format: date-time }
            active_work_truncated: { type: boolean, description: True when more work was running than this list shows. }
            latest_problem:
              type: [object, 'null']
              additionalProperties: false
              description: The most recent piece of work that failed or was blocked, in the same shape as active_work.
              properties:
                id: { type: string, format: uuid }
                phase: { type: string, enum: [before, during, after, platform] }
                kind: { type: string }
                status: { type: string }
                reason_code: { type: [string, 'null'] }
                deadline_at: { type: [string, 'null'], format: date-time }
            next_deadline_at: { type: [string, 'null'], format: date-time }
            artifacts:
              type: array
              description: Readiness of each thing the call produces - recording, transcript, analysis, lead, billing.
              items:
                type: object
                additionalProperties: false
                properties:
                  artifact: { type: string, enum: [recording, transcript, analysis, lead, billing] }
                  status: { type: string, enum: [pending, running, succeeded, empty, skipped, failed, not_expected, unavailable] }
                  version: { type: integer }
                  output_revision: { type: integer }
                  attempts: { type: integer }
                  deadline_at: { type: [string, 'null'], format: date-time }
                  reason_code:
                    type: [string, 'null']
                    description: >
                      Why the artifact is not `succeeded`. On `GET /calls/{id}` the `analysis` entry agrees
                      with the call's `analysis` member: a pass that left no summary reads `failed` /
                      `no_summary` here too. A `lead` entry that reads `skipped` names why:
                      `web_call_no_phone` (a browser rehearsal has no caller's number),
                      `transcript_too_short` (fewer than two turns) or `no_phone_number`.
        history:
          type: object
          additionalProperties: false
          description: The page of history you were given, and how to get the next one.
          properties:
            high_water_mark: { type: string, description: "Furthest journal position this snapshot covers, as a string." }
            retained_from_sequence: { type: string, description: "Earliest position still retained, as a string." }
            coverage: { type: string, enum: [canonical, legacy_best_effort] }
            coverage_started_at: { type: [string, 'null'], format: date-time }
            complete: { type: boolean, description: "True when this page is the whole history: on GET /calls/{id}, a settled call with no next_url and nothing expired." }
            gaps:
              type: array
              description: Why this page may not be the whole history. Empty when complete is true.
              items: { type: string }
            retained_until: { type: [string, 'null'], format: date-time }
            filters:
              type: object
              additionalProperties: false
              description: The filters this page was read under, echoed back.
              properties:
                phase: { type: [string, 'null'], enum: [before, during, after, platform, null] }
                kind: { type: [string, 'null'] }
                status: { type: [string, 'null'] }
            limit: { type: integer }
            next_url: { type: [string, 'null'], format: uri, description: "Next page, on the public API base. Null on the last page." }
            refresh_url: { type: string, format: uri, description: "This same page again, on the public API base." }
        items:
          type: array
          description: >
            The time-ordered rows themselves - one per step, attempt, phase boundary or
            platform event the call produced. `sequence` is a string so a large journal
            position survives JavaScript. `input` and `output` are bounded, redacted
            previews of the customer's own evidence, never raw credentials.
          items:
            type: object
            additionalProperties: false
            properties:
              id: { type: string, format: uuid }
              sequence: { type: string, description: "Journal position, as a string so a large value survives JavaScript." }
              phase: { type: string, enum: [before, during, after, platform] }
              kind: { type: string }
              event: { type: string }
              status: { type: [string, 'null'] }
              call_id: { type: [string, 'null'], format: uuid }
              request_id: { type: [string, 'null'], format: uuid }
              phase_id: { type: [string, 'null'], format: uuid }
              invocation_id: { type: [string, 'null'], format: uuid }
              attempt_id: { type: [string, 'null'], format: uuid }
              receipt_id: { type: [string, 'null'], format: uuid }
              attempt_number: { type: [integer, 'null'] }
              outer_run: { type: [integer, 'null'] }
              inner_attempt: { type: [integer, 'null'] }
              reason_code: { type: [string, 'null'] }
              late: { type: boolean, description: True when the row arrived after the page it belongs to was already read. }
              selected: { type: [boolean, 'null'] }
              should_execute: { type: [boolean, 'null'] }
              edges_truncated: { type: boolean }
              action:
                type: [object, 'null']
                additionalProperties: false
                description: The step this row is about, where it is one.
                properties:
                  name: { type: string }
                  type: { type: string, enum: [http, app, sequence, end_call, transfer, platform] }
                  binding_id: { type: [string, 'null'], format: uuid }
                  activation: { type: [string, 'null'] }
                  tool_id: { type: [string, 'null'], format: uuid }
                  tool_revision_id: { type: [string, 'null'], format: uuid }
                  schema_version: { type: [string, 'null'] }
                  adapter_version: { type: [string, 'null'] }
                  compatibility_version: { type: [string, 'null'] }
                  connection_id: { type: [string, 'null'], format: uuid }
                  connection_label: { type: [string, 'null'] }
                  connection_generation: { type: [integer, 'null'] }
              field_errors:
                type: array
                description: Validation failures, by path into the step's own input.
                items:
                  type: object
                  additionalProperties: false
                  properties:
                    path: { type: string }
                    code: { type: string }
              edges:
                type: array
                description: >
                  Links to other rows of this same block. Only edges pointing at something
                  you can read here are included - an invocation, a phase, or an artifact.
                items:
                  type: object
                  additionalProperties: false
                  properties:
                    relation: { type: string, enum: [parent, depends_on, triggered_by, replay_of, receipt_for] }
                    kind: { type: string, enum: [invocation, phase, artifact] }
                    id: { type: string, format: uuid }
              timing:
                type: object
                additionalProperties: false
                properties:
                  occurred_at: { type: [string, 'null'], format: date-time }
                  recorded_at: { type: string, format: date-time }
                  queued_at: { type: [string, 'null'], format: date-time }
                  claimed_at: { type: [string, 'null'], format: date-time }
                  dispatched_at: { type: [string, 'null'], format: date-time, description: "When the request actually left, never a claim timestamp." }
                  completed_at: { type: [string, 'null'], format: date-time }
                  queue_ms: { type: [integer, 'null'] }
                  validation_ms: { type: [integer, 'null'] }
                  network_ms: { type: [integer, 'null'] }
                  total_ms: { type: [integer, 'null'] }
                  audio_offset_ms: { type: [integer, 'null'], description: "Where in the recording this happened, where that is known." }
                  audio_clock_id: { type: [string, 'null'] }
              retry:
                type: object
                additionalProperties: false
                properties:
                  eligibility: { type: string, enum: [not_eligible, automatic, manual, unknown] }
                  reason_code: { type: [string, 'null'] }
                  next_at: { type: [string, 'null'], format: date-time }
                  automatic_recovery_stopped: { type: boolean }
              input:
                type: object
                additionalProperties: false
                description: Bounded, redacted preview of what went into the step.
                properties:
                  value: { description: "The preview itself - any JSON, exactly as the platform recorded it, or null when there is none." }
                  availability: { type: string, enum: [available, not_applicable, unavailable] }
                  unavailable_reason: { type: [string, 'null'] }
                  redacted: { type: boolean }
                  truncated: { type: boolean }
                  omitted:
                    type: array
                    description: What was left out of the preview, and why.
                    items:
                      type: object
                      additionalProperties: false
                      properties:
                        path: { type: string }
                        reason: { type: string, enum: [configured_sensitive, credential, private_reference, diagnostic, secret_value, url, depth_limit, byte_limit, node_limit, item_limit, string_limit, unavailable] }
                  omitted_metadata_truncated: { type: boolean }
                  expanded: { type: boolean }
              output:
                type: object
                additionalProperties: false
                description: Bounded, redacted preview of what the step returned.
                properties:
                  value: { description: "The preview itself - any JSON, exactly as the platform recorded it, or null when there is none." }
                  availability: { type: string, enum: [available, not_applicable, unavailable] }
                  unavailable_reason: { type: [string, 'null'] }
                  redacted: { type: boolean }
                  truncated: { type: boolean }
                  omitted:
                    type: array
                    description: What was left out of the preview, and why.
                    items:
                      type: object
                      additionalProperties: false
                      properties:
                        path: { type: string }
                        reason: { type: string, enum: [configured_sensitive, credential, private_reference, diagnostic, secret_value, url, depth_limit, byte_limit, node_limit, item_limit, string_limit, unavailable] }
                  omitted_metadata_truncated: { type: boolean }
                  expanded: { type: boolean }
              expansion_url: { type: [string, 'null'], format: uri, description: "This row on its own, with fuller previews. On the public API base." }
    CallRequest:
      type: object
      description: >
        Lifecycle record for one accepted call on a workflow agent. An outbound phone call
        returns its identity as `request_id` from POST /calls; a browser call is created
        directly with POST /call-requests. Either way this object is what you poll and what you
        cancel, and the two follow the same states.
      required: [id, run_id, channel, status, preparation_status, expires_at]
      properties:
        id: { type: string, format: uuid }
        run_id: { type: string, format: uuid, description: Shared lifecycle identity. It does not grant access to call history. }
        agent_id: { type: string, format: uuid, description: "The agent the request was made for. On GET /call-requests/{id}, the browser's poll and a replayed create." }
        channel:
          type: string
          enum: [phone, web]
          description: >
            `phone` is dialled by the platform once it is ready. `web` is started by the caller's
            own browser with POST /call-requests/{id}/start, because the microphone is there and
            not here.
        preparation_steps:
          type: array
          description: >
            On GET /call-requests/{id} (either channel) and the browser's poll. One entry per
            before-call step the workflow declares, in document order, whatever ran - so a
            waiting caller can be shown what is running, and a server can see which step failed
            and what its tool answered. Empty only between accepting the request and freezing the
            workflow version it runs. Step results are never included.
          items:
            type: object
            required: [id, label, status]
            properties:
              id: { type: string }
              label: { type: string, description: The author's own name for the step. }
              status:
                type: string
                enum: [waiting, inactive, running, pending, unknown, succeeded, failed, blocked, skipped, not_run, cancelled]
                description: >
                  waiting (not started yet); inactive (it runs only if an earlier step's route
                  chooses it, and none has yet); running (sent, waiting for the answer); pending
                  (its address accepted the request without a final answer, such as an HTTP 202 -
                  settled as failed in a moment); unknown (the request may or may not have reached
                  its address - a timeout or a dropped connection - settled as failed in a moment,
                  never sent twice); succeeded; failed; blocked (not sent, or its answer was not
                  usable); skipped (its condition said no, no route chose it, a step it depends on
                  was skipped, or an earlier step stopped the preparation); or not_run - the
                  preparation ended (failed, cancelled or ran out of time) before this step ran; or
                  cancelled - the request was cancelled while this step was running, and whatever
                  it answered is not used. waiting, inactive, running, pending and unknown are seen
                  while the request is preparing. A finished preparation reads succeeded, failed,
                  blocked, skipped, not_run and cancelled (an inactive step it never reached reads
                  not_run; a step a cancel overtook reads cancelled, never running), except one that
                  ended preparation_interrupted: the step it was running keeps the status it had.
              error_code:
                type: string
                description: >
                  Only on a step that did not succeed: what its tool answered, in the platform's
                  own codes - `downstream_http_error` (the address answered an HTTP error; see
                  `http_status`), `http_timeout`, `http_network_error`, `url_resolves_private`,
                  `output_schema_invalid` and the like. Never the response itself.
              http_status:
                type: integer
                description: >
                  Only on a step whose address answered: its HTTP status. A 4xx other than 408
                  and 429 answers the same way on every retry until the tool changes.
              refused_call:
                type: boolean
                description: >
                  true only on the step whose route refused the call (the request reads failed with
                  error_code before_declined). A step refused on a failure keeps its error_code and
                  http_status; one refused on its answer reads succeeded. Absent on every other step.
        status:
          type: string
          enum: [preparing, scheduled, ready, dispatching, dispatched, failed, expired, cancelled, dispatch_unknown]
          description: >
            `scheduled` waits for the workspace's next calling window; `preparing` and `ready`
            cover pre-call work; `dispatching` and `dispatched` mean the call is being placed or
            has been placed; `dispatch_unknown` means placement is still being confirmed and must
            not be retried blindly; `failed`, `expired` and `cancelled` are final.
        preparation_status:
          type: string
          enum: [pending, running, ready, failed, expired, cancelled, declined]
          description: >
            Progress of the pre-call step only. A preparation that fails or runs out of time does not
            always fail the request - an agent configured to continue with whatever is available still
            calls, with whatever the preparation produced. `declined` is a decision rather than a
            failure - a before-call step refused the call, so nothing is dialled, no call record is
            created, and the failure policy does not apply.
        workflow_revision_id: { type: [string, 'null'], format: uuid, description: The published version of the agent frozen for this request. }
        call_id: { type: [string, 'null'], format: uuid, description: "Set once a call record exists. Pass it to the call-by-id endpoint." }
        expires_at: { type: string, format: date-time, description: "After this moment a request that has not finished is abandoned and no call is placed. A request that already failed keeps status failed and its error_code." }
        error_code:
          type: [string, 'null']
          description: >
            Present only when status is failed or expired. An expired request is always
            `request_expired`. On a failed one the preparation's own code wins wherever it recorded one
            - `step_failed` when a before-call step failed and its failure setting stops the call
            (`preparation_steps` names the step and what its tool answered), `before_declined` for a
            refusal, `preparation_interrupted` when the platform could not finish running the steps
            (a fault on its side, never a tool's answer; no step is sent twice - create a new
            request), `preparation_unavailable` when the steps could not be run at all,
            `promotion_stalled` when the agent's latest settings were still not ready 30 s after the
            request was due (retry shortly) - and where it recorded nothing the value is
            `before_declined` for a refusal and `request_failed` for anything else.
        execution: { $ref: '#/components/schemas/CallExecution' }
    LegacyToolTestRequest:
      type: object
      additionalProperties: false
      description: Legacy webhook test migration boundary only. Cannot test a workflow-owned tool or use a workflow-owned agent as override authority.
      properties:
        agent_id: { type: string, format: uuid }
        arguments: { type: object, additionalProperties: { type: string } }
        context:
          type: object
          additionalProperties: false
          properties:
            call_id: { type: [string, 'null'], format: uuid }
            call_direction: { type: [string, 'null'], enum: [inbound, outbound, web_call, null] }
            caller_number: { type: [string, 'null'] }
            callee_number: { type: [string, 'null'] }
            call_metadata: { type: object, additionalProperties: true }
            call_variables: { type: object, additionalProperties: true }

    ToolExtractionParameter:
      type: object
      required: [name, description]
      properties:
        name:
          type: string
          example: callerName
          description: "Flat argument name exposed to the voice model; normalized to camelCase."
        description:
          type: string
          example: "The caller's full name"
          description: "Natural-language guidance for extracting this value from the conversation."
        required:
          type: boolean
          default: true
          description: "Whether the value must be collected before the tool can run. Omitted means true."

    ToolTestFailure:
      allOf:
        - { $ref: "#/components/schemas/Error" }
        - type: object
          required:
            - error
            - code
            - details
            - status_code
            - downstream_response
            - payload_sent
            - delivery_id
          properties:
            error: { type: string, const: "Webhook delivery failed" }
            code:
              type: string
              enum: [DOWNSTREAM_HTTP_ERROR, WEBHOOK_NETWORK_ERROR, WEBHOOK_TIMEOUT]
            details: { type: string }
            status_code:
              type: [integer, "null"]
              description: "Downstream HTTP status, or null when no response was received."
            downstream_response:
              type: string
              description: "Sanitized, length-capped downstream response preview. Configured request headers are never returned."
            payload_sent:
              type: object
              additionalProperties: true
            delivery_id:
              type: [string, "null"]
              format: uuid
    TranscriptEntry:
      type: object
      description: "A single turn in a call transcript."
      required: [role, text, start, end]
      properties:
        role:
          type: string
          enum: [agent, user, voicemail]
          description: >
            Who is speaking.
            `agent` — the AI agent.
            `user` — the live human on the call.
            `voicemail` — pre-recorded audio from the callee's answering machine, carrier voicemail greeting, or IVR menu. Treat these entries as non-conversational: they represent the callee's voicemail system, not anything the person actually said. When any entry has `role: "voicemail"`, the call's disposition will be `Voicemail`.
        text: { type: string, description: "Transcribed speech in the call's original language." }
        start: { type: integer, description: "Milliseconds from recording_started_at, the call's recording's first sample. Where recording_started_at is null (a browser call, or an older call recorded before the field was added), from the start of the recording, which on a browser call begins once the browser has connected, shortly after answered_at." }
        end: { type: integer, description: "Milliseconds from recording_started_at, as start is." }

    CallUsageLeg:
      type: object
      description: |
        What one engine leg of a call consumed, as the provider reported it.
        A call that ran on one engine has one leg; a call that spanned several provider sessions still
        has one leg, with the whole call's usage summed onto it. It is a measurement of consumption,
        not a price: what the call was charged is `cost_cents` on the call.
      required: [engine, model]
      properties:
        engine: { type: string, description: "The voice engine this leg ran on.", nullable: true }
        model: { type: string, description: "The voice model.", nullable: true }
        service: { type: string, nullable: true, description: "The provider service that ran the leg, such as gemini or openai." }
        sessions: { type: integer, description: "How many provider sessions the call spanned on this engine." }
        input_tokens: { type: integer, nullable: true, description: "Total prompt tokens. Null for an engine billed by time rather than by token." }
        output_tokens: { type: integer, nullable: true, description: "Total completion tokens. Null for an engine billed by time." }
        audio_input_tokens: { type: integer, nullable: true, description: "Prompt tokens that were the caller speaking." }
        text_input_tokens: { type: integer, nullable: true, description: "Prompt tokens that were text: instructions, history, tool definitions." }
        audio_output_tokens: { type: integer, nullable: true, description: "Completion tokens that were the agent speaking." }
        text_output_tokens: { type: integer, nullable: true, description: "Completion tokens that were text." }
        cached_input_tokens: { type: integer, nullable: true, description: "Prompt tokens served from the provider's cache." }
        audio_seconds: { type: number, nullable: true, description: "Seconds of live audio, for an engine billed by time." }
        backend_model: { type: string, nullable: true, description: "The reasoning model behind the voice, where the engine has one." }
        recorded_at: { type: string, format: date-time, nullable: true, description: "When the reading was stored." }

    CallEvent:
      type: object
      description: |
        A single event from a call's lifecycle, returned in the `events[]` array of `GET /calls/{id}`.
        Events are ordered by `timestamp` ascending. Use these for granular timing analysis and — for
        flow agents — reconstructing the decision path through the graph.
      required: [type, timestamp, data]
      properties:
        type:
          type: string
          enum:
            - call_initiated
            - websocket_connected
            - webrtc_connected
            - llm_started
            - llm_response_started
            - llm_response_ended
            - tool_called
            - tool_response
            - transcription_user
            - transcription_agent
            - call_ended
            - call_ended_idle
            - call_ended_max_duration
            - error
            - stall_recovery
            - transfer_started
            - transfer_answered
            - transfer_failed
            - flow_started
            - flow_node_entered
            - flow_eval_decision
            - flow_tool_result
            - flow_start_advance_degraded
            - call_ended_continuous_speech
          description: |
            Event type. Standard call lifecycle events fire on every call.

            - `call_ended` — the call finished, and this is the last event on it. `data`:
              `{end_reason, barge_ins, barge_ins_within_250ms_of_bot_audio_onset}`.
              `end_reason` says what ended it — `pipeline_finished` (the ordinary end),
              `caller_idle_timeout`, `continuous_speech_detected`, `max_duration_exceeded`,
              `transferred`, `farewell_without_end_tool`, `operator_ended` (an operator
              ended a call that was found stuck), or a short failure reason.
              `barge_ins` counts the times the caller spoke over the agent while it was
              actually talking and stopped it mid-sentence. It is one per agent utterance
              that was cut into, however many times the call's detectors announced the same
              intrusion, and a caller who waits for the agent to finish before answering is
              not counted at all — so `0` on a call with plenty of conversation means the
              agent was never talked over, not that barge-in was off.
              `barge_ins_within_250ms_of_bot_audio_onset` is the subset of those that landed
              in the first quarter-second of the agent's own audio. On a phone line with no
              echo cancellation a stop that early is more likely to be the agent hearing
              itself than a caller cutting in, so a high share of the total is a signal to
              look at the line rather than at the caller. Both are counts and never negative.
              Calls placed before 2026-09-16 carry neither key.
              It also carries timing numbers in milliseconds, measured on the voice server
              (a close estimate of what the caller heard, not an exact figure):
              `turn_gap_ms_p50`, `turn_gap_ms_p90` and `turn_gap_ms_max` are the gap between
              the caller finishing a sentence and the agent's first audible sound, over
              `turn_gap_ms_n` replies (at most 64); a call where the agent never replied
              carries none of them. `first_audio_ms` is the time from the call's pipeline
              starting to the agent first being heard (`null` if never). `tool_wait_ms_sum`
              and `tool_wait_ms_max` are the total and longest wait on tools (`0` without
              tool calls). `host_cpu_stall_ms`, `loop_lag_p99_ms`, `loop_lag_max_ms` and
              `mean_concurrency` describe the whole voice server while the call ran (processor
              wait, scheduler lateness, calls running at once), shared by every call at the
              same time; the first three are `null` when not measurable.
              `resolve_bot_workflow_ms`, `workflow_session_start_ms`, `prompt_build_ms`,
              `claim_media_admission_ms` and `record_media_receipt_ms` are the time spent on
              named steps before the call started (the last two on browser calls only; the
              workflow ones on workflow agents). `residual_wait_ms` (phone calls) is how long
              the agent still waited for its voice connection once everything else was ready.
              `smart_turn_predict_count`, `smart_turn_predict_wall_ms` and `smart_turn_cpu_ms`
              appear where the end-of-turn decision runs on the server: decisions made, their
              total duration, and the server processor time spent meanwhile (server-wide).
              Keys that do not apply to a call are absent. Calls placed before 2026-10-04 carry
              none of these.
              Four more describe silences: `longest_agent_silence_ms` is the longest stretch,
              after the agent first spoke, with nothing audible from it (to the end of the call
              if it never spoke again); `longest_dead_air_ms` is the longest stretch with neither
              the agent nor the caller audible, after either was first heard; `socket_drops` counts
              the times the agent's connection to its voice model failed (and the agent tried to
              rebuild it) during the call (a planned reconnect, such as the voice model's own
              scheduled session rotation or a fresh session the platform asked for, is not
              counted);
              `recovery_fired` counts the times the agent was prompted to speak because it owed
              the caller an answer and stayed quiet (for example after such a drop).
              "Audible" means at speech level, so a line carrying only faint sound counts as
              silent. Calls placed before 2026-10-21 carry none of these four, and the
              `turn_gap_ms_*` keys before then could count faint sound as the agent's reply.
            - `call_ended_continuous_speech` — the call was ended because the other side
              talked without a pause for longer than the agent's continuous-speech limit
              (usually an answering machine or a recording). `data`:
              `{reason, max_continuous_speech_secs}`. `call_ended` follows with `end_reason`
              `continuous_speech_detected`.
            - `flow_start_advance_degraded` — on a flow agent, the first step's instructions
              could not be delivered to the agent's voice session when the call moved off the
              start step, so the agent may have answered the first turn without them. `data`:
              `{step_id, seam, reason}`.
            - `stall_recovery` — the agent fell silent mid-turn and was nudged back
              into the conversation. `data`: `{timeout_s, recovery_count}`. Only logged
              once the nudge has provably reached the live session, so each event is a
              recovery that actually happened.
            - `transfer_started` — a transfer was accepted and the caller was handed off.
              `data`: `{destination, source, command_id, ...}`. `destination` is the
              E.164 number dialled, or, for a hand-off to a SIP address, that address
              without any credentials (on an extension call, the extension), with
              `method` set to `"sip_refer"` (`"extension_dialback"` on an extension
              call); `source` is `"prompt_tool"` | `"flow_node"` | `"workflow"`;
              `command_id` is the idempotency key for the handoff. The originating
              context is merged in: `tool_name` for prompt agents, `from_flow_node` for
              flow agents. Accepted is not answered — the destination can still be busy
              or not pick up, in which case the call ends shortly after with no
              conversation on the other end. For a SIP-address destination this is
              different: on a SIP REFER hand-off the event is recorded only once your
              phone system confirms it took the call over, together with
              `transfer_answered`, and a request your phone system refuses or never
              answers records `transfer_failed` instead. On an extension call (a
              dial-back, below) it is recorded when the carrier accepts the request,
              before anyone has answered.
            - `transfer_answered` — the transfer reached the other side. `data`:
              `{destination, source, ...}`; for a SIP-address destination `method`
              is `"sip_refer"` and this event means your phone system accepted the
              hand-off.
            - On a call that arrived over an
              [extension endpoint](/concepts/sip-trunks#register-as-an-extension), a
              transfer is a new call placed through your extension: `transfer_started`
              carries `method` `"extension_dialback"` once the carrier has accepted the
              request. No SIP REFER is sent. From then on the agent is out of the call,
              as in a transfer to a phone number, and Yappr stays on it until one side
              hangs up. If the new call is rejected or not answered within about 25
              seconds, `transfer_failed` records `NOT_CONNECTED` (the disconnect
              reason says why: "Transfer rejected", "Transfer destination busy",
              "Transfer destination unreachable" or "Transfer not answered", and the
              default "Transfer failed" when the carrier gives no reason) and the
              call **ends**: the caller is not handed back to the
              agent. If nothing has connected about 85 seconds after the request, Yappr
              ends the call too ("Transfer never connected"). Only a request the carrier
              refuses outright keeps the caller with the agent.
            - On an extension call whose transfer uses a transfer code (the one set on the
              extension endpoint, `register.pbx_feature_code`, or the transfer's own with
              `transfer_method` `"pbx_feature_code"`), Yappr first sends your phone system the
              code as key presses. Nothing is recorded when the code is sent. When your phone
              system then ends Yappr's leg within about 12 seconds, that is the hand-off:
              `transfer_started` with `method` `"pbx_feature_code"` is recorded at that
              moment, the call ends there and is marked transferred, no transfer minutes
              are billed, and no `transfer_answered` is recorded (Yappr can't see whether
              the person answered). Otherwise the attempt ends in exactly one of these:
              - The leg is still up after the wait: Yappr places the dial-back above,
                which records the only `transfer_started`, with `method`
                `"extension_dialback"` and `fallback_from` `"pbx_feature_code"`.
              - The leg ends in a way that can't be your phone system taking the call
                (sooner than the key presses take to play, after the carrier refused
                them, or ended from Yappr's side): an ordinary end of the call, with
                `transfer_failed` `CALL_ENDED` (`method` `"pbx_feature_code"`) and no
                `transfer_started`. A caller who hangs up later in the wait can't be
                told apart from the hand-off and is recorded as transferred.
              - The agent's session ends during the wait and nothing takes the call:
                Yappr hangs up and records `transfer_failed` `FEATURE_CODE_NOT_TAKEN`
                with no `transfer_started`; the call is `completed` with the
                `disconnect_reason` "Transfer failed".
              With a hang-up time (`pbx_feature_code_hangup_after_secs`, on the endpoint or
              the transfer: a code that starts an attended transfer), your phone system does
              not end Yappr's leg: Yappr hangs up that
              many seconds after the code, and that hang-up is the hand-off, recorded
              exactly as above (`transfer_started` with `method` `"pbx_feature_code"`,
              the call marked transferred, no transfer minutes). There is no dial-back. A
              leg that ends before Yappr hangs up is read as above. If the end of the leg
              is not reported after Yappr's hang-up (a late carrier event, or a hang-up
              command that failed even when sent twice), Yappr hangs up once more and
              still records the hand-off, ending the call at its first hang-up: an
              attended code never records `FEATURE_CODE_NOT_TAKEN`.
            - `transfer_failed` — a transfer was requested but never started, and the
              caller stays with the agent (except `REFER_FAILED`, `REFER_NO_RESULT` and
              `FEATURE_CODE_NOT_TAKEN`, where the call ends, and `NOT_CONNECTED`, below). `data`: `{error_code, destination, source, ...}`,
              with the same originating context as above. `error_code` is one of
              `NO_DESTINATION`, `INVALID_DESTINATION`, `NO_TELEPHONY_LEG`, `NO_API_KEY`,
              `ALREADY_TRANSFERRING`, `CALL_ENDED`, `CARRIER_REJECTED`,
              `CARRIER_UNREACHABLE`, `UNAVAILABLE_ON_SIP_TRUNK`,
              `REFER_ONLY_ON_SIP_TRUNK`, `REFER_FAILED`, `REFER_NO_RESULT`,
              `FEATURE_CODE_NOT_TAKEN` (a transfer code nobody took after the agent's
              session ended, above: the call ends).
              `UNAVAILABLE_ON_SIP_TRUNK`: the call came in over a
              [SIP trunk](/concepts/sip-trunks#transfers) or an
              [extension endpoint](/concepts/sip-trunks#register-as-an-extension) and the transfer destination
              is a phone number, which a trunk call can't dial, so nothing was
              dialled. Use a SIP address as the destination instead.
              `REFER_ONLY_ON_SIP_TRUNK`: the destination is a SIP address but the call
              did not arrive over a SIP trunk or an extension endpoint, and the agent
              keeps helping the caller.
              `REFER_FAILED`: your phone system reported that it could not place the
              new call (busy, not found or declined). `REFER_NO_RESULT`: nothing came
              back in time, because your phone system refused or ignored the request
              or the new call was not answered within about nine seconds. After
              `REFER_FAILED` and `REFER_NO_RESULT` the call ends: the request had
              already been sent to your phone system, and Yappr cannot take the caller
              back. A call that ends this way is `completed` with no `transferred_at`,
              and its `disconnect_reason` reads "Transfer refused by the phone system"
              (`REFER_FAILED`) or "Transfer failed" (`REFER_NO_RESULT`). This is the
              only per-call record of a soft transfer failure.

              One further `error_code`, `NOT_CONNECTED`, is reported later rather than at
              request time: the handoff was accepted by the carrier but the destination
              never answered — busy, rejected, or rang out. Its `data` carries
              `hangup_cause` and `transferred_at` as well, and `source` is
              `"carrier_webhook"`. A call can therefore emit `transfer_started` and then
              `transfer_failed`; that pair means the caller was handed off and nobody
              picked up.

            `flow_*` events fire only on flow agents (`agent.type='flow'`):

            - `flow_started` — flow controller began. `data`: `{agent_id, first_step_id, agent_speaks_first}`
            - `flow_node_entered` — a node was entered. `data`: `{step_id, type, name, reason}`
              The `reason` string explains routing (e.g. "tool success", "tool custom: Already booked",
              "eval: agreed_to_demo", "tool error: HTTP 500: ...").
            - `flow_eval_decision` — the model picked a transition for a conversation node.
              `data`: `{step_id, decision, valid, target_step_id, reason, reasoning, turn_id}`.
              `step_id` — node the decision was made FROM.
              `decision` — the transition id picked (or `"stay"`).
              `valid` — boolean; whether the picked transition was accepted.
              `target_step_id` — destination step id when `valid` is true; null otherwise.
              `reason` — short status/error explanation (e.g. why the pick was rejected).
              `reasoning` — the model's short justification for the pick.
              `turn_id` — monotonic counter for the conversation turn the decision ran on.
            - `flow_tool_result` — a tool_call node finished (or an integration_call node: the native
              Google Calendar/Gmail step, on an agent that still has one during its 30-day notice
              period, or on calls placed before the retirement). `data`: `{step_id,
              kind, status, tool_name, tool_id, provider, integration_id, action, args, arg_sources,
              response_preview, raw_response_preview, error, duration_ms}`. `kind` is `"tool_call"` |
              `"integration_call"`. `status` is `"success"` | `"error"`.
              `response_preview` is the JSON-stringified result the LLM saw (truncated to 50KB).
              `raw_response_preview` is present when the provider did server-side post-processing
              for the LLM (currently: Google Calendar wall-clock conversion); it carries the
              untouched provider response for audit. Null when `result` and `raw` are identical.
        timestamp: { type: string, format: date-time }
        data:
          type: object
          description: |
            Event-specific payload. Shape depends on `type`.

            Auth-related headers in `tool_called` events are redacted as `[REDACTED]`.

            `tool_called`, `tool_response` and `flow_tool_result` carry `exchange_id` when the tool
            call has a full record: it matches `tool_calls[].id` and the timeline row's `exchange_id`.

            Payloads carry call facts only. Platform implementation details — the
            provider's own model and voice identifiers, and telephony
            carrier handles — are not exposed and may change at any time without
            notice. `llm_started.voice` is reported as the same friendly voice
            name used by the Agent resource, never an internal identifier. The
            model an agent is set to is on the Agent resource (`model`, `resolved_model`).

    ToolCallPair:
      type: object
      description: |
        A single tool invocation (request + response) extracted from the call's event stream. The list
        contains both prompt-mode webhook tools and flow-mode tool/integration_call fires, in firing order.
        `kind` is the discriminator:

        - `webhook_tool` — prompt-mode agents with a tool list. Built from paired `tool_called` /
          `tool_response` events. The `request` envelope carries the full HTTP request (method, url,
          headers, body).
        - `tool_call` — flow-mode `tool_call` node fired. Built from one `flow_tool_result` event.
          `request` carries just `body` (the resolved args dict); HTTP details aren't meaningful here.
        - `integration_call` — the native Google Calendar/Gmail step fired. The step is retired: only
          an agent that still has one during its 30-day notice period emits this value, and calls
          placed before the retirement still carry it. Same `request.body`-only shape as `tool_call`; sibling fields
          `provider`, `action` and `integration_id` record which credential and method ran at the
          time. New integrations appear as `tool_call`.

        For flow agents prefer `flow_trace.steps[].tool_call` — same data, inlined per visited step.

        **The full record.** From 21 October 2026 each tool call also carries what it really sent
        and got back, on every engine (workflow agents, prompt and flow agents, connected apps,
        transfers and End): `agent_asked` (the arguments the agent gave), `request` (method, the
        full URL with its query, every header sent, the body), `response` (status, every header,
        the body, `error_code`, `timed_out`) and `agent_was_told` (what the agent got back); a
        before-call step instead carries `given_to_agent` (how its result reached the agent). Each
        body is kept up to 16 KB; past that it is cut (`truncated: true`) and `body_bytes` gives
        the full size. Anything that looks like a credential is `"[REDACTED]"` and its place is
        listed in `masked`: `Authorization`, `Cookie`, `X-Api-Key` and `Set-Cookie` headers; any
        header, query parameter or JSON key whose name contains token, secret, password,
        signature, credential, api key, access key, private key or session id, ends in `key` or
        `session` (`signing_key`, `license_key`, `user_session`; not `public_key`, `primary_key`,
        `foreign_key`, `sort_key`, `partition_key`), or is exactly `key`, `auth`, `sig`, `otp`,
        `jwt`, `pwd` or `bearer`; values that look like a bearer token, an API key or a JWT; a
        URL's user and password; and every value configured on the tool's headers. Your own data
        in a payload (names, numbers, emails) is not hidden. Bodies are kept for 90 days; after
        that `details_expired` is true and they are null, while the rest stays. A call made before
        records began has none of these fields and reads exactly as it always did.

        **Where it went needs a tools scope.** For a Make or Zapier hook the URL's path is the
        credential: a key with neither `tools:read` nor `tools:update` reads every `request.url`
        as its scheme and host alone, the entry carries `destination_path_withheld: true`, and the
        raw `tool_called` entries of `events` are cut the same way (`data.url`,
        `data.destination_path_withheld`). The same rule as `GET /deliveries/{id}`.
      required: [tool_name, timestamp, kind]
      properties:
        id:
          type: string
          description: >
            The record's id: present only when the call has a full record of this tool call. Matches
            `exchange_id` on the timeline row and on the tool's events.
        engine:
          type: string
          enum: [workflow, prompt, flow]
          description: Which engine ran it. Present with `id`.
        tool_type:
          type: string
          enum: [http, app, transfer, end]
          description: >
            What kind of tool it was (`kind` above says which event stream it came from). Present
            with `id`.
        status:
          type: string
          enum: [succeeded, failed, timeout, unreachable, refused, not_sent, unknown]
          description: >
            How it ended: `timeout` (no answer in time; it may still have acted), `unreachable`
            (nothing answered at the address), `refused` (turned away before anything was sent:
            an address that is not allowed, arguments the tool rejected, or a transfer on a call
            with no phone line), `not_sent` (a test run that held the request back), `unknown`
            (it is not confirmed whether it happened - the request went out and its answer could
            not be used, and the agent was told it cannot confirm it). Present with `id`.
        started_at:
          type: string
          format: date-time
          nullable: true
          description: When the request left (for transfer and End, when the agent asked). Present with `id`.
        agent_asked:
          nullable: true
          description: The arguments the agent called the tool with. Null when no agent asked (a before- or after-call step). Present with `id`.
        agent_was_told:
          nullable: true
          description: >
            What the agent got back, as it got it. Null when no agent asked (a before- or after-call
            step: what a before-call step gave the agent is `given_to_agent`). Present with `id`.
        given_to_agent:
          type: object
          description: >
            A before-call step only (`lane: before` on its timeline row): how its result reached the live
            agent, recorded as the agent's instructions were built. `via` empty means the agent was not
            given it, and `reason` says why. Absent when nothing was recorded (a call placed before
            Yappr began recording it, or one older than 90 days), which does not mean it was not
            given.
          required: [via, places, result, bytes, truncated, reason]
          properties:
            via:
              type: array
              items: { type: string, enum: [instructions_block, placeholder, seed] }
              description: >
                How the agent got it: `instructions_block` (the result is in the prepared-data section of its
                instructions, as the conversation started), `placeholder` (a `{{before.<step>.<field>}}` you
                wrote got its value, see `places`), `seed` (the step results every workflow conversation
                starts with, in the agent's starting context). Empty when the agent was not given it.
            places:
              type: array
              description: >
                Each `{{before.<step>.<field>}}` reference to this step in text the agent read: its global
                instructions (`global`), a conversation step's instructions (`step:<node id>`) or the opening
                line (`greeting`). `step:<node id>` places are listed for the steps the document lets the
                agent reach: every step in a flexible document, only the steps the conversation reached in a
                strict one.
              items:
                type: object
                required: [where, token, filled]
                properties:
                  where: { type: string, description: "`global`, `step:<node id>` or `greeting`." }
                  token: { type: string, nullable: true, description: "The reference as written, e.g. `{{before.today.busy|none}}`." }
                  filled: { type: boolean, nullable: true, description: "True when it got the step's value; false when its fallback (or nothing) was used." }
            result:
              nullable: true
              description: >
                The result as the agent's instructions carry it: credentials, diagnostics and private
                references left out, long values cut to fit (16 KB at most). Present also when the
                instructions did not carry it (`reason`), so you can see what the agent missed. Null when
                the step had no result.
            bytes:
              type: integer
              description: Bytes of the result the instructions placed; 0 when they placed none.
            truncated:
              type: boolean
              description: True when the agent saw a value that was cut to fit.
            reason:
              type: string
              nullable: true
              description: >
                Why the instructions did not carry the result, null when they did: `no_result_released` (the
                step gave no result, or an empty one), `budget` (the prepared-data section is limited to
                32 KB and this step's result did not fit), `not_in_instructions`, the step's own failure code
                (`http_timeout`), or a code for a result that cannot be shown (`evidence_format_unsupported`).
        masked:
          type: array
          items: { type: string }
          description: >
            Where a value was replaced by `"[REDACTED]"`, as paths (`request.headers.Authorization`,
            `request.url.query.api_key`, `response.body.access_token`), at most 64. Present with `id`.
        details_expired:
          type: boolean
          description: >
            True once the record is older than 90 days: `agent_asked`, `agent_was_told` and the
            record's request and response details are gone; the summary stays. Present with `id`.
        destination_path_withheld:
          type: boolean
          enum: [true]
          description: >
            Present (true) when `request.url` was cut to `scheme://host`: the key has neither
            `tools:read` nor `tools:update`, and a hook's path can be its credential. Absent when the
            URL is whole.
        tool_name: { type: string }
        timestamp: { type: string, format: date-time }
        kind:
          type: string
          enum: [webhook_tool, tool_call, integration_call]
        node:
          type: object
          nullable: true
          description: "Flow node identity. Set when `kind` is `tool_call` or `integration_call`; null for `webhook_tool`."
          properties:
            id: { type: string }
            name: { type: string }
            type: { type: string, enum: [tool_call, integration_call] }
        tool_id: { type: string, format: uuid, nullable: true, description: "Set when `kind` is `webhook_tool` or `tool_call`. References the tools table row." }
        provider: { type: string, nullable: true, description: "Set when `kind=integration_call` (e.g. `google_calendar`)." }
        action: { type: string, nullable: true, description: "Set when `kind=integration_call` (e.g. `create_event`)." }
        integration_id: { type: string, format: uuid, nullable: true, description: "Set when `kind=integration_call`. Connected credential used for this fire." }
        arg_sources:
          type: object
          nullable: true
          additionalProperties: { type: string, enum: [literal, ai_extract] }
          description: "Per-arg provenance map. Set for flow-mode rows; null for `webhook_tool`."
        request:
          type: object
          required: [body]
          properties:
            method: { type: string, nullable: true, description: "Set only when `kind=webhook_tool`." }
            url: { type: string, nullable: true, description: "Set when `kind=webhook_tool`, and on every tool call with a full record (`id`) that sent one. `scheme://host` alone for a key without `tools:read` or `tools:update` (`destination_path_withheld`)." }
            headers:
              type: object
              additionalProperties: { type: string }
              description: "Set only when `kind=webhook_tool`, and on every tool call with a full record (`id`): every header sent. Auth-related keys (Authorization, tokens, API keys) are redacted as `[REDACTED]`."
            body: { description: "Rendered request body / args dict sent to the tool or integration. With a full record (`id`): the body exactly as sent (16 KB at most).", nullable: true }
            target: { type: string, nullable: true, description: "With a full record, when there is no URL to show: a connected app's `App · Action` (`Google Calendar · Find event`) or a transfer's destination." }
            body_format: { type: string, enum: [json, text, empty, binary], description: "With a full record: `json` when `body` is JSON; `text` when it is not, or was cut." }
            body_bytes: { type: integer, nullable: true, description: "With a full record: the body's full size in bytes, also when it was cut." }
            truncated: { type: boolean, description: "With a full record: true when `body` is only the first 16 KB." }
        response:
          type: object
          nullable: true
          properties:
            success: { type: boolean, nullable: true }
            response_preview: { type: string, nullable: true, description: "JSON-stringified result the LLM saw, truncated to ~50KB." }
            raw_response_preview: { type: string, nullable: true, description: "Provider's untouched payload, present only when the LLM-facing sanitized view differs from the raw API response (e.g. Google Calendar dateTime stripping). Useful for audit." }
            error: { type: string, nullable: true }
            duration_ms: { type: integer, nullable: true }
            status: { type: integer, nullable: true, description: "With a full record: the HTTP status the endpoint answered with; null when nothing answered." }
            headers:
              type: object
              additionalProperties: { type: string }
              description: "With a full record: every header of the answer; `Set-Cookie` and anything that looks like a credential is `[REDACTED]`."
            body: { nullable: true, description: "With a full record: what the endpoint answered (16 KB at most), also when it refused or did not answer JSON." }
            body_format: { type: string, enum: [json, text, empty, binary] }
            body_bytes: { type: integer, nullable: true, description: "The answer's full size in bytes; null when nothing came back." }
            truncated: { type: boolean }
            timed_out: { type: boolean, description: "With a full record: true when no answer came in time." }
            error_code: { type: string, nullable: true, description: "With a full record: the code for what went wrong, from the `error_code` list of `GET /deliveries` (for example `downstream_http_error`, `http_timeout`, `http_network_error`, `invalid_json_response`). Null when it worked." }

    ToolExchangeRequest:
      type: object
      description: >
        A request exactly as it left: method, the full URL with its query (a URL's user and password
        removed), every header sent and the body, each secret replaced by `"[REDACTED]"`.
      properties:
        method: { type: string, nullable: true, example: POST }
        url: { type: string, nullable: true, example: "https://crm.example.com/contacts?api_key=[REDACTED]&phone=%2B972501234567" }
        target: { type: string, nullable: true, description: "When there is no URL to show: a connected app's `App · Action`, or a transfer's destination." }
        headers:
          type: object
          additionalProperties: { type: string }
          example: { Authorization: "[REDACTED]", Accept: application/json }
        body: { nullable: true, description: "JSON when `body_format` is `json`, else text." }
        body_format: { type: string, enum: [json, text, empty, binary] }
        body_bytes: { type: integer, nullable: true, description: "The full size in bytes, also when it was cut." }
        truncated: { type: boolean, description: True when `body` is only the first 16 KB. }

    ToolExchangeResponse:
      type: object
      description: >
        The answer exactly as it came back: status, every header and the body (16 KB at most), each
        secret replaced by `"[REDACTED]"`.
      properties:
        status: { type: integer, nullable: true, description: Null when nothing answered. }
        headers:
          type: object
          additionalProperties: { type: string }
        body: { nullable: true }
        body_format: { type: string, enum: [json, text, empty, binary] }
        body_bytes: { type: integer, nullable: true }
        truncated: { type: boolean }
        error: { type: string, nullable: true, description: "The code for what went wrong (`downstream_http_error`, `http_timeout`, `http_network_error`, `url_resolves_private`). Null when it worked." }
        timed_out: { type: boolean }

    FlowTrace:
      type: object
      description: |
        Structured view of a flow agent's path through its graph during the call. Built from the
        underlying `flow_started` / `flow_node_entered` / `flow_eval_decision` / `flow_tool_result` events.

        **Use this instead of `events[]` and `tool_calls[]` when working with flow-agent calls** — it gives
        you the ordered list of nodes visited, why each transition happened, the eval-LLM's reasoning at
        each conversation node, and the tool I/O inlined per step.
      required: [started_at, steps]
      properties:
        started_at: { type: string, format: date-time, description: "When the flow controller started for this call." }
        agent_speaks_first:
          type: boolean
          nullable: true
          description: "Whether the start node had agent_speaks_first=true (bot greeted before listening)."
        first_step_id:
          type: string
          nullable: true
          description: "Step id the flow began at. Always the start node, but useful for sanity checks."
        steps:
          type: array
          description: "Ordered list of node visits. Same step_id may appear multiple times if the flow loops back."
          items: { $ref: "#/components/schemas/FlowTraceStep" }

    FlowTraceStep:
      type: object
      description: "One node visit during a flow-agent call. Includes routing reason and any associated tool I/O or eval decisions."
      required: [step_id, step_type, entered_at, eval_decisions]
      properties:
        step_id: { type: string, description: "Node id from flow_config." }
        step_type:
          type: string
          enum: [start, conversation, tool_call, integration_call, transfer, end, unknown]
          description: "Node type. Drives which sibling fields are populated. `unknown` is reserved for events emitted by older runtimes that didn't tag node_kind. `integration_call` is historical only — the native calendar/mailbox step is retired and no new call produces it."
        step_name: { type: string, nullable: true }
        entered_at: { type: string, format: date-time }
        reason:
          type: string
          nullable: true
          description: |
            Why this step was entered. Examples:
            `"start"` — flow began.
            `"eval: <transition_label>"` — the eval LLM picked this transition from a conversation node.
            `"tool success"` — fell through after no custom branch matched.
            `"tool custom: <branch_label>"` — a custom JSONPath branch matched.
            `"tool error: <error_message>"` — tool failed.
        tool_call:
          nullable: true
          description: "Present when `step_type` is `tool_call` or `integration_call`. Carries the actual args sent and response received, with `kind` discriminating the two."
          allOf:
            - $ref: "#/components/schemas/FlowTraceToolCall"
        eval_decisions:
          type: array
          description: |
            Eval-LLM decisions made while at this step. Empty for non-conversation nodes; can have multiple
            entries when the user took several turns before transitioning. The last entry's `decision` is what fired
            (`"stay"` decisions don't advance; the final non-`"stay"` decision moved to the next step).
          items: { $ref: "#/components/schemas/FlowTraceEvalDecision" }

    FlowTraceToolCall:
      type: object
      description: "The actual tool call that fired during a `tool_call` or `integration_call` step."
      required: [kind, tool_name, status]
      properties:
        kind:
          type: string
          enum: [tool_call, integration_call]
          description: "Discriminator. `tool_call` → webhook/system tool referenced by `tool_id`. `integration_call` is historical only: it identified the retired native calendar/mailbox step by `provider`+`action`+`integration_id`, and appears on calls placed before that step was retired."
        tool_id: { type: string, format: uuid, nullable: true, description: "Set when `kind=tool_call`. Reference to the tools table row." }
        provider: { type: string, nullable: true, description: "Set when `kind=integration_call`. e.g. `google_calendar`, `gmail`." }
        action: { type: string, nullable: true, description: "Set when `kind=integration_call`. e.g. `create_event`, `send_email`." }
        integration_id: { type: string, format: uuid, nullable: true, description: "Set when `kind=integration_call`. Connected credential id used for this fire." }
        tool_name: { type: string }
        status:
          type: string
          enum: [success, error]
          description: "Set by the dispatcher. Hard failures (timeout, redirect or other non-2xx status, missing tool) → error. Any 2xx → success, even with a soft-fail body."
        args:
          type: object
          nullable: true
          description: "The actual payload sent to the tool / integration. For tool_call steps the merge order is standard metadata, then static_parameters, then resolved extraction_parameters (later values win collisions); for integration_call steps this is the resolved args_template (literal / ai_extract values, with all {{node.arg}} and {{metadata.key}} tokens interpolated)."
        arg_sources:
          type: object
          nullable: true
          additionalProperties: { type: string, enum: [literal, ai_extract] }
          description: "Per-arg provenance map: which mode each arg came from. `literal` includes both plain literals and template-interpolated literals (i.e. `{{check.start_time}}`-style cross-node tokens). Null for prompt-mode webhook tools."
        response_preview:
          type: string
          nullable: true
          description: "JSON-stringified response body the LLM saw, truncated to ~50KB. Truncation is byte-based — long responses may end mid-token."
        raw_response_preview:
          type: string
          nullable: true
          description: "Provider's untouched payload, present only when the LLM-facing sanitized view differs from the raw API response. Today this fires for Google Calendar `create_event` / `list_events` / `check_availability` (the runtime strips ISO timezone offsets and reshapes timezone metadata so Live can reliably parse times). Use this field for audit; the agent never sees it. Null when the provider returned a response that didn't need post-processing."
        error: { type: string, nullable: true }
        duration_ms: { type: integer, nullable: true }

    FlowTraceEvalDecision:
      type: object
      description: "One eval-LLM decision at a conversation node."
      required: [decision, decided_at]
      properties:
        turn_id:
          type: integer
          nullable: true
          description: "Monotonic counter — same value as the conversation turn the eval was running on."
        decision:
          type: string
          description: |
            Either a transition id (taken — flow advances) or `"stay"` (no transition; user takes another turn at this node).
        reasoning: { type: string, nullable: true, description: "The eval LLM's short justification." }
        decided_at: { type: string, format: date-time }

    PhoneNumber:
      type: object
      properties:
        id: { type: string, format: uuid }
        number: { type: string, example: "+972551234567"  }
        friendly_name: { type: string, nullable: true }
        provider:
          type: string
          description: |
            Where the number comes from: `telnyx` for a number bought from Yappr,
            `external` for a number in your own Telnyx account, added to a
            [carrier account](/api-reference/carrier-accounts/add-number), `phone_system`
            for the business number of an extension endpoint that calls out through your own
            phone system ([register.outbound](/concepts/sip-trunks#outbound-calls-through-the-extension)):
            switched on and off on that endpoint, never released here, no rent, and no calls in
            (they reach the endpoint's own agent; `inbound_agent_id` and `inbound_split` are
            refused with `422 FIELD_NOT_ALLOWED`).
          enum: [telnyx, external, phone_system]
        status: { type: string, enum: [active, pending_requirements, suspended] }
        is_active: { type: boolean }
        inbound_agent_id: { type: string, format: uuid, nullable: true }
        outbound_agent_id: { type: string, format: uuid, nullable: true }
        inbound_split:
          nullable: true
          description: |
            The A/B test on incoming calls, or `null` when the number always
            answers with `inbound_agent_id`.

            **`percent` is the share of calls that go to the SECOND agent**
            (`agent_id` below). The agent already bound to the number takes the
            rest — a `percent` of 30 means 70% of calls to `inbound_agent_id`
            and 30% to the second agent. The dashboard slider shows the first
            agent's share and stores `100 - slider`; the API always states the
            second agent's.

            Which agent answers a given call is fixed for that call: it is
            derived from the carrier's call id, so a redelivered webhook and
            every internal re-derivation agree. If the second agent cannot take
            calls (inactive, an unpublished workflow, or a different kind of
            agent from the first), the call goes to the first agent and the call
            record says so.
          allOf:
            - $ref: "#/components/schemas/AgentSplit"
        outbound_split:
          nullable: true
          description: |
            The same thing for calls this number places: when `POST /calls` is
            sent without an `agent_id`, this split decides which agent calls.
            An explicit `agent_id` always wins. BYOC SIP endpoints carry no
            split.
          allOf:
            - $ref: "#/components/schemas/AgentSplit"
        sip_inbound_configured:
          type: boolean
          description: |
            Whether carrier-side routing for incoming calls is in place. On an
            `external` number: whether the number is on Yappr's Call Control App
            in your Telnyx account, so calls to it reach Yappr.
        sip_outbound_configured: { type: boolean }
        country_code: { type: string, nullable: true }
        monthly_cost:
          type: number
          nullable: true
          description: >
            The number's monthly price in cents, before VAT, as listed for it. Whether Yappr
            charges it is `rent`. Null on an `external` number.
        rent:
          description: >
            Whether Yappr charges the number's monthly rent. Returned by GET /phone-numbers and
            PATCH /phone-numbers/{id}; not part of a number embedded elsewhere (a campaign's
            from_phone_number, a carrier account's numbers).
          allOf:
            - $ref: "#/components/schemas/PhoneNumberRent"
        next_renewal_at:
          type: string
          format: date-time
          nullable: true
          description: >
            When the rent next renews: monthly, on the day and time the subscription started (the
            last day of a shorter month). Null when `rent.included`, and when the number's release is
            scheduled (`scheduled_release_at`): it does not renew. Returned by GET /phone-numbers
            and PATCH /phone-numbers/{id}.
        scheduled_release_at:
          type: string
          format: date-time
          nullable: true
          description: >
            When a number released with POST /phone-numbers/{id}/release goes: the end of the period
            already paid for. Until then the number keeps working as before;
            POST /phone-numbers/{id}/keep undoes the release. Null when no release is scheduled.
        created_at: { type: string, format: date-time }
        phone_system:
          type: object
          nullable: true
          description: |
            The extension endpoint a `phone_system` number calls out through; `null` on every
            other number.
          properties:
            sip_endpoint_id: { type: string, format: uuid }
            sip_endpoint_name: { type: [string, "null"] }
        carrier_account:
          type: object
          nullable: true
          description: |
            The Telnyx account an `external` number calls through. `null` on numbers
            bought from Yappr, and for a key without `carrier_accounts:read` —
            `provider: external` still says the number is your own. On a number a
            [disconnect](/api-reference/carrier-accounts/delete) kept for its history,
            `status` is `disconnected`: `GET /carrier-accounts/{id}` no longer finds the
            account, and its `id` is what removes the number
            (`DELETE /carrier-accounts/{id}/numbers/{phone_number_id}`).
          properties:
            id: { type: string, format: uuid }
            name: { type: string }
            provider: { type: string, enum: [telnyx] }
            status: { type: string, enum: [untested, active, paused, disconnected] }
        carrier_state:
          type: object
          nullable: true
          description: |
            Where an `external` number stands in your Telnyx account. `null` on
            numbers bought from Yappr, and for a key without
            `carrier_accounts:read`. `state` is the first of these that applies:
            `telnyx_gone` (Telnyx no longer lists it: a sync found it gone, since
            `removed_at`; it cannot call), `removed` (Removed from this workspace: a
            disconnect kept it for its call history, since `removed_at`; it may still be
            in your Telnyx account, it cannot call, and `carrier_account.status` is
            `disconnected`), `not_ready` (Telnyx lists it
            with a status other than `active`), `paused` (its carrier account is
            paused), `blocked` (not configured, and a setting in `blockers` stops
            Yappr answering it), `not_configured` (calls out work; calls in still
            ring at `current_connection_name` until you configure it with
            `POST /carrier-accounts/{id}/numbers/{phone_number_id}/configure`) and
            `ready` (calls to it are answered here).
          properties:
            state: { type: string, enum: [ready, not_configured, blocked, paused, not_ready, telnyx_gone, removed] }
            telnyx_status:
              type: string
              nullable: true
              description: The number's status in Telnyx, as of the last sync. `null` until a sync has read it.
            current_connection_name:
              type: string
              nullable: true
              description: The connection the number is on in Telnyx, as of the last sync. `null` when it is on none.
            previous_connection_name:
              type: string
              nullable: true
              description: The connection the number goes back to when you stop answering it here. `null` when it had none.
            blockers:
              type: array
              items: { type: string, enum: [forwarding_always, translated_number, tech_prefix] }
              description: |
                Telnyx settings that stop Yappr answering the number. Configure is refused while any is on.
                `forwarding_always`: Telnyx forwards every call to it elsewhere. `translated_number`: Telnyx
                delivers its calls as another number. `tech_prefix`: Telnyx adds a tech prefix to the dialled
                number, so Yappr could not match it. Change the setting in Telnyx, then sync.
            notes:
              type: array
              items: { type: string, enum: [number_recording, forwarding_on_failure, call_screening, off_by_owner, off_until_active, off_while_paused] }
              description: |
                Telnyx voice settings on the number that configuring leaves on (recording, forwarding when
                unanswered, call screening). They stay as they are when you configure it. When the number is
                switched off (`is_active` is `false`, so it places no calls), one more note says why:
                `off_by_owner` (an owner or admin switched it off; it stays off until one switches it on),
                `off_until_active` (Telnyx did not list it as active; the sync switches it on once Telnyx does)
                or `off_while_paused` (its carrier account paused; turning the account back on switches it on).
            removed_at:
              type: string
              format: date-time
              nullable: true
              description: When the number went out of use here, on a `telnyx_gone` or `removed` number. `null` on every other.
        ownership_verified_at:
          type: string
          format: date-time
          nullable: true
          description: |
            When your Telnyx API key last proved that this `external` number is an
            active number in your account. `null` means that is not proven now: Telnyx
            no longer lists it as active, or its account was disconnected. The number is
            not callable until a [test](/api-reference/carrier-accounts/test) or a sync
            finds it again. Always `null` on numbers bought from Yappr.

    PhoneNumberRent:
      type: object
      required: [included, reason, monthly_price_cents, last_charged_at]
      properties:
        included:
          type: boolean
          description: >
            False when a rent was charged for the number in the last 40 days (each renewal is a
            phone_number row on GET /billing/transactions); true when none was.
        reason:
          type: string
          nullable: true
          enum: [own_carrier, not_charged, no_subscription, phone_system, null]
          description: >
            Why the rent is included: `own_carrier` - a number in your own Telnyx account, whose
            rent Telnyx bills you; `not_charged` - a monthly subscription is on record but has
            charged nothing in the last 40 days; `no_subscription` - a Yappr number with no
            subscription (one Yappr set up for you); `phone_system` - a number that calls out
            through your own phone system, which Yappr does not rent. Null when the rent is charged.
        monthly_price_cents:
          type: integer
          nullable: true
          description: The monthly rent before VAT, paid by card. Null when included.
        last_charged_at:
          type: string
          format: date-time
          nullable: true
          description: The newest rent charge in the last 40 days, or null.

    PhoneNumberRelease:
      type: object
      required: [phone_number_id, released, release_at]
      properties:
        phone_number_id: { type: string, format: uuid }
        released:
          type: boolean
          description: >
            True when the number is gone now: released at the carrier, its subscription ended, and
            no longer listed by GET /phone-numbers. False when it is still yours: kept until
            `release_at`, or kept for good.
        release_at:
          type: string
          format: date-time
          nullable: true
          description: >
            When a scheduled release happens: the end of the period already paid for. The number
            keeps working until then. Null when the number was released now, or no release is
            scheduled. GET /phone-numbers lists the same date as `scheduled_release_at`.

    BillingRates:
      type: object
      required: [currency, voice_models, default_rate_per_minute_cents, browser_call_rate_per_minute_cents, after_transfer_rate_per_minute_cents, ai_training_multiplier]
      properties:
        currency: { type: string, example: usd }
        voice_models:
          type: array
          description: One entry per voice model, ordered by `model`. Each carries the workspace's phone-call price.
          items: { $ref: "#/components/schemas/VoiceModelRate" }
        default_rate_per_minute_cents:
          type: integer
          nullable: true
          description: What a minute of a phone call costs this workspace, whatever the model. Credits (cents) per minute.
          example: 30
        browser_call_rate_per_minute_cents:
          type: integer
          nullable: true
          description: This workspace's price per minute for browser calls - your test calls, shared links and browser calls started through the API.
          example: 10
        after_transfer_rate_per_minute_cents:
          type: integer
          nullable: true
          description: This workspace's price per minute for the part of a call after it is passed to a person.
          example: 25
        ai_training_multiplier:
          type: integer
          enum: [1, 2]
          description: "2 on a workspace that opted out of AI training, 1 otherwise. The price charged per minute is the listed price times this."
    BillingDetails:
      type: object
      required: [name, email, address, tax_id, language]
      properties:
        name: { type: string, description: "The business or legal name printed on invoices.", example: Acme Ltd }
        email:
          type: string
          format: email
          nullable: true
          description: Where invoices are emailed. Defaults to the workspace owner's email.
          example: billing@acme.example
        address:
          nullable: true
          allOf: [{ $ref: "#/components/schemas/BillingAddress" }]
        tax_id:
          nullable: true
          allOf: [{ $ref: "#/components/schemas/BillingTaxId" }]
        language:
          type: string
          enum: [en, he]
          description: "The workspace language. Invoices are issued in English; he gives day-first dates."
    BillingDetailsUpdate:
      type: object
      minProperties: 1
      additionalProperties: false
      properties:
        name: { type: string, minLength: 1, maxLength: 256, nullable: true, description: "null resets it to the workspace name." }
        email: { type: string, format: email, maxLength: 254, nullable: true, description: "null resets it to the workspace owner's email." }
        address:
          nullable: true
          description: null removes the address.
          allOf: [{ $ref: "#/components/schemas/BillingAddress" }]
        tax_id:
          nullable: true
          description: null removes the tax ID. A new one replaces the old.
          allOf: [{ $ref: "#/components/schemas/BillingTaxId" }]
        language: { type: string, enum: [en, he] }
    BillingAddress:
      type: object
      required: [line1, country]
      additionalProperties: false
      properties:
        line1: { type: string, minLength: 1, maxLength: 200, example: 1 Example St }
        line2: { type: string, maxLength: 200, nullable: true }
        city: { type: string, maxLength: 200, nullable: true, example: Tel Aviv }
        state: { type: string, maxLength: 200, nullable: true }
        postal_code: { type: string, maxLength: 200, nullable: true, example: "6100000" }
        country: { type: string, pattern: "^[A-Z]{2}$", description: "Two-letter country code (ISO 3166-1 alpha-2).", example: IL }
    BillingTaxId:
      type: object
      required: [type, value]
      additionalProperties: false
      properties:
        type:
          type: string
          enum: [il_vat, eu_vat, gb_vat, us_ein, ca_bn, au_abn, ch_vat, no_vat, ae_trn, za_vat]
          description: il_vat for an Israeli VAT or company number.
        value: { type: string, minLength: 1, maxLength: 64, description: "Spaces are removed.", example: "000012345" }
    Invoice:
      type: object
      required: [number, kind, description, phone_number, status, issued_at, paid_at, currency, net_cents, vat_cents, total_cents, refunded_cents, lines, view_url, pdf_url]
      properties:
        number: { type: string, nullable: true, example: 4F2A9C1B-0007 }
        kind:
          type: string
          enum: [credits_top_up, auto_top_up, phone_number, other]
          description: What the payment was for.
        description: { type: string, nullable: true, description: "The first line's description, in English.", example: Credits top-up }
        phone_number: { type: string, nullable: true, description: "The number, for kind phone_number only.", example: "+972501234567" }
        status: { type: string, enum: [paid, open, uncollectible] }
        issued_at: { type: string, format: date-time }
        paid_at: { type: string, format: date-time, nullable: true }
        currency: { type: string, example: usd }
        net_cents: { type: integer, example: 5000 }
        vat_cents: { type: integer, example: 900 }
        total_cents: { type: integer, example: 5900 }
        refunded_cents: { type: integer, example: 0 }
        lines:
          type: array
          items: { $ref: "#/components/schemas/InvoiceLine" }
        view_url: { type: string, format: uri, nullable: true, description: The invoice's own page. }
        pdf_url: { type: string, format: uri, nullable: true, description: Downloads the invoice as a PDF. }
    InvoiceLine:
      type: object
      required: [description, quantity, unit_amount_cents, amount_cents]
      properties:
        description: { type: string, nullable: true, example: Credits top-up }
        quantity: { type: integer, example: 1 }
        unit_amount_cents: { type: integer, example: 5000 }
        amount_cents: { type: integer, example: 5000 }
    InvoiceList:
      type: object
      required: [invoices, next_cursor]
      properties:
        invoices:
          type: array
          items: { $ref: "#/components/schemas/Invoice" }
        next_cursor: { type: string, nullable: true, description: "Send as cursor for the next page; null when there is none." }
    VoiceModelRate:
      type: object
      required: [model, name, rate_per_minute_cents, effective_from]
      properties:
        model: { type: string, description: "The model id, the same value an agent carries as `model`.", example: gpt-live }
        name: { type: string, example: GPT Live }
        rate_per_minute_cents: { type: integer, description: "Credits (cents) per minute of a phone call on this model for this workspace, before the AI-training multiplier.", example: 30 }
        effective_from:
          type: string
          format: date-time
          nullable: true
          description: "Always null: prices are set per workspace, and when a price took effect is not recorded."
    UpcomingCharge:
      type: object
      properties:
        type: { type: string, enum: [phone_number_rent, auto_top_up] }
        phone_number_id: { type: string, format: uuid, nullable: true }
        phone_number: { type: string, nullable: true }
        amount_cents: { type: integer, nullable: true, description: "Before VAT." }
        due_at:
          type: string
          format: date-time
          nullable: true
          description: When a number's rent renews. Null for an automatic top-up, which is due when the balance falls.
        when_balance_below_cents:
          type: integer
          nullable: true
          description: An automatic top-up's trigger. Null on a number's rent.

    CarrierAccount:
      type: object
      description: |
        Your own Telnyx account, connected so agents can call from the numbers you
        own there. Yappr places each call **on your Call Control App, with your API
        key**, so the call runs on your Telnyx account and Telnyx bills you for it.
        The API key is write-only: no response ever contains it.
      properties:
        id: { type: string, format: uuid }
        name: { type: string, example: "Main Telnyx account" }
        provider: { type: string, enum: [telnyx] }
        api_key_last4: { type: string, example: "9XyZ", description: "The last four characters of the saved key. The key itself is never returned." }
        api_key_updated_at: { type: string, format: date-time }
        public_key_set: { type: boolean, description: "Whether you saved your account's public key." }
        signature_verified:
          type: boolean
          description: |
            `true` once a call event from Telnyx verified against your public key.
            From then on every event for this account must carry a valid signature.
        connection:
          type: object
          nullable: true
          description: The Call Control App calls go through. `null` until you [choose one](/api-reference/carrier-accounts/connection).
          properties:
            id: { type: string, example: "2890000000000000001" }
            created_by_yappr: { type: boolean }
            outbound_voice_profile_id: { type: string, nullable: true }
        status:
          type: string
          enum: [untested, active, paused]
          description: |
            `untested` — no call answered on your app since you connected or turned it
            back on. `active` — the last answered call ran on your app. `paused` —
            Telnyx refused your key, your app is gone, or Telnyx refused 5 calls in a
            row; every number on the account is paused (`is_active: false`) until you
            fix the cause and call [reactivate](/api-reference/carrier-accounts/reactivate).
        pause_reason:
          type: string
          nullable: true
          enum: [key_rejected, connection_invalid, carrier_rejections]
        last_error:
          type: object
          nullable: true
          properties:
            code:
              type: string
              description: "`carrier_rejected`, `key_rejected`, `connection_invalid`, `public_key_mismatch`, `connection_mismatch`, `inbound_on_app` or `number_released`."
            sip_code:
              type: string
              nullable: true
              example: "403"
              description: "The SIP code Telnyx ended a ringing call with (`401`, `403`, `407`, …). `null` when Telnyx refused over its API instead: the call itself before it rang, a command on it, or a test."
            at: { type: string, format: date-time, nullable: true }
        last_success_at: { type: string, format: date-time, nullable: true }
        last_tested_at: { type: string, format: date-time, nullable: true }
        last_synced_at:
          type: string
          format: date-time
          nullable: true
          description: When the last [sync](/api-reference/carrier-accounts/sync) of the account's numbers finished. `null` before the first one.
        last_sync_error:
          type: string
          nullable: true
          enum: [key_rejected, telnyx_refused_request, too_many_numbers, telnyx_unavailable, sync_failed, null]
          description: |
            Why the last sync failed: Telnyx refused the key (`key_rejected`) or this
            request (`telnyx_refused_request`), the account holds more than 10,000
            numbers (`too_many_numbers`), Telnyx did not answer (`telnyx_unavailable`),
            or Yappr could not save the result (`sync_failed`). A failed sync changes no
            number. `null` when the last sync worked, and before the first.
        sync:
          allOf:
            - { $ref: "#/components/schemas/CarrierSyncSummary" }
          nullable: true
          description: What the last sync found (the run so far while `in_progress`). `null` before the first one.
        sync_status: { $ref: "#/components/schemas/CarrierSyncStatus" }
        numbers:
          type: array
          items: { $ref: "#/components/schemas/PhoneNumber" }
        removed_numbers:
          type: array
          description: |
            Numbers [removed from this workspace](/api-reference/carrier-accounts/remove-number),
            newest first. A removed number leaves `numbers` and GET /phone-numbers; this keeps
            the `id` it had - the id its past calls and charges were recorded under - with its
            number and when it was removed.
          items:
            type: object
            required: [id, number, removed_at]
            properties:
              id: { type: string, format: uuid, description: The phone number id it had. }
              number: { type: string, description: E.164. }
              friendly_name: { type: [string, 'null'] }
              telnyx_number_id: { type: [string, 'null'], description: Its id in your Telnyx account. }
              created_at: { type: [string, 'null'], format: date-time, description: When it was added to this workspace. }
              removed_at: { type: string, format: date-time }
        webhook_url:
          type: string
          format: uri
          description: |
            The exact webhook URL a Call Control App you made must use. It carries a
            secret for your account: treat it like a password. Returned only to API keys
            with `carrier_accounts:manage` (and workspace owners and admins), and only
            when it is needed: on [connect](/api-reference/carrier-accounts/create) (at
            the top level), on an [update](/api-reference/carrier-accounts/update) that
            sends a new `api_key`, and on [GET /carrier-accounts/{id}](/api-reference/carrier-accounts/get)
            with `?include=webhook_url`. Every other read leaves it out.
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    CarrierRestoreResult:
      type: object
      description: |
        What `?restore_routing=true` did before a disconnect: each configured number put
        back on the connection it was on, up to 50 a request. Present only when you sent
        `restore_routing=true`.
      properties:
        ok: { type: boolean, description: "Every configured number is back on its own connection." }
        restored:
          type: array
          items:
            type: object
            properties:
              id: { type: string, format: uuid }
              number: { type: string, example: "+972501234567" }
              changed: { type: boolean, description: "`false` when the number had already left the app in Telnyx: nothing was sent." }
        failed:
          type: array
          items:
            type: object
            properties:
              id: { type: string, format: uuid }
              number: { type: string }
              code:
                type: string
                enum: [PREVIOUS_ROUTING_GONE, RESTORE_NOT_APPLIED, TELNYX_KEY_REJECTED, TELNYX_REFUSED_CHANGE, TELNYX_REFUSED_REQUEST, TELNYX_UNAVAILABLE, NUMBER_REMOVED_FROM_TELNYX, CONNECTION_REQUIRED, CARRIER_ACCOUNT_NOT_FOUND]
                description: What stop answering here would answer for it. After `TELNYX_KEY_REJECTED` the rest of the batch is not tried.
        remaining: { type: integer, description: "Configured numbers this request did not reach. Above 0, send the same request again." }

    CarrierSyncStatus:
      type: object
      description: |
        Whether and why this account's numbers are synced, read without running a sync.
        Yappr syncs an account by itself once a day, and when you choose its Call
        Control App, test it or turn it back on.
      properties:
        enabled:
          type: boolean
          description: |
            Yappr syncs this account by itself. `false` before a Call Control App is
            chosen, while the account is paused by a refused key or a missing app (the
            daily run skips it until you turn it back on), and on Yappr's own account.
        ready:
          type: boolean
          nullable: true
          description: |
            Yappr has switched number syncing on. While it is `false`, no account is
            synced and [POST /sync](/api-reference/carrier-accounts/sync) answers `503
            SYNC_NOT_READY`; your numbers stay as they are and calls from them still
            work. `null` when Yappr cannot say right now.
        last_synced_at: { type: string, format: date-time, nullable: true, description: "The account's `last_synced_at`." }
        last_sync_error:
          type: string
          nullable: true
          description: The account's `last_sync_error`.
        reason:
          type: string
          nullable: true
          enum: [connection_required, account_paused, sync_not_ready, never_synced, key_rejected, telnyx_refused_request, too_many_numbers, telnyx_unavailable, sync_failed, null]
          description: |
            Why the numbers are not synced, the first that applies; `null` when the last
            sync worked and nothing stands in the way.
            - `connection_required` — choose the [Call Control App](/api-reference/carrier-accounts/connection) first (`enabled: false`).
            - `account_paused` — [turn it back on](/api-reference/carrier-accounts/reactivate) (`enabled: false`).
            - `sync_not_ready` — Yappr has not switched number syncing on yet (`ready: false`). Nothing to do; it starts by itself.
            - `key_rejected`, `telnyx_refused_request`, `too_many_numbers`, `telnyx_unavailable`, `sync_failed` — the last sync failed (`last_sync_error`).
            - `never_synced` — on, and not run yet: the next test, Turn back on, or the daily run does it, or call POST /sync.
      example: { enabled: true, ready: true, last_synced_at: "2026-09-23T03:17:04Z", last_sync_error: null, reason: null }

    CarrierSyncSummary:
      type: object
      description: |
        What a [sync](/api-reference/carrier-accounts/sync) found: the run's counts
        (the run so far while `in_progress`). The counts mean what they mean on the
        sync's own answer; it never carries the read position.
      properties:
        in_progress:
          type: boolean
          description: "`true` while a large account is still being read in parts: the next part is read when you sync again, or by Yappr within 5 minutes."
        run_started_at: { type: string, format: date-time, nullable: true }
        completed_at: { type: string, format: date-time, nullable: true, description: "`null` while `in_progress`." }
        seen: { type: integer }
        added: { type: integer }
        updated: { type: integer }
        removed: { type: integer }
        not_ready: { type: integer }
        held_elsewhere: { type: integer }
        held_elsewhere_numbers: { type: array, items: { type: string } }
        held_elsewhere_details:
          type: array
          items:
            type: object
            properties:
              phone_number: { type: string }
              reason: { type: string, enum: [other_workspace, own_removed, pending_release] }
        excluded:
          type: array
          items:
            type: object
            properties:
              phone_number: { type: string }
              telnyx_number_id: { type: string, nullable: true }
        batch: { type: object, description: "The counts of the last part read.", additionalProperties: { type: integer } }
        run: { type: object, description: "The counts of the whole run so far.", additionalProperties: { type: integer } }

    CarrierAccountCreate:
      type: object
      required: [name, api_key]
      properties:
        name: { type: string, minLength: 1, maxLength: 100, example: "Main Telnyx account" }
        api_key:
          type: string
          format: password
          writeOnly: true
          description: |
            A Telnyx API key created just for Yappr (Account Settings → API Keys).
            Checked with Telnyx before anything is saved; stored encrypted; never returned.
        public_key:
          type: string
          writeOnly: true
          description: Your account's public key (Keys & Credentials → Public Key), 44 characters of base64. Recommended.
          example: "3MYsSvZbhKUP9VZ1pRgGNlDtJGbNkFMhTqwPjGEgUoY="

    CarrierAccountUpdate:
      type: object
      description: |
        Send at least one field. A new `api_key` must be from the same Telnyx account
        (it must see the account's Call Control App). A new `public_key` is verified
        again on the next call event.
      properties:
        name: { type: string, minLength: 1, maxLength: 100 }
        api_key: { type: string, format: password, writeOnly: true }
        public_key: { type: string, writeOnly: true }

    CarrierConnectionSetup:
      type: object
      description: Send exactly one of `create` or `connection_id`.
      properties:
        create:
          type: object
          description: Yappr creates a Call Control App named "Yappr outbound" in your account, on this outbound voice profile.
          required: [outbound_voice_profile_id]
          properties:
            outbound_voice_profile_id: { type: string, example: "2890000000000000002" }
        connection_id:
          type: string
          description: |
            A Call Control App you made just for Yappr. Its webhook URL must be exactly
            this account's `webhook_url`, it must have an outbound voice profile, and it
            must be switched on.

    CarrierAccountTestResult:
      type: object
      properties:
        ok: { type: boolean, description: "True when the key, the app and the outbound voice profile all pass. Numbers are reported, not required." }
        checks:
          type: array
          items:
            type: object
            properties:
              name: { type: string, enum: [api_key, connection, outbound_voice_profile, numbers] }
              ok: { type: boolean }
              detail: { type: string }
        telnyx:
          type: object
          nullable: true
          description: What your key can see. `null` when Telnyx refused the key.
          properties:
            connections:
              type: array
              items:
                type: object
                properties:
                  id: { type: string }
                  name: { type: string }
                  active: { type: boolean }
                  outbound_voice_profile_id: { type: string, nullable: true }
            outbound_voice_profiles:
              type: array
              items:
                type: object
                properties:
                  id: { type: string }
                  name: { type: string }
                  enabled: { type: boolean }
                  allowed_destinations: { type: array, items: { type: string } }
                  daily_spend_limit: { type: string, nullable: true }
                  daily_spend_limit_enabled: { type: boolean }
                  channel_limit: { type: integer, nullable: true }
        numbers:
          type: array
          items:
            type: object
            properties:
              id: { type: string, format: uuid }
              number: { type: string }
              verified: { type: boolean }

    ExternalNumberCreate:
      type: object
      required: [number]
      properties:
        number:
          type: string
          example: "+972501234567"
          description: An active number in the Telnyx account you connected, in E.164 (`+972` numbers are 12 or 13 characters). Yappr checks it with your key before adding it.
        friendly_name: { type: string, maxLength: 100, nullable: true }
        outbound_agent_id:
          type: string
          format: uuid
          nullable: true
          description: The agent that calls from this number by default.

    AgentSplit:
      type: object
      description: |
        A two-agent A/B test. `percent` is the share of calls the second agent
        (`agent_id`) takes; the resource's existing agent takes `100 - percent`.
      properties:
        agent_id:
          type: string
          format: uuid
          description: The second agent — the one being tested against the existing one.
        percent:
          type: integer
          minimum: 1
          maximum: 99
          description: Share of calls routed to `agent_id`, 1–99.
      required: [agent_id, percent]

    SipEndpoint:
      type: object
      description: |
        A SIP endpoint lets your own phone system (a PBX, a contact-center
        platform or a SIP provider) send calls to a Yappr agent, without a Yappr
        phone number. It comes in three kinds, set by `auth_mode` when you create it:

        - `credentials`: **username and password**. Yappr issues a SIP username
          and password. Your phone system sends calls to `sip.telnyx.eu` or
          `sip.telnyx.com` with them, dialling any number or extension, and the
          endpoint's agent answers every call. A call with a wrong username or
          password is refused before it reaches Yappr. The password is returned
          only once: by [create](/api-reference/sip-endpoints/create) and by
          [rotate-password](/api-reference/sip-endpoints/rotate-password). Any agent
          of the workspace can answer, including one that runs a workflow: see
          `inbound_agent_id`.
        - `uri`: **SIP address only**. Your phone system dials the endpoint's
          `sip_uri`, with no username or password. It works with any agent,
          including one that runs a workflow. The address is the secret:
          anyone who has it can call the agent, on your workspace's minutes, so
          treat it like an API key. Calls are not filtered by source address. To
          replace it, create a new endpoint, point your phone system at it, then
          delete the old one; calls to a deleted or switched-off endpoint are
          refused before they are answered.
        - `register`: **register as an extension**. For a hosted phone system that
          only gives you an extension account (server, username, password).
          Yappr registers to it like a softphone and the agent answers the calls
          the system routes to that extension. Yappr does not keep or return the
          extension's password. You send it to create the endpoint and again
          whenever it changes on your phone system, because Yappr's carrier holds
          it to keep the extension registered and to place transfers.
          The `register` object carries the settings and the registration
          `status`. See [Register as an extension](/concepts/sip-trunks#register-as-an-extension).

        `sip_username` and `sip_connection` appear on username-and-password
        trunks only, `max_concurrent_calls` on trunks and extension endpoints,
        `register` on extension endpoints only, and `allowed_source_ips` on SIP
        address endpoints only. List, get and update never return a password. A SIP
        address endpoint's `slug` and `sip_uri` are its credential, and a trunk's
        `sip_username` is half of its, so list and get return them only to a key
        that also holds `sip_endpoints:manage`; with `sip_endpoints:read` alone
        (the Read-only preset) they are `null`. The
        [setup guide](/concepts/sip-trunks) covers the phone system side.
      required: [id, name, auth_mode, slug, sip_uri, inbound_agent_id, is_active, last_call_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        name: { type: string, example: "Main office PBX" }
        auth_mode:
          type: string
          enum: [credentials, uri, register]
          description: |
            `credentials`: a username-and-password trunk. `uri`: a SIP address
            endpoint. `register`: an extension on your phone system that Yappr
            registers to. Endpoints created before username-and-password trunks
            existed are `uri`. It cannot be changed after the endpoint is created.
          example: credentials
        slug:
          type: [string, "null"]
          description: |
            SIP address endpoints: the user part of `sip_uri`, made of a readable
            prefix (the `slug` you sent, or one derived from `name`), a hyphen and
            24 random characters, about 120 bits that cannot be guessed. `null` on
            username-and-password trunks, and on list and get for a key without
            `sip_endpoints:manage`.
          example: "after-hours-bz3r3mtypuwuw8tpdw3x392s"
        sip_uri:
          type: [string, "null"]
          description: |
            SIP address endpoints: the full address your phone system dials, over
            UDP or TCP (port 5060) or TLS (port 5061). Over UDP or TCP it crosses
            the network in clear text, so use TLS where your phone system supports
            it. No username and no password: anyone who has it can call the agent,
            so treat it like an API key. `null` on username-and-password trunks, and
            on list and get for a key without `sip_endpoints:manage`.
          example: "sip:after-hours-bz3r3mtypuwuw8tpdw3x392s@yappr-byoc.sip.telnyx.com"
        sip_username:
          type: [string, "null"]
          description: |
            Username-and-password trunks only. The SIP username your phone system
            authenticates with: `yp` followed by 14 lowercase letters and digits.
            It never changes; only the password can be replaced. `null` on list
            and get for a key without `sip_endpoints:manage`, and on a trunk whose
            setup never finished (switched off; delete it and create a new one).
          example: "yp4k7d2m9x1q8w3z"
        max_concurrent_calls:
          type: integer
          minimum: 1
          maximum: 8
          description: |
            Username-and-password trunks and extension endpoints only. The most
            calls the endpoint takes at once, counting calls ringing and in
            progress: 1 to 8, 2 unless you changed it. The next call is refused (a trunk
            answers SIP `486 Busy Here`; an extension endpoint's call is refused
            without a specified code).
          example: 5
        sip_connection: { $ref: "#/components/schemas/SipConnection" }
        register: { $ref: "#/components/schemas/SipRegister" }
        inbound_agent_id:
          type: string
          format: uuid
          description: |
            The agent that answers every call on this endpoint. Any agent of
            the workspace can answer, including one that runs a workflow, on
            either kind of endpoint. Publish the workflow first: calls to an agent
            that is switched off, or whose workflow has never been published, are
            refused (on a trunk with SIP `603 Decline`).
        is_active:
          type: boolean
          description: |
            `false` switches the endpoint off: new calls are refused before they
            are answered until you switch it back on (a trunk or SIP address
            endpoint answers SIP `603 Decline`; on an extension endpoint `register.status`
            reads `disabled` and Yappr refuses new calls, but your phone system is not
            told). Calls in progress are not affected.
        last_call_at: { type: [string, "null"], format: date-time }
        allowed_source_ips:
          type: [array, "null"]
          deprecated: true
          description: |
            SIP address endpoints only. Source addresses recorded with the
            endpoint, for your records. **Calls are not checked against this
            list**: a call to the address is answered wherever it comes from.
            `null` when none is recorded.
          items: { type: string, example: "203.0.113.0/24" }
        created_at: { type: string, format: date-time }
        updated_at:
          type: string
          format: date-time
          description: When the endpoint last changed, a new password included.
        password_rotated_at:
          type: [string, "null"]
          format: date-time
          description: |
            Username-and-password trunks only (absent on a SIP address endpoint):
            when [rotate-password](/api-reference/sip-endpoints/rotate-password)
            last issued a new password. `null` until the first one.
          example: null

    SipConnection:
      type: object
      description: |
        Username-and-password trunks only: where and how your phone system sends
        the trunk's calls. It is the same on every trunk. The
        [setup guide](/concepts/sip-trunks) explains each value.
      required: [server, alternate_servers, transports, registration]
      properties:
        server:
          type: string
          description: |
            The SIP server (proxy, registrar) your phone system sends the trunk's
            calls to, for example in the US. From Israel or Europe,
            `sip.telnyx.eu` (in `alternate_servers`) is closer. If your system
            asks for a realm, the realm is the server name you send to.
          example: "sip.telnyx.com"
        alternate_servers:
          type: array
          items: { type: string }
          description: |
            Other servers that take the same username and password: use
            `sip.telnyx.eu` from Israel or Europe, and any other one for a backup
            route. The realm follows the server you use.
          example: ["sip.telnyx.eu", "sip.telnyx.me"]
        transports:
          type: array
          description: |
            The transports and ports to send the trunk's calls on. TLS (1.2 or
            1.3) is recommended. Telnyx publishes the same transports and ports
            for the alternate servers.
          items:
            type: object
            required: [protocol, port]
            properties:
              protocol: { type: string, enum: [tls, tcp, udp] }
              port: { type: integer }
              recommended:
                type: boolean
                description: "`true` on the transport to prefer. Absent on the others."
          example:
            - { protocol: tls, port: 5061, recommended: true }
            - { protocol: tcp, port: 5060 }
            - { protocol: udp, port: 5060 }
        registration:
          type: string
          enum: [optional]
          description: |
            `optional`: each call is checked against the username and password, so
            registering is not what lets a call in. Keep the connection open
            anyway: over TLS or TCP, register the trunk or send keep-alives (SIP
            `OPTIONS`) every 30 seconds or less; over UDP behind NAT or a
            firewall, send keep-alives every 30 seconds or less even if your
            system registers, because a registration is refreshed only every few
            minutes. Otherwise the agent's hang-up may not reach your phone system
            ([setup guide](/concepts/sip-trunks#register-or-send-keep-alives)).

    SipRegister:
      type: object
      description: |
        Extension endpoints (`auth_mode: "register"`) only: the extension Yappr
        registers as, and how that registration is going. It is absent on the
        other kinds. The extension's password is never returned.
        [Register as an extension](/concepts/sip-trunks#register-as-an-extension)
        explains what to set up on your phone system.
      required: [server, username, auth_username, transport, region, pbx_feature_code, pbx_feature_code_hangup_after_secs, status, status_detail, status_checked_at, last_activity_at, last_activity_kind, allow_list]
      properties:
        server:
          type: string
          description: The registrar of your phone system, as `host` or `host:port`.
          example: "sip1.example.net:5060"
        username:
          type: string
          description: |
            The extension, as your phone system calls it. It must be unique across
            Yappr: two endpoints can't register the same one.
          example: "101"
        auth_username:
          type: [string, "null"]
          description: The login user when your phone system uses a different one from the extension. `null` when it is the extension.
        transport:
          type: string
          enum: [udp, tcp, tls]
          description: |
            How Yappr registers. UDP is the transport that was tested end to end;
            TCP and TLS are accepted.
        region:
          type: string
          enum: [middle_east, europe]
          description: |
            Which Telnyx region registers and carries the media. It decides the
            address `allow_list` names: `192.76.120.75` for `middle_east` (observed
            live) and `192.76.120.72` for `europe` (this address comes from the
            carrier's documentation and was not observed live; read it from
            `allow_list`).
        pbx_feature_code:
          type: [string, "null"]
          description: |
            Your phone system's in-call transfer code, which every transfer to an extension on this
            endpoint's calls uses, on every agent
            ([how it works](/concepts/sip-trunks#hand-the-call-to-your-phone-system-with-its-transfer-code)).
            `null` when none is set: transfers then place a new call through the extension.
          example: "##"
        pbx_feature_code_hangup_after_secs:
          type: [integer, "null"]
          description: |
            Set when the code starts an attended transfer that your phone system completes when
            Yappr hangs up: Yappr hangs up this many seconds after the code. `null` when Yappr
            waits for your phone system to take the call.
          example: 4
        outbound:
          $ref: "#/components/schemas/SipRegisterOutbound"
        status:
          type: string
          enum: [pending, registering, registered, failed, disabled, unknown]
          description: |
            `pending`: just created or changed, and the carrier is still applying
            it (a few minutes). An endpoint that is switched off and still reads
            `pending` after a failed create never finished its setup: delete it and
            create it again. `registering`: the carrier is trying. `registered`:
            your phone system accepted the registration. `failed`: it did not;
            `status_detail` says why. `disabled`: the endpoint is switched off and Yappr refuses new calls; your phone system is not told.
            `unknown`: Yappr cannot read the state. When `status_detail` is set, the
            carrier's status could not be read for a while and the state was still
            `pending` or `registering` after the ten minutes a change takes: this does
            not mean the extension is not working or that calls are stopped. Do not
            treat it as `failed`; read the endpoint again later, and the first read
            that succeeds replaces it. While it is unknown for that reason, a call that
            went through the extension in the last 24 hours, after its settings last
            changed, is in `last_activity_at`: evidence that a call went through, not a
            registration. **`registered` does not
            prove the endpoint works end to end**: send a test call, and a test
            transfer if the agent transfers.
          example: registered
        status_detail:
          type: [string, "null"]
          description: |
            A short plain reason while `status` is `registering`, `failed` or `unknown`, for
            example "authentication failed (check the extension and password)",
            "your phone system is not reachable", "no answer from your phone
            system" or "extension username already in use" (the name is
            registered through Yappr, possibly by an endpoint deleted earlier: a deleted
            extension endpoint can keep its name for hours). On `unknown` it reads
            "we cannot read the carrier status right now (this does not mean the
            extension is not working)". `null` otherwise.
        status_checked_at:
          type: [string, "null"]
          format: date-time
          description: |
            When Yappr last asked the carrier for the status. It moves on every
            attempt, including one the carrier did not answer, so on its own it does not
            show that the status is current: while the carrier cannot be read it is the
            time of the last attempt, not of the last answer, and a stored `registered`
            keeps showing a fresh time though no read has succeeded. A read is refreshed
            when it is older than 15 seconds; a list of more than 20 extension
            endpoints serves stored values, so check this time.
        last_activity_at:
          type: [string, "null"]
          format: date-time
          description: |
            Evidence that a call went through the extension while Yappr cannot read the
            carrier's status: when the newest such call began, if that was in the last 24
            hours and after the extension's settings last changed (a call before a change
            went through the old settings). Set only while `status` is `unknown` and
            `status_detail` says the carrier's status cannot be read; `null` in every other
            state, and when no call qualifies. A call from your phone system counts once it
            reaches Yappr through the extension, answered or not. An outbound call counts
            only when it was answered: one nobody picked up, or one your phone system
            refused, is not evidence. It is never a registration: do not read it as
            `registered`, and `status` and `status_detail` are exactly what they would be
            without it. Only `GET /sip-endpoints/{id}` and the list fill it: the answers to
            create and update carry `null`, so read the endpoint again.
          example: "2026-11-10T15:25:00Z"
        last_activity_kind:
          type: [string, "null"]
          enum: [inbound_call, outbound_call, null]
          description: |
            What `last_activity_at` is: `inbound_call`, a call from your phone system that
            reached Yappr through the extension, or `outbound_call`, an answered call the
            agent placed out through it. An `outbound_call` shows that outbound calls work;
            it does not confirm that incoming calls arrive. `null` exactly when
            `last_activity_at` is.
          example: inbound_call
        allow_list:
          type: object
          description: What to allow on your phone system's firewall for this endpoint.
          required: [sip_ip, sip_ports, rtp_ports, note]
          properties:
            sip_ip: { type: string, description: "The carrier address of the region that registers and sends the calls: 192.76.120.75 for the Middle East (observed live), 192.76.120.72 for Europe (from the carrier's documentation, not observed live).", example: "192.76.120.75" }
            sip_ports: { type: array, items: { type: integer }, example: [5060, 5061] }
            rtp_ports: { type: string, description: "The media port range, on the carrier's side.", example: "16384-32768" }
            note: { type: string, example: "allow these on your phone system" }

    SipRegisterOutbound:
      type: [object, "null"]
      description: |
        Calls OUT through this extension: the agent's outbound calls go to your phone system
        through the extension, and your phone system dials the number on your own plan, showing
        the caller ID it is set to show for the extension
        ([how it works](/concepts/sip-trunks#outbound-calls-through-the-extension)). `null` when
        outbound calls were never set up. `caller_number` is listed under `GET /phone-numbers`
        with `provider: phone_system` and is used like any number.
      required: [enabled, caller_number, phone_number_id, dial_format, dial_prefix, paused]
      properties:
        enabled:
          type: boolean
          description: |
            Your switch. Calls go out when it is `true`, `paused` is `null` and the endpoint is
            switched on.
        caller_number: { type: string, example: "+97235550100", description: "The number your phone system shows, in E.164 form." }
        phone_number_id: { type: string, format: uuid, description: "The number's id under `GET /phone-numbers`: `from_phone_number_id` for a campaign." }
        dial_format:
          type: string
          enum: [national, e164]
          description: "How the number is handed to your phone system: `national` as 05X..., `e164` with the country code and no plus sign (972...). It changes nothing else: in both, calls are placed only to Israeli numbers (+972)."
        dial_prefix: { type: [string, "null"], example: "9", description: "The outside-line prefix dialled before the number, or `null`." }
        paused:
          type: [object, "null"]
          description: |
            Set when outbound calls paused on their own after three refusals in a row by your
            phone system; campaigns calling from the number pause with them. Send `enabled: true`
            to turn them back on.
          properties:
            reason: { type: string, enum: [phone_system_refused] }
            since: { type: [string, "null"], format: date-time }
            last_sip_code: { type: [string, "null"], example: "403" }

    SipRegisterOutboundInput:
      type: object
      required: [enabled]
      additionalProperties: false
      description: |
        Calls out through the extension. Yappr's own setting: it needs no password, is not sent to
        the carrier and does not count toward the 30 changes an hour. On PATCH a field you leave
        out keeps its value. Switching it on is refused with `403 SIP_REGISTER_OUTBOUND_NOT_ENABLED`
        for a workspace it isn't enabled for, and `409 VOICE_NOT_READY` while the voice server
        can't place these calls; switching it off always works.
      properties:
        enabled: { type: boolean, description: "`true` to call out through the extension (also lifts a pause), `false` to stop." }
        caller_number:
          type: string
          pattern: "^\\+[1-9][0-9]{6,14}$"
          example: "+97235550100"
          description: |
            The number your phone system shows, in E.164 form. Required the first time outbound is
            switched on (`field_required` at `/register/outbound/caller_number`). A number already
            in Yappr is refused with `409 PHONE_NUMBER_IN_USE`.
        dial_format: { type: string, enum: [national, e164], default: national, description: "How the number is handed to your phone system: `national` (05X...) or `e164` (972..., no plus sign). In both, calls are placed only to Israeli numbers (+972)." }
        dial_prefix: { type: [string, "null"], pattern: "^[0-9]$", description: "One digit, or `null` for none." }

    SipRegisterCreate:
      type: object
      description: |
        Extension endpoints only: the extension account your phone system gave you.
        Yappr does not store the password or return it. It is passed to Yappr's
        carrier, which holds it to keep the extension registered and to place
        transfers.
      required: [server, username, password]
      properties:
        server:
          type: string
          description: |
            The registrar, as a host name or IP address with an optional `:port`
            (1 to 65535). No `sip:` prefix, path or credentials. It is checked
            when you save: it must resolve to a public address, not a private,
            loopback or link-local one, and not a Yappr or Telnyx host.
          example: "sip1.example.net"
        username:
          type: string
          maxLength: 128
          minLength: 2
          pattern: "^[A-Za-z0-9+][A-Za-z0-9+_-]{1,127}$"
          description: |
            The extension: 2 to 128 characters; letters, digits, `+`, `-` and `_`,
            starting with a letter, digit or `+`. A dot, `@` or space cannot be
            registered. A 3-digit extension such as `101` works. Unique across
            Yappr, first come first served: with a short extension a clash is
            likely, so create a dedicated extension on your phone system with a
            distinctive name and register that one.
          example: "101"
        password:
          type: string
          minLength: 1
          maxLength: 128
          writeOnly: true
          description: |
            The extension's password. Yappr does not store, return or log it. It is
            passed to Yappr's carrier, which holds it to register (about every
            hour) and to place transfers: send the new one in an update whenever it
            changes on your phone system.
        auth_username:
          type: [string, "null"]
          maxLength: 128
          description: "Only when your phone system logs in with a user other than the extension: 1 to 128 letters, digits and `. _ @ + -`."
        transport:
          type: string
          enum: [udp, tcp, tls]
          default: udp
        region:
          type: string
          enum: [middle_east, europe]
          default: middle_east
          description: |
            The Telnyx region that registers. Pick the one nearer your phone system.
            It decides the address in `allow_list`: `192.76.120.75` for
            `middle_east` (observed live) and `192.76.120.72` for `europe` (this
            address comes from the carrier's documentation and was not observed
            live; read it from `allow_list`).
        pbx_feature_code:
          type: [string, "null"]
          examples: ["##", "*2", "*2{extension}#"]
          description: |
            Your phone system's in-call transfer code, set once for every transfer on this
            endpoint's calls, on every agent, whose destination is an extension a keypad can dial
            (`sip:400@pbx.example.com`): Yappr presses the code and then the extension, your phone
            system moves the caller, and Yappr leaves the call. Without
            `pbx_feature_code_hangup_after_secs`, if your phone system hasn't taken the call
            within about 12 seconds, Yappr places a new call through the extension instead;
            with it, Yappr's own hang-up completes the transfer and there is no fallback. A transfer tool or flow step with a code of its own uses that one. 1 to
            32 characters of `0`-`9`, `*`, `#`, `A`-`D` and the pauses `w` (half a second) and
            `W` (one second), with at least one key.
            `{extension}` may appear once and is replaced by the extension; without it the
            extension is sent right after the code (`##` and `sip:400@pbx.example.com` send
            `##400`). Surrounding spaces are trimmed before these checks, and the code is stored
            trimmed. Anything else is refused with `field_invalid` at
            `/register/pbx_feature_code`. Leave it out, or send `null` or `""`, for none.
        pbx_feature_code_hangup_after_secs:
          type: [integer, "null"]
          minimum: 1
          maximum: 10
          examples: [4]
          description: |
            Only with `pbx_feature_code`. Set it when your phone system's code starts an
            attended transfer that completes when the extension that typed it hangs up: Yappr
            hangs up this many seconds after the code (counted once its key presses have
            played), and until then the agent is off the line, silent and not listening. That
            hang-up is the hand-off, so there is no fallback: test it once. 4 is a good start.
            A whole number from 1 to 10 (`field_invalid` at
            `/register/pbx_feature_code_hangup_after_secs`); without a code it is
            `field_required` at `/register/pbx_feature_code`. Leave it out (or `null`) to wait
            for your phone system to take the call.
        outbound:
          $ref: "#/components/schemas/SipRegisterOutboundInput"

    SipRegisterUpdate:
      type: object
      description: |
        Any of the extension's settings. Changing `username` or `auth_username`
        needs `password` in the same request, and a password change is `password`
        on its own. Yappr does not keep the password, so it can't reuse it: send
        the new one whenever it changes on your phone system, because Yappr's
        carrier holds the last one it was given and uses it to register and to
        place transfers. Changing only `server`, `transport` or `region` doesn't
        need it.

        `pbx_feature_code` and `pbx_feature_code_hangup_after_secs` are Yappr's own
        settings: changing them needs no password, doesn't go to the carrier (the
        registration isn't touched), doesn't count toward the 30 changes an hour, and
        works while the endpoint is switched off. A field you leave out keeps its value.
      minProperties: 1
      properties:
        server: { type: string, example: "sip1.example.net:5060" }
        username: { type: string, minLength: 2, maxLength: 128, pattern: "^[A-Za-z0-9+][A-Za-z0-9+_-]{1,127}$" }
        password: { type: string, minLength: 1, maxLength: 128, writeOnly: true }
        auth_username: { type: [string, "null"], maxLength: 128 }
        transport: { type: string, enum: [udp, tcp, tls] }
        region: { type: string, enum: [middle_east, europe] }
        pbx_feature_code:
          type: [string, "null"]
          description: |
            The transfer code, by the same rule as on create. `null` or `""` removes it,
            and the hang-up time with it.
        pbx_feature_code_hangup_after_secs:
          type: [integer, "null"]
          minimum: 1
          maximum: 10
          description: |
            1 to 10 seconds, as on create; `null` removes it. It needs a code: the one sent
            in the same request, or the one already stored (`field_required` at
            `/register/pbx_feature_code` when there is neither).
        outbound:
          $ref: "#/components/schemas/SipRegisterOutboundInput"

    SipEndpointWithPassword:
      description: |
        The endpoint, as [create](/api-reference/sip-endpoints/create) returns it.
        On a username-and-password trunk it carries `sip_password`, the only time
        the password is returned besides
        [rotate-password](/api-reference/sip-endpoints/rotate-password).
      allOf:
        - { $ref: "#/components/schemas/SipEndpoint" }
        - type: object
          properties:
            sip_password:
              type: string
              description: |
                Username-and-password trunks only: the trunk's SIP password, 32
                letters and digits. Store it now: neither the API nor the dashboard
                can show it again. If it is lost,
                [issue a new one](/api-reference/sip-endpoints/rotate-password).
              example: "Ex4mpleOnlyNotARealPassword12345"

    CallFollowUps:
        type: object
        required: [state, groups]
        description: |
          **The agent's follow-ups that did not run on this call, and why.** Present on
          `GET /calls/{id}` only when there is something to explain; absent when every
          follow-up the call's workflow had started (its `trigger` rows are in `timeline`),
          when the workflow had none, and when the agent has no published workflow. The
          dashboard's call page reads the same answer.
        properties:
          state:
            type: string
            enum: [skipped, waiting]
            description: |
              `waiting` every group is still waiting for the result it runs on, and will run
              once that result is ready - read the call again · `skipped` at least one group
              will not run on this call.
          groups:
            type: array
            minItems: 1
            items:
              type: object
              required: [reason, steps]
              properties:
                reason:
                  type: string
                  enum: [browser_test, no_workflow_run, artifact_pending, artifact_unavailable, artifact_late, condition_not_met]
                  description: |
                    `browser_test` a test call from the dashboard that ran without the workflow, so
                    none of its follow-ups ran · `no_workflow_run` any other call that ran without
                    the workflow · `artifact_pending` the result this follow-up runs on is still
                    being produced · `artifact_unavailable` that result was never produced and
                    nothing more is coming, so the follow-up will not run (the transcript was
                    empty; a follow-up on analysis.ready reads this as soon as the call's
                    `analysis` reads failed or skipped with a completed_at) · `artifact_late` the call's run
                    closed before that result arrived · `condition_not_met` the follow-up's "Only if"
                    (`when` on its After trigger) did not hold for this call, so it ran nothing on
                    purpose. Treat an unrecognised reason as `skipped`.
                event:
                  type: string
                  description: The trigger's event, such as analysis.ready. Present on the artifact_* reasons and on condition_not_met.
                trigger_id:
                  type: string
                  description: The follow-up's id in the workflow document. Present on condition_not_met only.
                seen:
                  type: array
                  description: |
                    The call facts the condition read and the value the call had, in the call package's own paths
                    (`/status`, `/ended_by`, `/duration_seconds`, `/disposition/label`, `/analysis/extracted_data/<name>`).
                    A fact the call does not have is left out. Present on condition_not_met only.
                  items:
                    type: object
                    required: [path, value]
                    properties:
                      path: { type: string, example: /status }
                      value:
                        oneOf: [{ type: string }, { type: number }, { type: boolean }]
                        example: completed
                artifact:
                  type: string
                  description: The result that event waits for, such as analysis. Present on the artifact_* reasons only.
                steps:
                  type: array
                  items: { type: string }
                  description: The names of the steps that did not run, in the order the workflow lists them. For browser_test and no_workflow_run, every follow-up step the agent had published when the call started.

    CallAnalysis:
        type: object
        description: |
          **Where the call's post-call analysis stands.** Present on every call, in both
          `GET /calls` rows and `GET /calls/{id}`.

          `summary`, `disposition` and `extracted_data` are all written by that one pass, and
          until it lands none of them is on the call at all. Their absence alone therefore
          cannot tell you whether to poll again, to stop polling, or to raise a ticket. This
          member does.

          `status` is what you branch on. `reason` says which of that status's cases this is,
          and is `null` only on `done`. Treat an unrecognised `reason` as the bare `status`.
        properties:
          status:
            type: string
            enum: [pending, done, skipped, failed]
            description: |
              `pending` it is still coming — poll again (a workflow agent's call stays pending
              while a retry of its analysis is still due, even past ten minutes) · `done` it ran,
              and whatever it produced is on the call · `skipped` nothing is coming, and nothing
              is wrong · `failed` nothing is coming, and something is wrong.
          reason:
            type: string
            nullable: true
            enum: [call_in_progress, awaiting_analysis, call_did_not_complete, call_too_short, no_transcript, analysis_failed, no_summary, analysis_unavailable]
            description: |
              `call_in_progress` the call has not ended yet, which includes a call handed to a
              human until that leg ends · `awaiting_analysis` the call
              ended and the pass has not landed · `call_did_not_complete` the call failed or
              nobody answered, so there was nothing to read · `call_too_short` shorter than the
              three-second minimum · `no_transcript` nobody said anything on it ·
              `analysis_failed` the pass ran and could not produce an answer · `no_summary` the
              pass ran and came back without a summary on every attempt, so nothing it produced
              was kept (a `done` call always has a summary) · `analysis_unavailable` the call is
              long past the point where the pass should have landed and it never did.
          completed_at:
            type: string
            format: date-time
            nullable: true
            description: >
              When the pass finished, when the platform recorded the time; when the summary was
              written again later (after a repair of the call's transcript), when that happened.
              Null on a call analysed before this was recorded, and on every state derived from
              the call itself.
        required: [status, reason, completed_at]

    CallFailure:
        type: object
        description: |
          **Why the call did not complete.** Present only on a call whose `status` is `failed`
          or `no_answer`; a call that completed has no `failure` member at all, so check for the
          member rather than for a value inside it. A call someone ended on purpose from outside
          it (`ended_by: operator` - POST /calls/{id}/end, an End button) did not fail and has no
          `failure` either: `ended_by` and `disconnect_reason` say why it stopped.

          `code` is stable and is what you branch on. `reason` is one sentence written for a
          person, and its wording changes. The raw text the platform recorded internally is
          never returned: it is the carrier's own cause code, an exception's tail, or a
          provider's error class, none of which is an answer to give a customer.

          New codes are added when a new failure becomes distinguishable — treat an
          unrecognised one as `unknown`.
        properties:
          code:
            type: string
            enum: [no_answer, busy, rejected, cancelled, unreachable, caller_left, network_blocked, voice_connection_failed, preparation_failed, voice_unavailable, call_interrupted, transfer_failed, session_expired, phone_system_refused, unknown]
            description: |
              `no_answer` nobody picked up · `busy` the number was busy · `rejected` refused at
              the far end · `cancelled` cancelled before anyone answered (at stage `connecting`: a
              browser session ended with POST /calls/{id}/end or its cancel_url before such an end was recorded as
              the operator's; those older calls read ended_by system) · `unreachable` the
              number could not be reached · `caller_left` a browser call the caller cancelled, closed,
              or navigated away from, before it connected (ended_by reads caller) · `network_blocked` a browser call
              whose connection never came up, almost always a firewall on the caller's side ·
              `voice_connection_failed` a browser call the voice server did not answer: it refused
              to connect it ·
              `preparation_failed` a dashboard rehearsal whose before-call steps failed before any
              browser connected ·
              `voice_unavailable` the voice server did not answer: it timed out, was busy, could not
              start the call, or answered a browser that had already stopped waiting (never
              `network_blocked` on a call made since that late answer is recorded; an older call
              recorded only the browser's timeout and reads `network_blocked`) ·
              `call_interrupted` the call ended unexpectedly mid-conversation ·
              `transfer_failed` handed to another number that never picked up ·
              `session_expired` a minted browser session nobody connected to before its token
              expired · `phone_system_refused` a call out through your own phone system
              (a `phone_system` number) that your phone system refused before it rang; the
              lead is not blocked for it · `unknown` it failed and nothing recorded why.
          reason:
            type: string
            description: "One sentence for a person to read. Never an internal code; do not match on it."
          stage:
            type: string
            enum: [dialing, connecting, conversation]
            nullable: true
            description: "Where in the call it went wrong. `null` when nothing recorded enough to say."
          at:
            type: string
            format: date-time
            nullable: true
            description: "When the failure was recorded - or, when nothing recorded a moment of its own, when the call ended (`ended_at`). `null` only while neither is known."
        required: [code, reason, stage, at]
    Disposition:
      type: object
      properties:
        id: { type: string, format: uuid }
        label: { type: string }
        color:
          type: string
          example: "#22c55e"
          description: >
            Always set. A disposition created without a colour is stored grey
            (`#6b7280`), the same default the dashboard's picker starts on.
            The format is not validated.
        position: { type: integer, description: "Display order, ascending. Not unique." }
        is_protected: { type: boolean, description: "Protected dispositions cannot be deleted. They can still be renamed, which stops the rules that set them by name from finding them." }
        created_at: { type: string, format: date-time }

    CallWindow:
      type: object
      description: |
        A single allowed time range on one day of the week. All times are in the
        workspace's timezone (see `companies.timezone` / `CallWindowConfig.timezone`).
        Multiple ranges per day are allowed but must not overlap.
      required: [day_of_week, start_time, end_time]
      properties:
        day_of_week: { type: integer, minimum: 0, maximum: 6, description: "0=Sunday, 1=Monday, …, 6=Saturday." }
        start_time:  { type: string, pattern: '^([01]\d|2[0-3]):[0-5]\d$', example: "09:00"  }
        end_time:    { type: string, pattern: '^([01]\d|2[0-3]):[0-5]\d$', example: "19:00"  }

    CallWindowConfig:
      type: object
      description: |
        Company-level configuration that gates **phone calls** by time-of-day.
        When `outbound_enabled` is true, outbound API requests placed outside
        any allowed window are deferred — the response is `202 Accepted` with
        `status: "scheduled"` and a `scheduled_for` timestamp marking the next
        window opening. When `inbound_enabled` is true, inbound calls received
        outside any allowed window are ended before being answered (no
        `call_logs` row is created).

        Browser sessions minted with `POST /calls {"type":"web"}` are
        rehearsals, not customer traffic: they are never gated by either
        toggle and always mint immediately, whatever the schedule says.

        A day with no windows is a closed day for whichever directions are
        enforced. The default schedule (seeded for every company) is Sunday
        through Thursday 09:00–19:00 plus Friday 09:00–11:30; Saturday is
        closed.
      properties:
        timezone:
          type: string
          description: |
            The workspace's clock, as an IANA timezone name. `UTC` until someone
            sets it (`timezone_set` says which). Set it with `timezone` on
            `PUT /call-windows`, or under Settings → Workspace clock.
          example: "Asia/Jerusalem"
        timezone_set:
          type: boolean
          readOnly: true
          description: |
            Whether the workspace chose its clock. `false` means `timezone` is
            the `UTC` default nobody picked: the calling hours, relative dates
            and consumption days are still read on UTC, and the dashboard shows
            times on each reader's own browser clock (labelled as such) until the
            clock is set. `true` once any write names `timezone`, including
            `UTC` on purpose.
          example: true
        inbound_enabled:
          type: boolean
          description: When true, inbound phone calls outside the window are ended before an agent answers. Default false.
        outbound_enabled:
          type: boolean
          description: When true, outbound phone calls outside the window are scheduled for the next opening. Default true.
        closed_message:
          type: string
          nullable: true
          maxLength: 500
          description: |
            Optional message an inbound caller will hear when `inbound_enabled`
            is true and the window is closed, spoken before the call ends.
            `null` (the default) ends the call without saying anything. Blank
            strings are stored as `null`. The field is stored and returned
            today; calls do not speak it yet, so an out-of-hours call is still
            ended in silence until the voice release that picks it up.
          example: "You've reached us outside our hours. We're here Sunday to Thursday, nine to seven."
        updated_at:
          type: string
          format: date-time
          description: |
            The version of this whole record — the hours, the toggles and the
            message together. Send it back as `expected_updated_at` on a
            `PUT` and the write is refused with `409 CALL_WINDOWS_CONFLICT` if
            anyone changed the hours in between, instead of silently replacing
            what they wrote. These settings are workspace-wide, so the other
            writer may be a colleague's dashboard tab.
          example: "2026-09-22T11:30:00.000Z"
        windows:
          type: array
          items: { $ref: "#/components/schemas/CallWindow" }

    Lead:
      type: object
      properties:
        id: { type: string, format: uuid }
        phone_number: { type: string, example: "+972501234567"  }
        name: { type: string, nullable: true }
        email: { type: string, format: email, nullable: true }
        source:
          type: string
          enum: [api, manual, csv_import, call]
          example: api
          description: |
            How the lead first appeared.

            `call` — created from a call this workspace took or placed. The
            most common value by far, and written only by Yappr: a request
            cannot claim it. `api` — created through this API. `manual` —
            typed into the dashboard. `csv_import` — arrived in a
            spreadsheet.

            A create may send `api`, `manual` or `csv_import`; any other
            value is refused rather than silently rewritten.
        tags:
          type: array
          items:
            $ref: "#/components/schemas/LeadTag"
        long_term_context: { type: string, nullable: true, description: "AI memory for this lead. Injected into the agent's system prompt at call time when lead_memory_enabled is true on the agent." }
        extracted:
          type: object
          nullable: true
          additionalProperties: true
          description: >
            What this lead's calls collected, keyed by the extraction parameter's own name,
            merged across every call with this person. The most recent call that answered a
            field wins it; a field that call never covered keeps the answer an earlier one
            found. Only answers are merged: unlike a call's own extracted_data on
            GET /calls/{id}, which carries every parameter with null for the ones that call
            never covered, a parameter no call has answered is absent here. Read-only
            and written only by the post-call pass: it is stored under the reserved
            metadata.extracted key, neither a create nor a PATCH can set it, and replacing
            metadata does not erase it. Null until a call collects something.
        extracted_precision:
          type: object
          nullable: true
          additionalProperties:
            $ref: "#/components/schemas/ExtractedDatePrecision"
          description: >
            The date parameters the latest call that answered them gave as a month and no day
            ("sometime in November"), keyed by parameter name, each {"precision": "month",
            "month": "YYYY-MM"}, with "approximate": true when the call's own
            extracted_data_precision has it (a month worked out from a length of time ago, such as
            "three months ago", rather than named). Such a field is absent from extracted, because a month is not a
            day; a later call that names the day moves it back to extracted and out of here.
            Read-only, stored under the reserved metadata.extracted_precision key like extracted,
            and null when no call has given a month alone. The same member is on the lead inside
            GET /calls/{id}.
        metadata: { type: object }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    LeadTag:
      type: object
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        description: { type: string, nullable: true }
        color: { type: string, nullable: true }
        sort_order: { type: integer }
        created_at: { type: string, format: date-time }

    ApiKey:
      type: object
      description: |
        An API key belonging to your workspace. The secret itself is stored only
        as a SHA-256 hash and is returned exactly once, by `POST /api-keys`; no
        read ever returns it. `prefix` is the first 16 characters of the secret
        and is what identifies a key in the dashboard list.
      properties:
        id: { type: string, format: uuid }
        name:
          type: string
          description: What you called the key. Unique among this workspace's active keys, compared without regard to case.
          example: "Nightly lead sync"
        prefix:
          type: string
          description: First 16 characters of the key, enough to tell two keys apart. Never the whole secret.
          example: "ypr_live_9f2c41a"
        scopes:
          type: array
          items: { type: string }
          example: ["leads:read", "leads:manage"]
        agent_ids:
          type: array
          nullable: true
          items: { type: string, format: uuid }
          description: |
            The agents this key is limited to, or `null` for a key that reaches
            the whole workspace. A limited key reaches those agents, their calls,
            the leads they called (read only), their spend, their deliveries and
            their campaigns, and calls only from numbers those agents answer or
            call from; everything the workspace shares answers
            `403 API_KEY_AGENT_SCOPED`, and naming another agent answers
            `403 AGENT_OUTSIDE_KEY_SCOPE`.
          example: null
        agents:
          type: array
          nullable: true
          description: |
            The same agents as `agent_ids`, in the same order, each with its
            name — so a read says which client a limited key reaches. An
            archived agent keeps its name; an agent that no longer exists has
            `name: null`. `null` for a key that reaches the whole workspace.
          items:
            type: object
            properties:
              id: { type: string, format: uuid }
              name: { type: string, nullable: true }
          example: null
        created_at: { type: string, format: date-time }
        expires_at:
          type: string
          format: date-time
          nullable: true
          description: |
            When the key stops working, or `null` for a key that works until it
            is revoked. Past this moment every request made with it answers
            `401 EXPIRED_KEY`; the key stays listed until it is revoked.
          example: null
        last_used_at:
          type: string
          format: date-time
          nullable: true
          description: When this key last authenticated a request. `null` if it never has.
    ApiKeyCreated:
      allOf:
        - $ref: "#/components/schemas/ApiKey"
        - type: object
          properties:
            key:
              type: string
              description: |
                The full secret. This is the only response that ever contains it —
                store it before you do anything else. If you lose it, revoke the
                key and issue another.
              example: "ypr_live_9f2c41a7b0e3…"
    RevokedApiKey:
      description: |
        A key this workspace revoked, as `GET /api-keys?revoked=true` lists it:
        what it could reach (`scopes`, `agents`, `expires_at`), when it was
        made, and when and by whom it was revoked. Revocations are on record
        from 22 September 2026, and who revoked a key from 28 September 2026:
        before that `revoked_by` and `revoked_by_key` may both be null.
      allOf:
        - $ref: "#/components/schemas/ApiKey"
        - type: object
          properties:
            revoked_at:
              type: string
              format: date-time
              nullable: true
              description: When the key was revoked; null for a key revoked before the time was kept.
            revoked_by:
              type: object
              nullable: true
              description: The person who revoked it in the dashboard, or null when a key did, or when it was not recorded. `email` is null when the account no longer exists. The email is personal data, which is why the dashboard marks a key holding `api_keys:read` or `api_keys:manage` as reading it.
              properties:
                id: { type: string, format: uuid }
                email: { type: string, nullable: true }
            revoked_by_key:
              type: object
              nullable: true
              description: The key that revoked it with `DELETE /api-keys/{id}`, or null when a person did. `name` and `prefix` are null for a key that no longer exists.
              properties:
                id: { type: string, format: uuid }
                name: { type: string, nullable: true }
                prefix: { type: string, nullable: true }
    DncEntry:
      type: object
      description: |
        A phone number on the company's Do-Not-Call list. Outbound call placement
        skips numbers on this list — the request returns `status: "dnc_blocked"`
        and a `call_logs` row is recorded for analytics, but no carrier leg is
        established and no minutes are charged.

        DNC entries can be **global** (block every agent) or **agent-scoped**
        (block only specific agents — others can still call the number). Scope
        is controlled via the `agent_ids` field.
      properties:
        id: { type: string, format: uuid }
        company_id: { type: string, format: uuid }
        phone_number:
          type: string
          description: E.164 form, e.g. `+972501234567`. Whatever input format you submit gets normalized before storage.
          example: "+972501234567"
        reason:
          type: string
          nullable: true
          description: Optional free-form note. Surfaced in the dashboard, not in outbound API responses.
        source:
          type: string
          enum: [manual, api, auto]
          description: |
            Where this entry came from. `manual` = added via dashboard, `api` =
            added via this API, `auto` = reserved for future automated additions
            (e.g. opt-out keyword detection during a call).
        expires_at:
          type: string
          format: date-time
          nullable: true
          description: When the block lapses. `null` = permanent. Past timestamps are filtered out at outbound-check time.
        active:
          type: boolean
          description: |
            Whether this entry blocks calls right now: `true` when `expires_at` is
            `null` or still in the future, `false` once it has passed. A lapsed
            entry is not removed - it stays on the list, and a `?phone=` lookup
            still returns it, with `active: false` - until you delete it or give
            it a new `expires_at`.
          example: true
        agents:
          type: array
          description: |
            Empty array `[]` (or omitted on insert) = **global**: every agent
            in the company is blocked from calling this number.

            Non-empty = **scoped**: only the listed agents are blocked. Agents
            NOT in the array can still place outbound calls to this number.

            On GET responses each item is the full agent object (resolved
            from the underlying `agent_ids` column so you don't have to make
            a second `/agents/{id}` call). On POST/PATCH inputs the field is
            named `agent_ids` and takes a `string[]` of UUIDs — see those
            endpoints for the input shape.
          items: { $ref: "#/components/schemas/Agent" }
        created_by:
          type: string
          format: uuid
          nullable: true
          description: Best-effort attribution to a user; null when added via API.
        created_at: { type: string, format: date-time }

    SharedLink:
      type: object
      properties:
        id: { type: string, format: uuid }
        token: { type: string }
        url: { type: string, description: "Full shareable URL" }
        agent_id: { type: string, format: uuid }
        company_id: { type: string, format: uuid }
        created_by: { type: string, format: uuid, nullable: true }
        expires_at: { type: string, format: date-time, nullable: true }
        is_revoked: { type: boolean }
        status: { type: string, enum: [active, expired, revoked] }
        created_at: { type: string, format: date-time }

    ConnectionAction:
      type: object
      description: One thing a connected app can do on calls.
      required: [action, name, description, effect, default]
      properties:
        action: { type: string, example: GOOGLECALENDAR_FIND_FREE_SLOTS }
        name: { type: string, example: Find free time }
        name_he: { type: [string, 'null'], example: חיפוש זמן פנוי }
        description: { type: string, description: One line for a person. }
        effect: { type: string, enum: [read, write, delete] }
        default: { type: boolean, description: On when the app is added without a list of actions. }
        description_he: { type: [string, 'null'], description: 'One spoken-Hebrew line, for a curated action.', example: בודק מתי היומן פנוי בטווח שעות }
        inputs:
          type: array
          description: 'How each input is set, configuration inputs (which calendar) first. Absent for an action the catalogue has no word on.'
          items: { $ref: '#/components/schemas/ActionInputSpec' }
    ActionInputSpec:
      type: object
      description: >
        One input of an action. role config is a setting of the agent (which calendar, which sheet), usually
        Fixed; role conversation is filled from the call, usually by the agent (AI). default_source is what
        a new binding gets when you do not set it - null for a configuration ID with no default (a
        spreadsheet, a channel, a board): the agent cannot guess one, so you set it.
      required: [name, label, role, required, default_source]
      properties:
        name: { type: string, example: items }
        label: { type: string, example: Calendar }
        label_he: { type: string, example: יומן }
        role: { type: string, enum: [config, conversation] }
        resource: { type: [string, 'null'], enum: [calendar, sheet, channel, board, event_type, null], description: 'Set when the account can list the choices: GET /tool-connections/{id}/options/calendars for calendar.' }
        shape: { type: string, enum: [value, one_item_array], description: 'one_item_array: the tool takes a list, and you fix it to a list of one id (["primary"]).' }
        required: { type: boolean }
        default_source:
          oneOf:
            - { $ref: '#/components/schemas/ActionInputSource' }
            - { type: 'null' }
    ActionInputSource:
      type: object
      description: >
        Where an action input's value comes from - the workflow's own input sources (see the workflow
        document's bindings). Fixed is {"kind": "literal", "value": ...}: the agent never sees it, and it is
        sent as is (a literal may be one call reference such as "{{call.caller_number}}", or a relative time such as "{{call.time.start_of_today.Asia/Jerusalem}}", resolved when the step runs). AI is {"kind":
        "model", "path": "/<input>"}: the agent fills it from the conversation. Choose from a list is a model
        source with options: the agent picks one of 1-20 {value, label} choices by its label. From the call:
        request (a call request field), stored (saved context) or step (an earlier step's result), each with
        an optional fallback {"value": ...}. Fixed and from-the-call values are left out of what the agent is
        asked for, and a value it sends for them anyway is ignored.
      required: [kind]
      properties:
        kind: { type: string, enum: [literal, model, request, stored, step] }
        value: { description: 'literal: the fixed value.' }
        path: { type: string, description: 'model: "/<input>". request, stored, step: a pointer into the value read, such as /phone.' }
        options:
          type: array
          minItems: 1
          maxItems: 20
          description: 'model only: the choices the agent picks from, each value listed once. Text inputs (or a list of text) only.'
          items:
            type: object
            additionalProperties: false
            required: [value, label]
            properties:
              value: { type: string, minLength: 1, maxLength: 500 }
              label: { type: string, minLength: 1, maxLength: 120 }
        scope: { type: string, enum: [before, during], description: 'step: a before-call step or an action step.' }
        step_id: { type: string }
        fallback: { type: object, required: [value], properties: { value: {} }, description: 'Sent when the value read is missing.' }
      example: { kind: literal, value: [c_1a2b3c@group.calendar.google.com] }
    GrantedAction:
      allOf:
        - { $ref: '#/components/schemas/ConnectionAction' }
        - type: object
          properties:
            binding_id: { type: string, example: i_0b8f4c2e_find_free_slots, description: 'The binding this action runs as on every step.' }
            inputs:
              type: object
              description: 'The agent''s source for each input, by input name.'
              additionalProperties: { $ref: '#/components/schemas/ActionInputSource' }
            input_specs: { type: array, items: { $ref: '#/components/schemas/ActionInputSpec' } }
            bindable: { type: boolean, description: 'The account''s tool for this action takes the agent''s own calendar. False on a tool built before that: the first write that sets a calendar rebuilds it (a new revision of the same tool), so you can send it anyway.' }
            missing_inputs:
              type: array
              items: { type: string }
              example: [spreadsheet_id]
              description: 'Required inputs that have no source yet - a configuration ID with no default (a spreadsheet, a channel, a board) starts with none, because the agent cannot guess it. Omitted when none. Set each with PATCH /agents/{id}/integrations/{integration_id} and inputs; until then the integration is saved but not published (not_live_reason inputs_missing).'
            overrides:
              type: array
              description: 'Steps with their own settings for this action (the workflow''s binding_overrides).'
              items:
                type: object
                required: [node_id, binding_id, inputs]
                properties:
                  node_id: { type: string }
                  binding_id: { type: string, example: o_k3j9x0a2b1 }
                  inputs: { type: object, additionalProperties: { $ref: '#/components/schemas/ActionInputSource' } }
    ToolGrant:
      type: object
      description: A saved webhook or call transfer given to every conversation step of the agent.
      required: [id, kind, tool_id, name, binding_id, inputs, overrides, status]
      properties:
        id: { type: string, example: tg_5c1e9a20 }
        kind: { type: string, enum: [webhook, transfer] }
        tool_id: { type: string, format: uuid }
        name: { type: string, example: Send lead to CRM }
        binding_id: { type: string, example: t_5c1e9a20, description: 'Its binding: PATCH its inputs keyed by this id.' }
        inputs: { type: object, additionalProperties: { $ref: '#/components/schemas/ActionInputSource' } }
        overrides: { type: array, items: { type: object } }
        status: { type: string, enum: [live, not_live, unavailable], description: 'unavailable: the tool is no longer in the workspace.' }
    ToolGrantWriteResult:
      type: object
      required: [integration, draft_version, live]
      properties:
        integration: { $ref: '#/components/schemas/ToolGrant' }
        draft_version: { type: integer }
        live: { type: boolean }
        not_live_reason: { type: string, enum: [draft_has_other_changes, agent_not_published, publish_not_requested, publish_refused, publish_unavailable] }
        settings_updated_at: { type: string, format: date-time }
    Integration:
      type: object
      description: A connected account given to the whole agent.
      required: [id, app, app_name, connection, actions, status]
      properties:
        id: { type: string, example: i_0b8f4c2e }
        app: { type: string, example: googlecalendar }
        app_name: { type: string, example: Google Calendar }
        connection:
          type: object
          properties:
            id: { type: string, format: uuid }
            label: { type: string, example: Clinic calendar }
            state: { type: string, example: ready }
            ready: { type: boolean }
        actions: { type: array, items: { $ref: '#/components/schemas/GrantedAction' } }
        status: { type: string, enum: [live, not_live, building, reconnect_required] }
    IntegrationWriteResult:
      type: object
      required: [integration, draft_version, live]
      properties:
        integration: { $ref: '#/components/schemas/Integration' }
        draft_version: { type: integer }
        live: { type: boolean, description: The change is on the agent's calls now. }
        not_live_reason: { type: string, enum: [draft_has_other_changes, agent_not_published, publish_not_requested, publish_refused, publish_unavailable, inputs_missing] }
        issues: { type: array, items: { type: object }, description: 'With publish_refused: what the compiler refused, as POST /agents/{id}/workflow/publish names it. With inputs_missing: each required input still without a source (missing_input_source, path /actions/<n>/inputs/<input>), with the PATCH that sets it.' }
        skipped_actions:
          type: array
          description: 'Default actions the app cannot offer to a voice agent, left out of the integration, each with why. Empty when every default was given. An action named in actions is never skipped: it is refused (422 INTEGRATION_ACTION_UNAVAILABLE).'
          items:
            type: object
            required: [action, reason, message]
            properties:
              action: { type: string, example: GOOGLECALENDAR_DELETE_EVENT }
              reason: { type: string, description: 'not_eligible, needs_setup, action_version_deprecated, changed_meanwhile (send the request again), account_unavailable (reconnect the account), action_unknown, build_failed (try again in a minute), or the lowercase code of a failed build.', example: action_version_deprecated }
              message: { type: string, example: 'Google Calendar cannot offer GOOGLECALENDAR_DELETE_EVENT to an agent: this version of it is deprecated.' }
        settings_updated_at: { type: string, format: date-time, description: 'Present when live is true: publishing moved the agent''s settings token, as POST /agents/{id}/workflow/publish answers it. Send it as expected_updated_at on your next PATCH /agents/{id}.' }
    ConnectionAgent:
      type: object
      required: [agent_id, name, via, tools_count, live]
      properties:
        agent_id: { type: string, format: uuid }
        name: { type: string }
        via: { type: string, enum: [integration, tools] }
        tools_count: { type: integer, minimum: 0 }
        live: { type: boolean }
    Error:
      type: object
      required: [error, code]
      description: |
        Every error response - the secret-key API and the browser data plane alike - carries a
        human-readable `error` and a stable machine `code`, and a refusal that names what is
        wrong with the request carries `issues[]` too. Branch on `code`, never on the `error`
        text. A refusal that names nothing more specific carries the code its status means:
        `BAD_REQUEST` (400), `UNAUTHORIZED` (401, the browser data plane; the secret-key API
        answers `MISSING_KEY`, `INVALID_KEY` or `EXPIRED_KEY`), `BILLING_ERROR` (402),
        `FORBIDDEN` (403), `NOT_FOUND` (404), `METHOD_NOT_ALLOWED` (405), `CONFLICT` (409),
        `GONE` (410), `PAYLOAD_TOO_LARGE` (413), `UNSUPPORTED_MEDIA_TYPE` (415),
        `UNPROCESSABLE_REQUEST` (422), `RATE_LIMIT` (429), `INTERNAL_ERROR` (500),
        `UPSTREAM_ERROR` (502), `SERVICE_UNAVAILABLE` (503), `UPSTREAM_TIMEOUT` (504). Some
        refusals add members of their own beside these (a call request's `status`, a workflow's
        `current_version`); the operation says which.
      properties:
        error: { type: string, description: "The refusal, in one sentence for a person. Its wording may change." }
        code: { type: string, description: "The stable code to branch on." }
        issues:
          type: array
          description: >
            Each thing at fault, on a 400 or 422 that names them: every query parameter or body
            field, not just the first. `path` is the parameter's name or the field's location.
          items:
            type: object
            required: [code, message]
            properties:
              code: { type: string, description: "query_param_unknown, query_param_repeated, query_param_blank, query_param_invalid, field_unknown, field_required, field_invalid, or the route's own word." }
              path: { type: string }
              message: { type: string }

    CallRequestAccepted:
      type: object
      description: >
        The `202` a browser call request answers when it is accepted (POST /web-call/call-requests):
        the call request as it starts, plus the capability and the three browser URLs that follow,
        cancel and start it. The steps have not run yet, and nothing is dialled.
      required: [id, request_id, run_id, call_id, type, channel, status, preparation_status, agent_id, accepted_at, expires_at, start_capability, status_url, cancel_url, start_url]
      properties:
        id: { type: string, format: uuid, description: Same value as request_id on this channel. }
        request_id: { type: string, format: uuid, description: "Hand it to your server to read the request with GET /call-requests/{id}." }
        run_id: { type: string, format: uuid }
        call_id: { type: 'null', description: Always null here. A browser call has no call record until it is started. }
        type: { type: string, enum: [web] }
        channel: { type: string, enum: [web] }
        status: { type: string, enum: [preparing, scheduled] }
        preparation_status: { type: string, enum: [pending] }
        agent_id: { type: string, format: uuid }
        accepted_at: { type: string, format: date-time }
        expires_at: { type: string, format: date-time, description: After this the request is abandoned and the capability stops working. }
        start_capability: { type: string, description: "Returned once, and stored only as a hash. Send it as the x-yappr-call-request-key header on the read, the cancel and the start." }
        status_url: { type: string, format: uri, description: GET it with the capability to follow the steps. }
        cancel_url: { type: string, format: uri, description: POST to it with the capability to stop a request that has not started. }
        start_url: { type: string, format: uri, description: POST the browser's SDP offer to it with the capability once the request reads ready. }

    FlowValidationIssue:
      type: object
      required: [node_id, code, message]
      description: |
        A single validation problem detected during a flow create/update save. Returned as part of the
        `FLOW_INVALID` 400 response — see `FlowInvalidError`.
      properties:
        node_id:
          type: string
          nullable: true
          description: "ID of the offending node, or null when the issue applies to the flow as a whole (e.g. `no_start`)."
        code:
          type: string
          description: "Machine-readable issue code; see enum below."
          enum:
            - no_start
            - multiple_starts
            - start_unwired
            - instructions_missing
            - tool_id_missing
            - integration_id_missing
            - transition_description_missing
            - action_invalid
            - success_not_wired
            - transfer_to_missing
            - transfer_to_invalid_sip
            - terminal_not_allowed
            - no_terminal
            - unreachable_node
            - unknown_target_node
            - duplicate_node_id
            - cycle_no_exit
            - tool_not_in_company
            - integration_not_in_company
            - tool_deleted
            - integration_deleted
            - args_template_missing_required
            - args_template_missing_description
            - args_template_dangling_reference
            - global_not_allowed
            - global_jump_description_missing
            - schema_invalid
            - too_many_extraction_contracts
        message:
          type: string
          description: "Human-readable explanation of what to fix."

    FlowInvalidError:
      description: |
        400 response shape returned when a flow create/update save fails validation. Both `code` and `error`
        carry the literal string `FLOW_INVALID`; branch on `code`, which every error in this API carries.
        The `issues` array lists every problem found — fix all of them and re-save.
      allOf:
        - { $ref: "#/components/schemas/Error" }
        - type: object
          required: [error, code, issues]
          properties:
            error:
              type: string
              enum: [FLOW_INVALID]
            code:
              type: string
              enum: [FLOW_INVALID]
            issues:
              type: array
              items: { $ref: "#/components/schemas/FlowValidationIssue" }
    # ── Flow agents ────────────────────────────────────────────────────────────
    Transition:
      type: object
      required: [id, label, description, next_step_id]
      description: |
        A labeled outgoing branch from a conversation node. The voice agent picks one
        (or stays) at each user-turn boundary by calling the `pick_transition` tool.
      properties:
        id: { type: string, description: "Stable transition id (used in the flow graph and traces)" }
        label: { type: string, description: "Short human-readable label, also surfaced in the dashboard and call traces" }
        description:
          type: string
          minLength: 1
          description: |
            REQUIRED, non-empty. The natural-language trigger the voice agent reads at runtime
            to decide whether to take this path. Describe a user-side signal (what the caller
            said or implied), not an agent intent. Example: "Caller confirmed they want a demo
            scheduled" — not "agent books the demo". An empty description is rejected with
            error code `transition_description_missing`.
        next_step_id: { type: string, description: "Destination node id" }

    CustomTransition:
      type: object
      required: [id, label, jsonpath, equals, next_step_id]
      description: |
        Deterministic branch for a tool-call node, matched by JSONPath equality against the tool's parsed response body.
        Custom branches are evaluated top-to-bottom, first match wins; mutually exclusive with success/error (only one
        out-edge fires per tool fire). See /docs/api-reference/agents/flow-config-schema for the full runtime semantics.
      properties:
        id: { type: string }
        label: { type: string }
        jsonpath:
          type: string
          example: "$.status"
          description: |
            Dotted path into the tool's parsed response body (root `$`). Supported: `$.foo.bar`, `$.list[0].name`,
            `$.items[2]`. NOT supported: recursive descent (`$..`), wildcards (`$.*`), filter expressions.
        equals:
          type: string
          example: "no_availability"
          description: |
            Compared via string equality after JSON-style stringification of the extracted value:
            booleans become "true"/"false" (lowercase), null becomes "null", numbers via str(). Match the
            stringified form exactly or the branch never fires.
        next_step_id: { type: string }

    ToolCallTransitions:
      type: object
      description: |
        Routing for a tool_call node. Routing is deterministic, no LLM. error fires on hard failures
        (timeout, 4xx/5xx, integration disconnected). Otherwise custom[] is evaluated in declaration order
        and the first match wins; success fires only if no custom matched. Exactly one out-edge per fire.
      properties:
        success_next_step_id: { type: string, nullable: true }
        error_next_step_id: { type: string, nullable: true }
        custom:
          type: array
          default: []
          items: { $ref: "#/components/schemas/CustomTransition" }

    FlowNodePosition:
      type: object
      description: UI-only persisted x/y on the React Flow canvas. The runtime ignores this.
      properties:
        x: { type: number }
        y: { type: number }

    GlobalNodeFields:
      type: object
      description: |
        Optional fields available on every node EXCEPT start and tool_call. When `is_global`
        is true, the node is reachable from any conversation node without an explicit edge —
        the eval LLM gets it as an additional candidate transition with a strong "prefer
        labeled transitions" bias. Use sparingly (recommended ≤3 globals per flow). Good for
        misclassification recovery and universal escape hatches; bad for happy-path shortcuts.
      properties:
        is_global:
          type: boolean
          default: false
          description: "Mark this node as globally reachable. Only valid on conversation/end/transfer nodes."
        global_jump_description:
          type: string
          nullable: true
          description: |
            REQUIRED when is_global=true. Natural-language condition the eval LLM uses to decide whether
            to jump here. Describe a clear user-side signal, not an agent intent.
            Example: "User reveals they're actually an owner, not a tenant".

    StartNode:
      type: object
      required: [id, type]
      properties:
        id: { type: string }
        type: { type: string, enum: [start] }
        name: { type: string }
        position: { $ref: "#/components/schemas/FlowNodePosition" }
        agent_speaks_first:
          type: boolean
          default: true
          description: >
            Whether the bot speaks first on call connect. When false, the
            bot waits silently for the caller to speak first
            (silence_timeout_secs on the agent still applies).
            For flow agents this OVERRIDES the agent-level
            agent.agent_speaks_first / agent.greeting_message fields.
        greeting:
          type: string
          nullable: true
          description: "Spoken greeting (only used when agent_speaks_first is true). Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations)."
        is_literal:
          type: boolean
          default: false
          description: "When true, speak `greeting` verbatim. When false, treat it as an LLM instruction."
        next_step_id: { type: string, nullable: true }
        auto_advance:
          type: boolean
          default: true
          description: >
            Whether to enter the first conversation node immediately on session start (default `true`).
            When `false`, the bot's greeting is delivered in start-node context only; the first
            conversation node is entered only after the user's first reply (via internal advancement).

    ConversationNode:
      type: object
      required: [id, type, instructions, transitions]
      allOf:
        - $ref: "#/components/schemas/GlobalNodeFields"
      properties:
        id: { type: string }
        type: { type: string, enum: [conversation] }
        name: { type: string }
        position: { $ref: "#/components/schemas/FlowNodePosition" }
        instructions: { type: string, description: "Layered on top of agent.system_prompt as a system message at step entry. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations)." }
        transitions:
          type: array
          items: { $ref: "#/components/schemas/Transition" }

    ToolCallNode:
      type: object
      required: [id, type, transitions]
      description: |
        Deterministic tool dispatch. Tool args are owned by the tool itself
        (`payload_config.static_parameters` for literals plus
        `payload_config.extraction_parameters` for runtime-extracted values) —
        a `tool_call` node carries no per-node `args_template`. The same tool
        used by N flow nodes always sends the same shape; if you need a
        different shape per step, create a separate tool or supply a
        `config_override`. At call start, the effective referenced-tool config is
        registered as a flat argument-submission schema: one named string field
        per `extraction_parameters` entry, with `required` (default `true`)
        controlling which fields must be collected. The model never submits a
        `node_id` or nested `args` object. The runtime assembles standard call
        metadata and static parameters; the submitter exposes only extraction
        fields. Payload merge order is standard metadata, then static parameters,
        then extracted values, so extracted values win deliberate name
        collisions. Keep names unique unless that override is intentional.
        Schemas remain fixed for that live call; tool/config-override edits apply
        on the next call. Stale
        `args_template` payloads on this node type are silently dropped at parse
        time.
      properties:
        id: { type: string }
        type: { type: string, enum: [tool_call] }
        name: { type: string }
        position: { $ref: "#/components/schemas/FlowNodePosition" }
        tool_id: { type: string, format: uuid, nullable: true, description: "References an existing row in the company's tools table" }
        config_override:
          type: object
          additionalProperties: true
          nullable: true
          description: "Per-node override merged shallow over the referenced tool's config (array replacement). Open-shape — each tool type has its own valid keys. For a transfer tool it may set `transfer_method`, `pbx_feature_code` and `pbx_feature_code_hangup_after_secs` (see TransferNode); the merged result is checked when you save, with the same codes."
        transitions: { $ref: "#/components/schemas/ToolCallTransitions" }
        pre_fire_announcement:
          type: boolean
          nullable: true
          description: |
            When true, the platform plays a short hold tone the moment this node fires so the caller
            doesn't sit in silence while the action runs. The tone is platform-controlled (not
            configurable) and stops automatically when the action returns. Use it for actions you
            expect to take more than ~500 ms (webhook to a slow CRM, complex DB lookup); skip it for
            fast actions to avoid making the call feel chatty.
        timeout_secs:
          type: number
          nullable: true
          minimum: 1
          maximum: 600
          description: |
            Per-node hard cap on execution time. When the action doesn't return in this many seconds,
            the runtime cancels it and routes to `error_next_step_id` with a `tool_timeout_after_Ns`
            error. When null/omitted on a webhook tool, the controller uses the effective tool
            `config.timeout_seconds` plus one second of dispatch overhead. Other tool nodes use the
            platform default (30s). Set this only when the flow needs a different node-level limit.

    CallMetadataKey:
      type: string
      description: |
        Built-in keys available under the `{{metadata.<key>}}` interpolation namespace. The runtime
        substitutes per-call metadata at dispatch time — direction-aware so flow authors don't have
        to special-case inbound vs. outbound. User-defined custom keys (declared via
        `FlowConfig.metadata.custom_metadata_keys`) are also available under the same namespace —
        anything not built-in and not passed at dispatch time resolves to an empty string at
        runtime (NOT a save-time error).
      enum:
        - id              # The call id (matches GET /calls/:id).
        - direction       # "inbound" | "outbound" | "web".
        - agent_number    # The platform leg of the call (number we own). Direction-aware.
        - user_number     # The human leg of the call. Direction-aware.
        - agent_name      # Agent display name.

    TransferNode:
      type: object
      required: [id, type]
      allOf:
        - $ref: "#/components/schemas/GlobalNodeFields"
      properties:
        id: { type: string }
        type: { type: string, enum: [transfer] }
        name: { type: string }
        position: { $ref: "#/components/schemas/FlowNodePosition" }
        transfer_to:
          type: string
          nullable: true
          example: "+972501234567"
          description: |
            Where to send the caller: either a phone number or a SIP address.

            - A **phone number** (for example `+972501234567`) is dialled as a second call. It
              can't be used on a call that arrived over a SIP trunk or an extension endpoint.
            - A **SIP address** (`sip:` or `sips:`, for example `sip:reception@pbx.example.com`)
              hands the caller back to your own phone system, which places the new call
              (a SIP REFER). It works on calls that arrived over a
              [username-and-password SIP trunk](/concepts/sip-trunks#transfers). On a call
              that arrived over an [extension endpoint](/concepts/sip-trunks#register-as-an-extension)
              it works differently: no REFER is sent, and Yappr places a new call through
              your extension to the extension or queue in the address (only the part before
              the `@` is used). On any other call the transfer is refused and the agent
              keeps helping the caller.
              On a trunk, your phone system has about nine seconds to have the new call
              answered, and if the transfer fails the call ends. On an extension call the
              new call has about 25 seconds to be answered, and if it fails or isn't
              answered the call also ends. The address must be
              `sip:user@host[:port]`, at most 256 characters, with a user part, and no
              password or `?headers`. A value that starts with `sip:` or `sips:` but is
              malformed is rejected when you save the flow.
          examples:
            - "+972501234567"
            - "sip:reception@pbx.example.com"
        transfer_message: { type: string, nullable: true, description: "Spoken before transferring. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations)." }
        transfer_method:
          type: string
          nullable: true
          enum: [auto, pbx_feature_code]
          default: auto
          description: |
            How a call that arrived through an
            [extension endpoint](/concepts/sip-trunks#hand-the-call-to-your-phone-system-with-its-transfer-code)
            is transferred. `auto` (or leaving it out) uses the transfer code set on the
            extension endpoint (`register.pbx_feature_code`), or the usual dial-back when it
            has none. `pbx_feature_code` uses this node's own code and hang-up time instead,
            as a pair, with nothing taken from the endpoint: it first sends your phone system
            the in-call transfer code (`pbx_feature_code`) followed by the extension, so the
            phone system moves the
            caller itself and Yappr leaves the call; without a hang-up time
            (`pbx_feature_code_hangup_after_secs`), if it doesn't within about 12 seconds,
            Yappr falls back to the dial-back. Ignored on every other call. With
            `pbx_feature_code`, `transfer_to` must name an extension a keypad can dial: up
            to 32 digits, `*` or `#`, as `sip:400@pbx.example.com` or `400`. Anything else
            is rejected when you save (`transfer_method_invalid`,
            `transfer_extension_not_dialable`).
        pbx_feature_code:
          type: string
          nullable: true
          maxLength: 32
          pattern: '^[0-9A-Da-d*#wW]*(\{extension\})?[0-9A-Da-d*#wW]*$'
          examples: ["##", "*2", "#1", "*2{extension}#"]
          description: |
            Your phone system's own in-call transfer code (blind or attended), sent as key presses. Required
            when `transfer_method` is `pbx_feature_code` (`pbx_feature_code_missing`),
            ignored otherwise. 1 to 32 characters: `0`-`9`, `*`, `#`, `A`-`D`, and the
            pauses `w` (half a second) and `W` (one second), with at least one key.
            `{extension}` may appear once and is replaced by the extension; without it
            the extension is sent right after the code (`##` + `400` sends `##400`).
            Anything else is rejected when you save (`pbx_feature_code_invalid`).
        pbx_feature_code_hangup_after_secs:
          type: integer
          nullable: true
          minimum: 1
          maximum: 10
          examples: [4]
          description: |
            Set it when your phone system's code starts an attended transfer that
            completes when the transferring extension hangs up. Yappr hangs up this many
            seconds after the code (counted once its key presses have played); until
            then the agent is off the line, silent and not listening. Because that
            hang-up is the hand-off there is no fallback dial-back, so
            test it once. 4 is a good start. Leave it out (or null) to wait for your
            phone system to end the call, with the dial-back as the fallback. A whole
            number from 1 to 10, only with `transfer_method` `pbx_feature_code`; anything
            else is rejected when you save (`pbx_feature_code_hangup_after_secs_invalid`,
            `pbx_feature_code_hangup_after_secs_without_code`).

    EndNode:
      type: object
      required: [id, type]
      allOf:
        - $ref: "#/components/schemas/GlobalNodeFields"
      description: >
        Terminal. Reaching an End node hangs up the call. For per-call data
        extraction or webhook delivery, use the agent-level
        `extraction_parameters` and `webhook_url` / `webhook_events` fields
        on the agent (those apply uniformly to prompt + flow agents).
      properties:
        id: { type: string }
        type: { type: string, enum: [end] }
        name: { type: string }
        position: { $ref: "#/components/schemas/FlowNodePosition" }
        farewell: { type: string, nullable: true, description: "Spoken before the call ends. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations)." }
        is_literal: { type: boolean, default: false }

    FlowNode:
      description: Discriminated by `type`.
      oneOf:
        - $ref: "#/components/schemas/StartNode"
        - $ref: "#/components/schemas/ConversationNode"
        - $ref: "#/components/schemas/ToolCallNode"
        - $ref: "#/components/schemas/TransferNode"
        - $ref: "#/components/schemas/EndNode"
      discriminator:
        propertyName: type
        mapping:
          start: "#/components/schemas/StartNode"
          conversation: "#/components/schemas/ConversationNode"
          tool_call: "#/components/schemas/ToolCallNode"
          transfer: "#/components/schemas/TransferNode"
          end: "#/components/schemas/EndNode"

    FlowConfig:
      type: object
      required: [nodes]
      description: |
        The full flow definition stored in `agents.flow_config`. Constraints enforced at validate-time
        (any failure returns 400 `FLOW_INVALID` with one issue per problem — see `FlowInvalidError`):

        - Exactly one node of `type=start` (`no_start` / `multiple_starts`).
        - Start node has a `next_step_id` (`start_unwired`).
        - All `next_step_id` references resolve to a real node id (`unknown_target_node`).
        - Node ids are unique.
        - Every conversation node has non-empty `instructions` (`instructions_missing`).
        - Every conversation transition has a non-empty `description` (`transition_description_missing`).
          The description is the natural-language trigger the voice agent reads at runtime to pick a path —
          a bare `label` is not sufficient.
        - Every tool_call node has a `tool_id` (`tool_id_missing`).
        - At most 127 unique typed extraction contracts may be exposed in one flow
          (`too_many_extraction_contracts`). Nodes with identical effective tool/config schemas
          deduplicate.
        - tool_call nodes have a wired `success_next_step_id` (`success_not_wired`).
        - transfer nodes have a `transfer_to` (`transfer_to_missing`): a phone number or a SIP address. A value starting `sip:` or `sips:` that is not a valid SIP address is rejected on save (`transfer_to_invalid_sip`).
        - **Only `end` and `transfer` nodes may be terminal.** conversation and tool_call nodes must
          have at least one outgoing edge (a transition for conversation; `success` for tool_call).
          Violations: `terminal_not_allowed` per offending node, `no_terminal` if the flow has none at all.
        - A flow may no longer contain an `integration_call` node. The native calendar/mailbox step
          is retired; a stored flow that still has one is rejected here and refused by the call
          runtime. Delete the step and rebuild it as a tool step on a connected app.
        - Every node must be reachable from start (`unreachable_node`).
      properties:
        nodes:
          type: array
          minItems: 1
          items: { $ref: "#/components/schemas/FlowNode" }
        flow_config_version: { type: string, default: "1" }
        metadata:
          type: object
          additionalProperties: true
          description: Optional metadata surfaced to the eval LLM context (e.g. agent purpose, customer name conventions).
          properties:
            custom_metadata_keys:
              type: array
              items: { type: string }
              description: |
                User-declared keys that this flow's `args_template` token interpolation expects to
                find under the `{{metadata.<key>}}` namespace at dispatch time. Surfaced in the
                dashboard so callers know which keys to pass in `POST /calls body.metadata`.
                Keys not listed here still resolve at runtime if passed (and to empty string if
                not) — this list is purely a hint for the UI / API consumers.

    FlowVersion:
      type: object
      properties:
        id: { type: string, format: uuid }
        content_hash: { type: string, description: "SHA-256 hex (length=64) of the canonicalized flow_config — identical saves dedupe" }
        created_at: { type: string, format: date-time }
        created_by_email: { type: string, nullable: true, description: "Email of the user who saved this version. NULL for API-key snapshots." }

    FlowTraceEntry:
      type: object
      properties:
        step_id: { type: string }
        kind:
          type: string
          enum: [enter, eval, tool_mock, auto_advance, end]
        decision: { type: string, nullable: true, description: "Chosen transition id or 'stay'" }
        reason: { type: string }
        data:
          description: Tool result that was injected (when kind=tool_mock)
          additionalProperties: true

    ToolConnectionActor:
      type: object
      description: Who started an authorization for this connection - a member of the workspace, or the API key that asked for it. Every connection has one, so this is never null. The id stays after that member leaves the workspace or that key is revoked, so it can name somebody who no longer has access. No name or address is returned; the id is what a caller compares.
      required: [type, id]
      properties:
        type: { type: string, enum: [user, api_key] }
        id: { type: string, format: uuid }
    ToolConnection:
      type: object
      required: [id, toolkit, label, state, connected, enabled, binding_revision, authorization_epoch, disconnect_progress, created_at, updated_at]
      properties:
        id: { type: string, format: uuid, description: Stable Yappr connection ID. }
        toolkit: { type: string }
        label: { type: string, maxLength: 200 }
        provider_identity: { type: [string, 'null'], description: "Verified provider identity, when available." }
        state: { type: string, enum: [disconnected, connecting, verifying, ready, reconnect_required, degraded] }
        connected: { type: boolean, description: An exact account was bound; this does not imply action readiness. }
        enabled: { type: boolean }
        binding_revision: { type: string, pattern: '^[0-9]+$', description: Decimal identity revision. Replacement creates a new revision. }
        authorization_epoch: { type: string, pattern: '^[0-9]+$', description: 'Decimal authorization generation; disconnect invalidates previously accepted authority. "0" on a connection that never bound an account, and a disconnect leaves it there: nothing was ever authorized under it.' }
        disconnect_progress: { type: string, enum: [none, pending, record_deleted, manual_revocation_required, unknown] }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        removed_at: { type: [string, 'null'], format: date-time, description: 'When this record was taken off the list with POST /tool-connections/{id}/remove. Records with a value here are excluded from GET /tool-connections unless you ask for state=removed. Null again once the record is authorized again - a completed POST /tool-connections/{id}/reconnect puts it back on the list.' }
        created_by: { $ref: '#/components/schemas/ToolConnectionActor' }
        started_by: { $ref: '#/components/schemas/ToolConnectionActor' }
        app_name: { type: [string, 'null'], description: 'The app''s display name, such as Google Calendar, for the toolkit slug beside it.' }
        open_attempt:
          type: [object, 'null']
          description: 'The sign-in still open on this connection, started by anyone - a member, another browser or an API key - or null. A reconnect beside one nobody has opened yet replaces it; one a person is in the middle of answers 409 CONNECTION_ATTEMPT_OPEN until it finishes, expires, or is cancelled with POST /tool-connections/attempts/{open_attempt.id}/cancel.'
          required: [id, status, expires_at]
          properties:
            id: { type: string, format: uuid, description: 'The attempt id: read it at GET /tool-connections/attempts/{id}, cancel it at POST /tool-connections/attempts/{id}/cancel.' }
            status: { type: string, enum: [pending_human, claimed, creating_link, awaiting_consent, verifying, reconciliation_required] }
            expires_at: { type: string, format: date-time }
        last_attempt:
          type: [object, 'null']
          description: 'The most recent sign-in on this connection, open or closed, and why it ended. Use it to tell a connection whose sign-in never finished (state connecting, open_attempt null) from one still in progress, and to say why: an open sign-in past expires_at reads as status expired with error_code AUTH_EXPIRED. Start it again with POST /tool-connections/{id}/reconnect.'
          required: [id, status, error_code, expires_at, updated_at]
          properties:
            id: { type: string, format: uuid, description: 'The attempt id, readable at GET /tool-connections/attempts/{id}.' }
            status: { type: string, enum: [pending_human, claimed, creating_link, awaiting_consent, verifying, completed, failed, expired, cancelled, reconciliation_required] }
            error_code: { type: [string, 'null'], description: 'Why it ended, with the same values as error_code on ToolConnectionAuthAttempt.' }
            expires_at: { type: string, format: date-time }
            updated_at: { type: string, format: date-time }
        check:
          description: 'The account''s last connection check (POST /tool-connections/{id}/check), shared by the workspace, or null when it was never checked. Present once the platform keeps checks; a client must treat a missing key as null. state ready and connected say only that the sign-in worked; this says whether the app answered a read.'
          oneOf:
            - { $ref: '#/components/schemas/ConnectionCheck' }
            - { type: 'null' }
    ConnectionCheck:
      type: object
      description: 'What one harmless read through a connected account found. Never a write: the read is the app''s own lookup (its phone numbers, its calendars, the signed-in profile), or for an app with none that is certain to change nothing, no read at all (status not_checked, code no_probe).'
      required: [status, code, reading, reason, action, checked_at]
      properties:
        status:
          type: string
          enum: [working, app_reports_problem, reconnect_needed, unreachable, not_checked]
          description: 'working: the app answered the read. app_reports_problem: it answered with a problem the account has (nothing set up, a missing permission, an error) - the account can still be given to agents, but its actions may fail until it is fixed in the app. reconnect_needed: the app wants the account signed in again (POST /tool-connections/{id}/reconnect). unreachable: it could not be checked just now (the app was busy, timed out or had a passing error of its own); this says nothing about the account, check again in a minute. not_checked: connected, not checked further.'
        code:
          type: string
          enum: [working, no_items, nothing_set_up, permission, reconnect, app_error, rate_limited, unreachable, no_probe, inconclusive]
          description: 'Why, as a code: no_items (the read answered an empty list, such as no calendars), nothing_set_up (the app says what was read does not exist, such as no phone numbers), permission, reconnect, app_error, rate_limited, unreachable, no_probe (no read is certain to change nothing for this app), inconclusive.'
        reading: { type: string, description: 'The same in plain English, ready to show: "Connected, but WhatsApp says no phone numbers are set up."' }
        reason: { type: [string, 'null'], maxLength: 240, description: 'The app''s own words, when it gave any: one line, at most 240 characters, with long numbers cut to their last four digits and anything token-like hidden. Never a response body.' }
        action: { type: [string, 'null'], description: 'The read action that was run, or null when none was.' }
        checked_at: { type: string, format: date-time }
        attempt:
          type: [object, 'null']
          description: 'Only on an account''s kept check (GET /tool-connections): a later check that could not confirm anything (status unreachable or not_checked). It never replaces the verdict above, which stays until a check confirms something or the account is signed in again; this says when that later check ran and why it could not.'
          required: [status, code, checked_at]
          properties:
            status: { type: string, enum: [unreachable, not_checked] }
            code: { type: string, enum: [rate_limited, unreachable, no_probe, inconclusive] }
            checked_at: { type: string, format: date-time }
      example:
        status: app_reports_problem
        code: nothing_set_up
        reading: 'Connected, but WhatsApp says no phone numbers are set up.'
        reason: '(#100) Tried accessing nonexisting field (phone_numbers)'
        action: WHATSAPP_GET_PHONE_NUMBERS
        checked_at: '2026-11-02T11:20:41.000Z'
    ToolConnectionAuthAttempt:
      type: object
      required: [id, connection_id, status, expires_at, next_poll_at]
      properties:
        id: { type: string, format: uuid }
        connection_id: { type: string, format: uuid }
        status: { type: string, enum: [pending_human, claimed, creating_link, awaiting_consent, verifying, completed, failed, expired, cancelled, reconciliation_required] }
        expires_at: { type: string, format: date-time }
        next_poll_at: { type: string, format: date-time }
        error_code:
          type: [string, 'null']
          description: 'Why the attempt ended, when the status alone does not say: AUTH_SUPERSEDED (cancelled - a reconnect replaced it before anyone opened its link), AUTH_EXPIRED (expired), MEMBERSHIP_REMOVED or AUTHORITY_REMOVED (cancelled - the member signing in lost access), AUTH_ACCOUNT_MISMATCH or AUTH_CONFIG_CHANGED (failed), AUTH_LINK_UNKNOWN or AUTH_REDEMPTION_UNKNOWN (the sign-in did not complete). null while open, when finished, and when a person cancelled it.'
        return_path: { type: string, enum: [/en/tools, /he/tools] }
    ToolConnectionHandoff:
      type: object
      required: [connection, attempt, handoff_url]
      properties:
        connection: { $ref: '#/components/schemas/ToolConnection' }
        attempt: { $ref: '#/components/schemas/ToolConnectionAuthAttempt' }
        handoff_url: { type: string, format: uri, description: "Expiring one-time Yappr handoff for an authorized human, on the Yappr dashboard (https://app.goyappr.com/<locale>/tool-connection/<attempt id>#<token>). Treat its fragment as a secret capability; never log it." }
    ToolConnectionError:
      type: object
      properties:
        error: { type: string }
        code:
          type: string
          description: >
            One of CONNECTION_INVALID (fix the request body or query and retry),
            CONNECTION_CURSOR_INVALID (drop the cursor and start the listing again),
            CONNECTION_BODY_TOO_LARGE (send a smaller body),
            CONNECTION_REPLACEMENT_REQUIRED (reconnect accepts mode="replace" only),
            CONNECTION_NOT_FOUND (the connection or attempt is not in this workspace),
            CONNECTION_ATTEMPT_CLOSED (the sign-in attempt already finished — start a new one),
            CONNECTION_STILL_CONNECTED (only a disconnected connection can be taken off the list — send the DELETE first),
            CONNECTION_ATTEMPT_OPEN (an authorization for this connection is still in progress — let it finish,
            expire or cancel it, then take the connection off the list),
            CONNECTION_RATE_LIMIT (ten of this caller's own authorizations are already open — finish,
            cancel or let one expire; or the workspace started more than 120 in ten minutes),
            AUTH_LINK_UNKNOWN or AUTH_REDEMPTION_UNKNOWN (the sign-in did not complete — start a
            new connection rather than reusing the handoff),
            CONNECTION_CONFIG_UNAVAILABLE or CONNECTION_STORAGE_UNAVAILABLE or
            CONNECTION_UNAVAILABLE (temporary; retry the same request unchanged).
            Errors never echo credentials.
    # ── Agent Eval ─────────────────────────────────────────────────────────────
    EvalPersona:
      type: object
      description: >
        Reusable caller archetype consumed by eval cases. The `identity_prompt`
        plus `behavior_traits` shape how the persona LLM responds; the same
        persona can be reused across many cases.
      required: [id, company_id, name, identity_prompt, language, created_at]
      properties:
        id: { type: string, format: uuid }
        company_id: { type: string, format: uuid }
        name: { type: string, example: "Frustrated tenant"  }
        description: { type: string, nullable: true }
        identity_prompt:
          type: string
          description: System prompt fragment defining who the persona is. Written second-person ("You are…").
          example: "You are a 38-year-old tenant calling about a leaking pipe in your kitchen. You're frustrated because this is the third time you've reported it."
        behavior_traits:
          type: object
          additionalProperties: true
          description: >
            Free-form JSON. Common keys: `patience` (low|medium|high), `verbosity`
            (terse|chatty), `cooperation` (cooperative|adversarial), `interruption_tendency`
            (none|occasional|frequent), `accent` / `dialect` hints, `goal` (what the
            persona is trying to achieve in the call).
          example:
            patience: "low"
            verbosity: "chatty"
            cooperation: "cooperative"
            interruption_tendency: "occasional"
            goal: "Get a maintenance technician scheduled today"
        language:
          type: string
          enum: [he, en, ar, ru, fr, es, de, it, pt, nl, tr, pl, uk, hi, ja, ko, zh]
          default: en
          description: "The language the test caller speaks: any call language except multi. One persona is one caller; for a multilingual agent, make one persona per language."
        voice_config:
          type: object
          additionalProperties: true
          description: Forward-compat for v2 voice-mode (TTS/STT loopback). Ignored in text mode.
        created_by: { type: [string, 'null'], format: uuid, description: The member who created it; null for one created with an API key. }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        deleted_at: { type: string, format: date-time, nullable: true }

    Assertion:
      type: object
      description: >
        A single success criterion attached to an eval case, discriminated by `type`
        (the alias `kind` is accepted and behaves identically).
        Each assertion has a `weight` (defaults to 1.0) used in the weighted score
        calculation: `score = sum(weight * passed?1:0) / sum(weight) * 100`. Cases pass
        when `score >= pass_threshold`.
      anyOf:
        - required: [type]
        - required: [kind]
      properties:
        type:
          type: string
          enum: [must_say, must_not_say, must_call_tool, must_reach_node, custom_llm_judge]
          description: >
            Assertion type. Each type reads a different combination of the
            sibling fields below. Accepted alias: `kind`. If both are present,
            `type` wins.
        kind:
          type: string
          enum: [must_say, must_not_say, must_call_tool, must_reach_node, custom_llm_judge]
          description: "Alias for `type`. Provide one or the other, not both."
        weight: { type: number, default: 1.0, minimum: 0, description: "Relative weight in the case score." }
        description: { type: string, nullable: true, description: "Optional human-readable note shown in the dashboard alongside this assertion." }
        # must_say / must_not_say
        pattern:
          type: string
          nullable: true
          description: >
            For `must_say` / `must_not_say`: a regex evaluated against the
            full agent transcript (case-insensitive by default). For literal
            punctuation, escape with backslashes (e.g. `goodbye\\?`) — or use
            `phrase`, which needs no escaping.
        phrase:
          type: string
          nullable: true
          description: >
            For `must_say` / `must_not_say`: the text to look for, matched as a
            plain substring by default (regex metacharacters are NOT special —
            `12.30` matches only `12.30`). Set `match_type: regex` to compile it
            instead. Supply either `phrase` or `pattern`; `pattern` wins if both
            are present. An assertion with neither fails with an explicit reason
            rather than matching nothing.
        match_type:
          type: string
          enum: [substring, regex]
          nullable: true
          description: >
            How to interpret `phrase` / `pattern`. Defaults to `substring` for
            `phrase` and `regex` for `pattern`.
        case_sensitive:
          type: boolean
          default: false
          description: "Match case-sensitively. Applies to `phrase` and `pattern` alike."
        # must_call_tool
        tool_name: { type: string, nullable: true, description: "`must_call_tool` only: name of a tool the agent must invoke at least once during the run." }
        args_match:
          type: object
          additionalProperties: true
          nullable: true
          description: >
            `must_call_tool` only: optional shape the tool's arguments must
            match. Each key must equal the value. The sentinel `"$present"`
            checks the key exists with a non-null value.
        # must_reach_node
        node_id:
          type: string
          nullable: true
          description: >
            `must_reach_node` only: flow node id the run must enter, matched
            against the `node_entered` events in `GET /agent-eval/runs/{id}/turns`.
            Only meaningful for flow agents; for prompt-mode agents it fails with
            a reason saying no flow nodes were entered. On failure the reason
            lists the nodes the flow did reach.
        # custom_llm_judge
        rubric:
          type: string
          nullable: true
          description: >
            `custom_llm_judge` only: natural-language rubric an LLM scores the run
            against. The judge sees the full transcript (both sides), the business
            tool calls with their arguments, and the flow nodes entered; internal
            routing calls (`pick_transition` and argument submitters) are excluded
            so a "must not call any tool" rubric isn't tripped by flow bookkeeping.
            Judging is strict — anything the run doesn't positively demonstrate
            fails. If the judge is unreachable the assertion fails with the reason
            rather than passing silently.

    AssertionResult:
      type: object
      description: One assertion's outcome after the run completed.
      required: [assertion, passed, weight]
      properties:
        assertion: { $ref: "#/components/schemas/Assertion" }
        passed: { type: boolean }
        weight: { type: number }
        reason: { type: string, nullable: true, description: "Short human-readable explanation. For LLM judges this is the judge's verdict." }

    Evaluation:
      type: object
      description: Roll-up of assertion results that's also stored on `eval_runs.evaluation`.
      required: [score, pass_fail, results]
      properties:
        threshold: { type: number, minimum: 0, maximum: 100, description: "The case's pass_threshold the score was judged against." }
        score: { type: number, minimum: 0, maximum: 100, description: "Weighted percentage of assertions that passed." }
        pass_fail: { type: boolean, description: "True iff `score >= case.pass_threshold`." }
        results:
          type: array
          items: { $ref: "#/components/schemas/AssertionResult" }

    EvalSuite:
      type: object
      description: Curated bundle of eval cases that run as one batch (regression sweep).
      required: [id, company_id, name, parallelism, created_at]
      properties:
        id: { type: string, format: uuid }
        company_id: { type: string, format: uuid }
        name: { type: string }
        description: { type: string, nullable: true }
        agent_id:
          type: string
          format: uuid
          nullable: true
          description: >
            Optional default agent for ad-hoc cases added to the suite. Per-case
            `agent_id` always wins; this is just a convenience for the dashboard.
        parallelism:
          type: integer
          minimum: 1
          maximum: 16
          default: 1
          description: Max concurrent cases when the suite runs.
        created_by: { type: [string, 'null'], format: uuid }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        deleted_at: { type: string, format: date-time, nullable: true }

    EvalCase:
      type: object
      description: A specific eval scenario — persona + target agent + scenario + success criteria.
      required: [id, company_id, agent_id, persona_id, name, scenario, success_criteria, max_turns, pass_threshold, tool_policy, created_at]
      properties:
        id: { type: string, format: uuid }
        company_id: { type: string, format: uuid }
        agent_id:
          type: string
          format: uuid
          description: Agent under test. Full agent record is expanded inline as `agent` in API responses.
        agent: { $ref: "#/components/schemas/Agent" }
        persona_id: { type: string, format: uuid }
        persona: { $ref: "#/components/schemas/EvalPersona" }
        suite_id:
          type: string
          format: uuid
          nullable: true
          description: Optional parent suite. When null, the case is ad-hoc — runnable on its own but not part of a regression sweep.
        suite:
          description: The parent suite expanded inline on single-case and list reads; null for an ad-hoc case.
          oneOf: [{ type: 'null' }, { $ref: "#/components/schemas/EvalSuite" }]
        name: { type: string, example: "Yes path — caller agrees on first ask"  }
        description: { type: string, nullable: true }
        scenario:
          type: string
          description: >
            Free-form one-paragraph framing the persona LLM is given on top of
            its identity. Describe the situation that prompted the call.
          example: "The persona is responding to a missed call from your business about their recent inquiry. They have time to talk for 5 minutes."
        success_criteria:
          type: array
          items: { $ref: "#/components/schemas/Assertion" }
          description: Array of assertions evaluated after the run completes.
        max_turns:
          type: integer
          minimum: 1
          maximum: 100
          default: 20
          description: Hard cap on conversation turns. Hitting this terminates the run with `termination_reason='max_turns'`.
        pass_threshold:
          type: number
          minimum: 0
          maximum: 100
          default: 80
          description: Weighted-score threshold (0-100) for `pass_fail=true`.
        agent_overrides:
          type: object
          additionalProperties: true
          nullable: true
          description: >
            Optional per-case overrides applied to the agent's saved config at run
            time (e.g. a different `system_prompt` or `flow_config` for A/B testing).
            Same shape as the agent record. The agent on disk is never mutated.
            Configuration only: the identity fields `id`, `company_id`,
            `company_timezone`, `tools` and `flow_tools` are stored but ignored at
            run time — a run always executes as the agent's own workspace, with the
            tools that workspace resolved.
        tool_policy:
          type: string
          enum: [mock, real, allowlist]
          default: mock
          description: >
            How the agent's tools behave during the run. Applies to BOTH agent
            types — a flow agent's `tool_call` steps and the tools attached to a
            single-prompt agent, which the model calls directly. `mock`
            (default): webhook tools make no request — each returns the fixed
            synthetic result
            `{"success": true, "status_code": 200}`. The canonical request body is
            still assembled (so argument-resolution bugs still surface, and
            `must_call_tool` + `args_match` still assert against it), but target
            validation and the network hop are skipped, so `mock` does not prove
            the endpoint is reachable or acceptable. Because the synthetic body is
            fixed, a step whose transitions branch on the response CONTENT always
            takes its success edge under `mock`. `real`: tools fire for real
            (charges real money, hits real systems). `allowlist`: webhook tools
            matching an entry in `tool_allowlist` fire for real, the rest return
            the same synthetic success. Note that `allowlist` differentiates
            webhook tools ONLY — steps calling a connected app (Google Calendar,
            Gmail) dispatch for real under both `real` and `allowlist`, because
            those are gated separately and have no per-tool name to match on. Use
            `mock` to hold those back too. Hang-up and transfer tools are
            policy-independent: they make no request, so in a run they simply end
            it (a transfer never places a call to its destination).
        tool_allowlist:
          type: array
          items: { type: string }
          default: []
          description: >
            Used only when `tool_policy='allowlist'`. Entries match a tool's `id`
            or its `name`, exactly and case-sensitively. Prefer ids: tool names are
            not unique within a company, so a name arms every tool that shares it.
            An entry that matches nothing is mocked rather than fired — a typo
            fails safe, and shows in the run trace as `dispatched: false`.
        created_by: { type: [string, 'null'], format: uuid }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        deleted_at: { type: string, format: date-time, nullable: true }

    SuiteRunSummary:
      type: object
      description: |
        Aggregate roll-up of one suite execution. Computed on demand from the
        eval_runs grouped by suite_run_id. The `runs` array (per-run details)
        is added by the per-execution endpoint but omitted from list responses.
      required: [suite_run_id, suite_id, total_runs, completed, in_flight, passed, failed, cancelled, total_cost_cents]
      properties:
        suite_run_id: { type: string, format: uuid }
        suite_id: { type: string, format: uuid, nullable: true }
        started_at: { type: string, format: date-time, nullable: true, description: "Earliest started_at across runs." }
        ended_at: { type: string, format: date-time, nullable: true, description: "Latest ended_at across runs. null until in_flight === 0." }
        total_runs: { type: integer }
        completed: { type: integer, description: "Runs with status='completed'." }
        in_flight: { type: integer, description: "Runs with status in (queued, running). 0 means the suite has settled." }
        cancelled: { type: integer }
        passed: { type: integer, description: "Completed runs with pass_fail=true." }
        failed: { type: integer, description: "Completed runs with pass_fail=false." }
        score_avg: { type: number, nullable: true, description: "Mean of completed runs' scores. null when 0 completed." }
        pass_rate: { type: number, nullable: true, description: "passed / completed (0..1). null when 0 completed." }
        total_cost_cents: { type: integer, description: "Sum across all runs in this suite_run." }

    EvalRun:
      type: object
      description: One execution of a case. Append-only after creation except for status/billing/lifecycle fields.
      required: [id, company_id, status, mode, created_at]
      properties:
        id: { type: string, format: uuid }
        company_id: { type: string, format: uuid }
        case_id: { type: string, format: uuid, nullable: true, description: "FK; nullable because cases can be deleted while runs are kept as history." }
        case: { $ref: "#/components/schemas/EvalCase" }
        persona:
          description: The persona expanded inline on GET /agent-eval/runs/{id} only.
          oneOf: [{ type: 'null' }, { $ref: "#/components/schemas/EvalPersona" }]
        agent:
          description: The agent under test expanded inline on GET /agent-eval/runs/{id} only.
          oneOf: [{ type: 'null' }, { $ref: "#/components/schemas/Agent" }]
        suite_id: { type: string, format: uuid, nullable: true }
        suite_run_id:
          type: string
          format: uuid
          nullable: true
          description: |
            Groups runs spawned by a single `POST /agent-eval/suites/{id}/run` call.
            Pass to `GET /agent-eval/suites/{id}/runs/{suite_run_id}` for the aggregate.
        status:
          type: string
          enum: [queued, running, completed, failed, cancelled]
          description: >
            User-facing run status. Flips to `completed`/`failed` as soon as
            the conversation ends — BEFORE the worker scores assertions and
            bills. **Do not treat `score` / `pass_fail` / `total_cost_cents`
            as final until `queue_status === "done"`.**
        queue_status:
          type: string
          enum: [pending, claimed, done]
          description: >
            Internal worker pipeline state. `pending` = waiting in queue,
            `claimed` = the cron worker has dispatched it to the voice runtime,
            `done` = the worker has finished scoring + billing.
            Always poll for `queue_status === "done"` before reading the
            scoring / billing fields. The transient window between
            `status === "completed"` and `queue_status === "done"` is
            typically &lt; 5 seconds but can be longer under contention.
        queue_attempts: { type: integer, description: How many times the run has been picked up for execution. }
        queue_locked_until: { type: [string, 'null'], format: date-time, description: Until when the current pickup holds the run. }
        mode:
          type: string
          enum: [text, voice]
          default: text
          description: Always `text` in v1. `voice` is reserved for the future loopback mode.
        agent_id: { type: string, format: uuid, nullable: true, description: "Denormalized snapshot — same as `case.agent_id` at the moment the run was created." }
        persona_id: { type: string, format: uuid, nullable: true }
        started_at: { type: string, format: date-time, nullable: true }
        ended_at: { type: string, format: date-time, nullable: true }
        duration_ms: { type: integer, nullable: true }
        score: { type: number, nullable: true, minimum: 0, maximum: 100 }
        pass_fail: { type: boolean, nullable: true }
        termination_reason:
          type: string
          nullable: true
          enum: [persona_goodbye, agent_ended, max_turns, timeout, error, cancelled]
          description: Why the run stopped.
        evaluation:
          $ref: "#/components/schemas/Evaluation"
          description: Populated when status is `completed` or `failed`.
        # Billing fields
        agent_input_tokens: { type: integer, default: 0 }
        agent_output_tokens: { type: integer, default: 0 }
        persona_input_tokens: { type: integer, default: 0 }
        persona_output_tokens: { type: integer, default: 0 }
        agent_cost_cents: { type: integer, default: 0 }
        persona_cost_cents: { type: integer, default: 0 }
        total_cost_cents: { type: integer, default: 0, description: "Total amount debited from the company's credit balance for this run." }
        error:
          type: string
          nullable: true
          description: >
            Populated when `status='failed'`. Stable machine-readable codes:
            `insufficient_credits`, `agent_inactive` (the agent under test is
            deactivated — reactivate it and re-run), `eval_unreachable`,
            `eval_dispatch_failed`, `eval_timeout`, `eval_failed`. Anything else is
            a free-text detail; treat an unrecognized value as `eval_failed`.
        agent_overrides:
          type: object
          additionalProperties: true
          nullable: true
          description: Snapshot of the case's `agent_overrides` plus any per-run overrides supplied at create time.
        created_by: { type: [string, 'null'], format: uuid }
        created_at: { type: string, format: date-time }

    EvalRunTurn:
      type: object
      description: Append-only per-message row from an eval run. Ordered by `turn_number`.
      required: [id, run_id, turn_number, role, created_at]
      properties:
        id: { type: string, format: uuid }
        run_id: { type: string, format: uuid }
        turn_number: { type: integer, minimum: 0, description: "Monotonic counter starting at 0 for the very first turn." }
        role:
          type: string
          enum: [persona, agent, tool_result, flow_event]
          description: >
            `persona` and `agent` are LLM-generated text turns. `tool_result` rows
            carry the synthetic-or-real tool result injected back into the agent.
            `flow_event` rows mirror the flow_node_entered / flow_eval_decision /
            flow_tool_result events emitted by flow agents during the run.
        text: { type: string, nullable: true, description: "Spoken (would-be-spoken) text. Always present for persona/agent rows." }
        tool_calls:
          type: array
          nullable: true
          description: >
            Tool invocations recorded for this turn — both the functions the agent
            called itself and the server-side fires of a flow's tool / connected-app
            steps. This is the field `must_call_tool` matches on (by exact
            `tool_name`, with `args_match` compared against `args`). On a
            `role='tool_result'` row the object carries `tool_name`, `args` (the
            request body that was, or would have been, sent), `result`, `error`,
            `duration_ms`, and — only under a tool policy that could hold the step
            back (`mock` / `allowlist`) — `dispatched`: `false` for a step whose
            request was assembled but never sent, `true` for one that really fired.
            Under `tool_policy: "real"` the field is absent, because nothing could
            have held the step back. It covers webhook tools (a flow step or a
            prompt agent's own tool) and connected-app steps alike.
          items:
            type: object
            additionalProperties: true
        flow_event:
          type: object
          additionalProperties: true
          nullable: true
          description: Flow-event payload (only when `role='flow_event'`).
        input_tokens: { type: integer, default: 0 }
        output_tokens: { type: integer, default: 0 }
        cost_micros: { type: integer, default: 0, description: "This turn's cost in millionths of a US cent. A run sums each side and rounds it up to whole cents on its own (agent_cost_cents, persona_cost_cents); total_cost_cents is those two added together." }
        latency_ms: { type: integer, nullable: true }
        created_at: { type: string, format: date-time }

    BillingTransaction:
      type: object
      description: |
        One row of `GET /billing/transactions`. A usage row folds one day (on the statement's clock) of one product's
        charges (`id` and `description` null, `count` the number of charges); a `starting_balance`
        row is the balance no ledger entry records (`id` and `description` null); every other row
        is one ledger entry (`count` 1).
      required: [id, type, product, date, created_at, description, count, status, amount_cents, affects_balance, payment]
      properties:
        id:
          type: string
          format: uuid
          nullable: true
          description: The entry's id — the one `GET /billing/transactions/{id}` reads. Null on a usage row and a starting balance.
        type:
          type: string
          enum: [top_up, gift, usage, refund, adjustment, phone_number, starting_balance, other]
          description: >
            `top_up` — credits you paid for. `gift` — credits Yappr added with no payment behind
            them, such as the one-time US$5 (500 credits) a new account gets on the first workspace
            it creates, once its phone number is verified. `usage` — calls and Agent Eval runs, one
            row per day per product. `refund` — a top-up that was refunded or disputed, taking its
            credits back out. `adjustment` — a
            manual correction by Yappr, in either direction. `phone_number` — a number's first
            charge or monthly renewal, paid by card. `starting_balance` — a balance Yappr set with
            no ledger entry behind it, dated when the credit account was opened (the ledger does
            not say when it was set); before it the balance is 0. `other` — anything newer than
            this list.
        product:
          type: string
          enum: [voice_call, eval_run]
          nullable: true
          description: On a usage row, what was charged. Null on every other row.
        date:
          type: string
          format: date
          description: The day of the entry on the statement's clock (`range.timezone`), or of the charges a usage row folds.
          example: "2026-09-23"
        created_at:
          type: string
          format: date-time
          description: When the entry was recorded. On a usage row, the day's last charge.
        description:
          type: string
          nullable: true
          description: The entry's own description. Null on a usage row. A `gift` row always reads `Credits from Yappr`.
        count:
          type: integer
          description: >
            How many ledger entries the row stands for. 1 except on usage rows, where it is the
            number of charges: a call that cost nothing has no entry, so a day's `count` can be
            lower than the number of calls Call Logs shows for it.
        status:
          type: string
          enum: [completed, in_progress, pending, failed, refunded]
          description: >
            Usage rows count completed charges only. The row for today (on the statement's clock)
            is `in_progress`: the day is still running and its amount can still grow. Every earlier
            usage row is `completed`.
        amount_cents:
          type: integer
          description: Signed for the account holder — positive put credits in, negative took them out (or, for a phone number, was charged to the card).
        affects_balance:
          type: boolean
          description: True when the row moved the credit balance. False for phone numbers (paid by card) and for a row that did not complete.
        payment:
          allOf: [{ $ref: "#/components/schemas/TransactionPayment" }]
          nullable: true
          description: On a `top_up` row, what the payment record holds to match it to a card statement or an invoice. Null on every other row.
    TransactionPayment:
      type: object
      description: |
        What a top-up's payment record holds that you can match to your card statement or an
        invoice. A card line shows the day and the total charged, VAT included; an invoiced
        top-up also has the number printed on its invoice. The payment processor's own ids are
        never returned: they are on nothing you hold. A field the record does not hold is null —
        older top-ups may lack the VAT or the total, and a top-up paid at checkout has no
        invoice.
      required: [channel, invoice_number, receipt_number, total_charged_cents, vat_cents, currency]
      properties:
        channel:
          type: string
          nullable: true
          enum: [checkout, auto_top_up, saved_card]
          description: How the top-up was paid — `checkout` (paid on the payment page from Billing or `POST /billing/topup`), `auto_top_up` (charged automatically when the balance ran low), or `saved_card` (charged to the saved card on request, as top-ups were for a while). Null when the payment record does not say.
          example: auto_top_up
        receipt_number:
          type: string
          nullable: true
          description: The number printed on the card receipt for this top-up, when the payment record holds one; null otherwise. Never a payment processor id.
          example: null
        invoice_number:
          type: string
          nullable: true
          description: The number printed on the invoice for this top-up (automatic top-ups, and saved-card top-ups that were invoiced). Null when there is no invoice.
          example: A1B2C3D4-0007
        total_charged_cents:
          type: integer
          nullable: true
          description: What the card was charged, VAT included — the amount on the card statement. `amount_cents` on the row is the credits, before VAT.
          example: 5900
        vat_cents:
          type: integer
          nullable: true
          description: The VAT in `total_charged_cents`. Null when the VAT was not recorded, even if the total was; `0` only when it was recorded as 0 (a top-up paid before VAT applied).
          example: 900
        currency:
          type: string
          description: The currency of the payment, lower case.
          example: usd

    BillingConsumption:
      type: object
      description: |
        One row of aggregated billing consumption returned by `GET /billing/consumption`.

        Which of the optional keys a row carries follows the request's `group_by`: `period`
        on `day` / `month` (and `total` on `group_by=total`), `agent_id` and `agent_name` on
        `agent`, `agent,disposition` and `agent,source`,
        `disposition_id` and `disposition` on `disposition` and `agent,disposition`,
        `source` on `source` and `agent,source`, `phone_number_id`, `phone_number` and
        `provider` on `phone_number`, and `carrier_account_id`, `carrier_account` and `provider`
        on `carrier_account`. Agent rows also embed `agent`. `product`, `total_amount_cents` and
        `count` are on every row.
      required: [product, total_amount_cents, count]
      properties:
        period:
          type: string
          description: >
            Bucket label. Format depends on the `group_by` query param: ISO date
            (`2026-05-07`), ISO month (`2026-05`), or `total` for an ungrouped sum. A charge is
            dated when it was debited from the balance (a call's charge when the call settled),
            on the report's clock.
          example: "2026-05-07"
        product:
          type: string
          enum: [voice_call, eval_run, phone_number, topup, refund, adjustment]
          description: >
            Product category aggregated — the same six names the `product` filter takes.
            `voice_call` covers paid call minutes, `eval_run` is agent-eval runs,
            `phone_number` is number purchases and monthly rent (paid by card), `topup` is every
            credit purchase — paid top-ups and credits from Yappr alike, negative because they
            put credits in, and a refunded or disputed top-up's reversal, positive (excluded by
            default — opt in with `include_topups=true`; `GET /billing/transactions` names them
            apart), `refund` is a `refund` ledger entry, `adjustment` a manual correction.
        total_amount_cents:
          type: integer
          description: >
            Sum of the bucket's ledger amounts in cents, signed the ledger's way: charges
            positive, credits added (top-ups, credits from Yappr, a card refund of a number)
            negative. The opposite sign from `GET /billing/transactions`.
        count:
          type: integer
          description: >
            Number of charged entries in this bucket: one per charge in the ledger (a call's
            minutes are one entry), not minutes. A call with no charge in the ledger is not in it.
        agent_id:
          type: string
          format: uuid
          nullable: true
          description: >
            Present when the request grouped by agent (`group_by=agent`, `agent,disposition` or
            `agent,source`). Null on a charge with no call behind it (rent, an eval run, a top-up),
            and on a call whose agent has since been deleted — the call keeps its charge.
        agent_name:
          type: string
          nullable: true
          description: >
            The agent's name, beside `agent_id`, so a report needs no second read of GET /agents.
            Archived agents keep theirs. Null wherever `agent_id` is null, and for an agent that
            is not this workspace's. Names are not unique; `agent_id` is.
          example: Dental intake
        agent:
          type: object
          nullable: true
          description: >
            The agent behind `agent_id`, on every agent row: its `id`, `name` and `archived_at`
            (null while it is not archived). Null wherever `agent_id` is null, and for an agent
            that is not this workspace's - a call this workspace was charged for on another
            workspace's agent, which `GET /agents/{id}` answers 404 for.
          properties:
            id: { type: string, format: uuid }
            name: { type: string, nullable: true }
            archived_at: { type: string, format: date-time, nullable: true }
          example: { id: 00000000-0000-4000-8000-0000000000a1, name: Dental intake, archived_at: null }
        disposition_id:
          type: string
          format: uuid
          nullable: true
          description: >
            Present when the request grouped by disposition (`group_by=disposition` or
            `agent,disposition`). Null for a charge with no call behind it, and for a call
            nobody has dispositioned.
        disposition:
          type: string
          nullable: true
          description: >
            The outcome's label, exactly as GET /dispositions returns it. Present when the
            request grouped by disposition; null wherever `disposition_id` is null.
          example: Interested
        source:
          type: string
          nullable: true
          enum: [test, shared_link, api, phone_inbound, phone_outbound, unknown]
          description: >
            Where the call behind this bucket's charges was started, exactly as GET /calls
            reports it. Present when the request grouped by source (`group_by=source` or
            `agent,source`). Null on a charge with no call behind it — a number's monthly
            rent, a top-up, an eval run. `unknown` is a call recorded before origins were
            written down, and is deliberately not a value you can filter GET /calls by.
          example: shared_link
        phone_number_id:
          type: string
          format: uuid
          nullable: true
          description: >
            Present when the request grouped by `phone_number`: the workspace number behind this
            bucket's charges — the number a call used (its from-number, or the number that
            answered), or the number a monthly rent was for. Null on a charge with no number
            behind it: a browser call, a call on a SIP endpoint, an eval run, a top-up. A number
            removed from the workspace keeps its id. The one exception: a call on your own Telnyx
            account from a number removed before 27 September 2026, whose id was not kept, comes
            back with `phone_number_id: null` and its `phone_number`, as a row of its own.
        phone_number:
          type: string
          nullable: true
          description: >
            The number in E.164, beside `phone_number_id`. For a removed number, the number its
            calls carry. Null on a charge with no number behind it, and on a removed number's rent.
          example: "+12025550143"
        provider:
          type: string
          nullable: true
          enum: [external, telnyx]
          description: >
            Whose carrier the number is on: the number's own `provider` from GET /phone-numbers,
            the same word a call from it carries on GET /calls. `external` — your own Telnyx
            account, which billed you for these calls' phone minutes (and the number's rent), so
            the row's amount is Yappr's charge only. `telnyx` — a number bought from Yappr. For a
            removed number, whose account its calls ran on. Null wherever `phone_number` is null.
            On `group_by=carrier_account`: `external` on an account's row, `telnyx` on Yappr's
            carrier (calls on Yappr numbers, and their rent), null with no carrier at all (browser
            and SIP endpoint calls, eval runs).
          example: external
        carrier_account_id:
          type: string
          format: uuid
          nullable: true
          description: >
            Present when the request grouped by `carrier_account`: your Telnyx account the
            bucket's calls ran on - the call's own account, as GET /calls reports it, else its
            number's. Null on Yappr's carrier and with no carrier; `provider` says which.
        carrier_account:
          type: object
          nullable: true
          description: >
            The account behind `carrier_account_id`, named as GET /carrier-accounts names it. Null
            wherever `carrier_account_id` is null, and for an account that is no longer this
            workspace's (its calls keep the id).
          properties:
            id: { type: string, format: uuid }
            name: { type: string }
          example: { id: 00000000-0000-4000-8000-00000000ca01, name: Client A - Telnyx }
        input_tokens:
          type: integer
          description: >
            Input tokens consumed across this bucket. Present only for
            token-metered products (currently `eval_run`); omitted entirely for
            products that do not meter tokens, rather than reported as `0`.
            Eval input counts are large relative to output because the agent's
            conversation context is re-sent on every turn.
          example: 34645047
        output_tokens:
          type: integer
          description: >
            Output tokens produced across this bucket. Present only for
            token-metered products (currently `eval_run`).
          example: 205402
        total_tokens:
          type: integer
          description: >
            `input_tokens + output_tokens`. Present only for token-metered
            products (currently `eval_run`). This is the figure that explains
            the bucket's `total_amount_cents` — eval charges are a direct
            function of tokens consumed.
          example: 34850449

    # ── Deliveries ─────────────────────────────────────────────────────────────
    Delivery:
      type: object
      description: |
        One webhook delivery, as `GET /deliveries` lists it and as a call's own timeline
        carries it. The two shapes are the same: this object is the timeline's `delivery` row
        (which carries the same `id`, `tool_id`, `agent_id`, `retry_of` and `retried_by`) plus
        the `call_id` it happened on and the `source` that says whether it was real traffic or
        a rehearsal.
      required: [kind, id, call_id, tool_id, agent_id, at, event, status, source, retry_of, retried_by]
      properties:
        kind:
          type: string
          enum: [delivery]
          description: >
            Always `delivery`. Carried so a reader parsing a call's timeline and a reader
            paging this list can use one branch, not two.
        id: { type: string, format: uuid }
        call_id:
          type: string
          format: uuid
          nullable: true
          description: The call this delivery was about. Read it with GET /calls/{id}.
        tool_id:
          type: string
          format: uuid
          nullable: true
          description: >
            The tool whose step sent it — the id `?tool_id=` filters on. Null for an agent not
            yet on the workflow engine, which sends in its own name (see `agent_id`).
        agent_id:
          type: string
          format: uuid
          nullable: true
          description: >
            The agent: the one that sent it in its own name, or, for a tool's step, the agent
            whose call it happened on — the id `?agent_id=` filters on. Null for a tool test,
            which happens on no call.
        at:
          type: string
          format: date-time
          description: When the delivery settled — or, on a `pending` row, when it was recorded.
        delivered_at:
          type: string
          format: date-time
          nullable: true
          description: >
            When your endpoint accepted it: the same moment as `at` on a `delivered` row, and
            null on a `failed`, `pending` or `unknown` one, where nothing is known to have been
            delivered. Use `at` for the row's time.
        retry_of:
          type: string
          format: uuid
          nullable: true
          description: The delivery this one re-sent, when it is a retry (`POST /deliveries/{id}/retry`).
        retried_by:
          type: string
          format: uuid
          nullable: true
          description: >
            The retry that re-sent this delivery, if one was made. A delivery is retried at most
            once, so a failure with `retried_by` set is refused `409 DELIVERY_ALREADY_RETRIED` —
            skip it, and read (or retry) the retry instead.
        chain_root_id:
          type: string
          format: uuid
          nullable: true
          description: >
            The first delivery of the chain this row belongs to — the `X-Webhook-Delivery-Id`
            every send of it carried, and the id your endpoint should dedupe on. A first send's
            own `id`; a retry's original (however many retries in); for a `call.dnc_blocked` the
            platform sent again on its own, its first delivery. Null only when it could not be
            read (try again).
        call_request_id:
          type: string
          format: uuid
          nullable: true
          description: >
            The call request (`GET /call-requests/{id}`) a before-call step's request served
            (`event` `call.preparing`, from 2 October 2026). Such a send happens before the call
            exists, so its `call_id` is usually null. Null on every other delivery.
        event:
          type: string
          description: >
            The event that triggered it, spelled as the trigger authored it; `call.preparing` for
            a before-call step's request. A rehearsal's event can carry a `test:` prefix — branch
            on `source`, not on the spelling.
          example: call.answered
        source:
          type: string
          enum: [live, test]
          description: >
            `live` — sent by real traffic: a real call, or a lead event (`lead.created`,
            `lead.updated`), which can belong to no call and then has `call_id: null`. `test` — a
            rehearsal: sent by `POST /tools/{id}/test` (a legacy webhook tool's test, or a
            workflow tool's real test with `policy: allowlist`), which happens on no call and so
            has `call_id: null`, or sent on a test call you placed from the dashboard (the
            agent's **Test** button, in the browser or by phone — the calls `GET /calls` reports
            as `source: "test"`), a before-call step's request on one included.
          example: live
        status:
          type: string
          enum: [delivered, failed, pending, unknown]
          description: >
            `delivered` — your endpoint accepted it. `failed` — it did not, after every
            attempt (it refused, could not be reached, or — for a workflow tool — answered 2xx
            with a body the tool could not use). `pending` — it has not settled yet. `unknown` —
            a workflow tool's request, or a retry, got no answer in time: your endpoint may or
            may not have acted on it.
        response_status:
          type: integer
          nullable: true
          description: The HTTP status your endpoint answered with. Null when nothing answered.
          example: 200
        attempt_count:
          type: integer
          nullable: true
          description: >
            How many times the request has been sent, the one that settled it included, counted
            across retries: a retry of a delivery sent once reads 2 (from 1 October 2026; a retry
            recorded before then reads 1). The `X-Webhook-Delivery-Attempt` of its last send.
        error_code:
          type: string
          nullable: true
          enum: [http_timeout, legacy_http_timeout, http_network_error, downstream_http_error, output_schema_invalid,
            invalid_json_response, response_too_large, url_resolves_private, delivery_failed, null]
          description: >
            Why it did not land, as a code to branch on: `http_timeout` (no answer within the
            limit; the row is `unknown`, so a retry needs `acknowledge_unknown`),
            `legacy_http_timeout` (the same, from an agent's own webhook or a legacy webhook tool,
            which record it `failed` and retry it without asking), `http_network_error` (unreachable, or the connection dropped before an
            answer), `downstream_http_error` (it answered with an error; see `response_status`),
            `output_schema_invalid` / `invalid_json_response` / `response_too_large` (a workflow
            tool's endpoint answered 2xx with something the tool could not use),
            `url_resolves_private`, or `delivery_failed` for anything else. Null on a
            `delivered` or `pending` row. The same codes a tool test and a workflow step use.
          example: http_timeout
        error_message:
          type: string
          nullable: true
          description: >
            One sentence, for a person to read, written only when the delivery failed — for
            example "Webhook did not respond within 30 seconds", or, for a workflow tool that
            answered 2xx without its Outputs, "Webhook answered HTTP 200, but not with the
            tool's outputs (missing: booking_id)", which names the Output fields (never a value).
            Wording may change; branch on `status` and `error_code`.
        tool_name:
          type: string
          nullable: true
          description: >
            The name you know the sender by — the tool whose step sent it, or, for an agent
            not yet on the workflow engine, the agent itself.

    DeliveryDetail:
      description: |
        One delivery, as `GET /deliveries/{id}` and `POST /deliveries/{id}/retry` return it:
        the list's row, field for field, plus what it sent and what came back, its retry
        link, whether it can be retried, where it went and where a retry would go now. Every
        configured header value of the sender is replaced by `[REDACTED]` in either body
        before it leaves the database, and so are the sender's query string and each of its
        values of six characters or more: a value of six characters or more wherever it
        appears (as a value, inside a string, or as a key); a shorter header value only where
        it is the whole body or a whole JSON string in it. Query values shorter than six
        characters are never withheld. An address is returned without its query string, fragment or
        credentials.
      allOf:
        - $ref: "#/components/schemas/Delivery"
        - type: object
          required: [retryable, request, response, retry_target, exchange, bodies_withheld, destination_path_withheld]
          properties:
            exchange:
              type: object
              nullable: true
              description: >
                The delivery's full record (from 21 October 2026): the request exactly as it left
                (the full URL with its query, every header sent, the body) and the answer (status,
                every header, the body), each secret `"[REDACTED]"` and named in `masked`, the same
                record `GET /calls/{id}` gives each tool call. The answer's body is what the
                endpoint returned, at most 2,000 characters for a webhook delivery. Kept for 90
                days, then `details_expired` is true and `request` and `response` are null. Null for
                a delivery made before records began. Bodies are null when `bodies_withheld`; the
                URL is `scheme://host` when `destination_path_withheld`.
              properties:
                id: { type: string }
                status: { type: string, enum: [succeeded, failed, timeout, unreachable, refused, not_sent, unknown] }
                started_at: { type: string, format: date-time, nullable: true }
                duration_ms: { type: integer, nullable: true }
                request:
                  nullable: true
                  allOf: [{ $ref: "#/components/schemas/ToolExchangeRequest" }]
                response:
                  nullable: true
                  allOf: [{ $ref: "#/components/schemas/ToolExchangeResponse" }]
                masked: { type: array, items: { type: string } }
                details_expired: { type: boolean }
            bodies_withheld:
              type: boolean
              description: >
                True when the key does not hold `calls:read`: the two bodies carry call data (the
                caller, the numbers, what was collected), so a key reading the log with
                `tools:read` alone gets `request.body` and `response.body` as null.
            destination_path_withheld:
              type: boolean
              description: >
                True when the key holds neither `tools:read` nor `tools:update`: an address is the
                tool's configuration, and for a Make or Zapier hook its path is the credential, so
                `request.destination` and `retry_target.destination` are `scheme://host` only.
            test_id:
              type: string
              format: uuid
              nullable: true
              description: >
                The tool test that sent it (`GET /tools/{id}/tests/{test_id}`): a test delivery has
                an id of its own, so this is the way back. Null for anything else, and for a retry
                of a test.
            retryable:
              type: boolean
              description: >
                True when `POST /deliveries/{id}/retry` would send it: it failed (and was not
                answered with a 2xx) or is `unknown` (sent again only with
                `acknowledge_unknown: true`), it has not already been retried (`retried_by` is
                null), its sender is still a webhook with an address, and its tool is not
                archived.
            tool_archived:
              type: boolean
              description: >
                True when the tool that sent it is archived: it cannot be retried
                (`404 WORKFLOW_TOOL_ARCHIVED`) until the tool is restored with
                `POST /tools/{id}/restore`.
            request:
              type: object
              properties:
                destination:
                  type: string
                  nullable: true
                  description: >
                    Where it was sent, when it was sent — `scheme://host/path`, without the query
                    string, fragment or credentials; `scheme://host` when
                    `destination_path_withheld`. Null for a delivery made before destinations were recorded
                    (then `recorded` is false).
                  example: https://crm.example.com/status/500
                tool_revision_id:
                  type: string
                  format: uuid
                  nullable: true
                  description: >
                    The workflow tool revision that sent it. Null for a legacy webhook tool, an agent's
                    own webhook, and deliveries made before destinations were recorded.
                recorded:
                  type: boolean
                  description: >
                    True when the delivery recorded what it was sent with. When false (an older
                    delivery), `method` and `header_names` are the sender's current ones.
                method:
                  type: string
                  nullable: true
                  description: The HTTP method it was sent with (the sender's current one when `recorded` is false).
                  example: POST
                timeout_ms:
                  type: integer
                  nullable: true
                  description: >
                    How long the endpoint was given to answer: the limit of the tool revision that
                    sent it, 30000 for an agent's own webhook, a legacy webhook tool's current
                    setting. Null when not known.
                  example: 10000
                header_names:
                  type: array
                  items: { type: string }
                  description: >
                    The name of every header it was sent with, the platform's own included -
                    `X-Webhook-Delivery-Id`, `X-Webhook-Delivery-Attempt`, `User-Agent`, and where
                    sent `X-Webhook-Event`, `X-Webhook-Test`, `X-Webhook-Retry-Of`, `Content-Type`
                    (from 1 October 2026; an older delivery lists the configured ones, and the
                    sender's current ones when `recorded` is false). A configured header's value is never
                    returned; the platform's own are, in `platform_headers`.
                platform_headers:
                  type: object
                  additionalProperties: { type: string }
                  description: >
                    The values the platform set on this send, by header name - they carry no secret:
                    `X-Webhook-Delivery-Id` (the chain's first delivery, `chain_root_id` - dedupe on
                    it), `X-Webhook-Retry-Of` (on a retry, the delivery it re-sent),
                    `X-Webhook-Delivery-Attempt`, `X-Webhook-Event`, `X-Webhook-Test`, and
                    `User-Agent` / `Content-Type` unless the sender configured its own. Only the
                    headers in `header_names`; empty when `recorded` is false.
                  example:
                    X-Webhook-Delivery-Id: 024a8da9-68ed-44f4-9355-b6ee5c7e02a7
                    X-Webhook-Delivery-Attempt: "1"
                    User-Agent: Yappr-Webhooks/1.0
                    Content-Type: application/json
                revision:
                  type: integer
                  nullable: true
                  description: >
                    The number of the tool revision that sent it (`tool_revision_id`). Null when
                    that is null. A body's `call.version` is the call package's format version, not
                    this number.
                body:
                  nullable: true
                  description: >
                    The body that was sent, as stored when it was sent. A retry re-sends exactly
                    this. JSON; for a `GET` sender these fields went as query parameters. Null
                    when `bodies_withheld`.
            response:
              type: object
              properties:
                status:
                  type: integer
                  nullable: true
                  description: The HTTP status the endpoint answered with; null when nothing answered.
                body:
                  type: string
                  nullable: true
                  description: >
                    What the endpoint answered, as text, at most 2,000 characters; `""` for an
                    empty answer. A workflow step or tool test the endpoint accepted keeps what came
                    back (from 27 September 2026). Null when nothing was kept: nothing answered, the
                    delivery was made before the answer was stored (September 2026), or a workflow
                    step's endpoint refused it or answered with a body the tool could not use — the
                    workflow engine keeps the status, not that text. A retry always keeps it. Null
                    too when `bodies_withheld`.
            retry_target:
              type: object
              nullable: true
              description: >
                Where `POST /deliveries/{id}/retry` would send it now — the sender's current
                address, which is not always where this delivery went. Null when the sender is no
                longer a webhook with an address.
              properties:
                destination:
                  type: string
                  description: The sender's current address, in the same form as `request.destination`.
                  example: https://crm.example.com/post
                tool_revision_id:
                  type: string
                  format: uuid
                  nullable: true
                  description: The workflow tool revision a retry would be sent with. Null for a legacy sender.
                changed:
                  type: boolean
                  description: True when that address is not where this delivery went.

    # ── Campaigns ──────────────────────────────────────────────────────────────
    Campaign:
      type: object
      description: |
        A paced bulk-outbound dialing job over enrolled contacts.

        A campaign is an **admission-only scheduler**. It decides *when* each enrolled
        contact becomes eligible, then performs one ordinary outbound call — the same
        queue, the same priority, and the same concurrency limits as a call placed with
        `POST /calls`. The pacing fields below only control how fast a campaign hands
        calls to that queue; a campaign call never takes precedence over anything else.

        Campaigns are always created as `draft` and are launched with
        `POST /campaigns/{id}/launch`.

        **Two independent per-contact stop conditions** apply, whichever fires first:
        `max_attempts`, and the stop-disposition set (`stop_disposition_ids` plus the
        `stop_on_*` booleans). Landing a stop disposition retires that contact
        permanently; any other outcome retries until the attempt cap.

        Fields marked *Engine-owned* are written by the campaign engine and are never
        writable. Sending one on create or update returns `400`, as does any field name
        that isn't on the writable list — a misspelled `stop_dispositions` is rejected
        rather than silently ignored, so you can never believe a kill switch is armed
        when it is not.
      properties:
        id: { type: string, format: uuid }
        company_id: { type: string, format: uuid }
        name: { type: string, example: "July reactivation"  }
        description: { type: string, nullable: true }
        status:
          type: string
          enum: [draft, scheduled, running, paused, paused_insufficient_credit, paused_budget,
                 paused_infra, paused_config, completed, stopped, archived]
          description: |
            Engine-owned. Move it with the transition endpoints
            (`launch` / `pause` / `resume` / `stop`), never with `PATCH`.

            `draft` — created, not dialing.
            `scheduled` — not entered today. A campaign launched before its `starts_at`
            reads `running` and places no call until that moment.
            `running` — admitting contacts.
            `paused` — paused by you. A manual pause is **never** lifted automatically; it
            survives a top-up.
            `paused_insufficient_credit` — balance is below the minimum needed to place a
            call. **Auto-resumes** shortly after the balance is topped up.
            `paused_budget` — `budget_cents` reached, or the workspace's own monthly
            spending limit reached; `pause_reason` says which.
            `paused_infra` — the safeguard: one contact's call could not be placed more
            times than `max_infra_retries` allows (nobody's phone rang). Calls already
            under way finish normally and every contact keeps its place; nothing new is
            dialed until you resume. Not lifted automatically.
            `paused_config` — a permanent configuration problem (from-number no longer
            active, agent missing a call-duration cap, no reachable calling window).
            `completed` — every enrolled contact reached a terminal state.
            `stopped` — stopped by you. Terminal.
            `archived` — soft-deleted by `DELETE /campaigns/{id}`. Terminal.
        pause_reason:
          type: string
          nullable: true
          enum: [manual, insufficient_credit, campaign_budget, workspace_spend_limit,
                 call_placement_failures, configuration, null]
          description: |
            Why the campaign is paused, or `null` when it is not. Read-only.
            `manual` (`paused`), `insufficient_credit` (`paused_insufficient_credit`),
            `campaign_budget` or `workspace_spend_limit` (both `paused_budget` — this
            campaign's `budget_cents`, or the workspace's monthly limit from
            `PATCH /billing`), `call_placement_failures` (`paused_infra`),
            `configuration` (`paused_config`).
        agent_id:
          type: string
          format: uuid
          nullable: true
          description: Agent that runs the calls. Required before launch.
        agent:
          nullable: true
          description: |
            The Agent for `agent_id`. For a key holding `agents:read` it is the
            same object, field for field, that `GET /agents/{id}` returns for it.
            For a key without `agents:read` it is `{ id, name }` only: the
            campaign never shows a key more of an agent than `GET /agents/{id}`
            would.
          allOf:
            - $ref: "#/components/schemas/Agent"
        split:
          nullable: true
          description: |
            The A/B test on this campaign's calls, or `null` when every contact is
            called by `agent_id`.

            **`percent` is the share of contacts that go to the SECOND agent**
            (`agent_id` inside the object). `agent_id` on the campaign takes the rest.

            A contact is assigned once, on its first admission, and keeps that agent
            for every later attempt — a no-answer redial is the same conversation and
            not a fresh coin toss. Changing `percent` afterwards therefore only affects
            contacts that have not been dialed yet. Changing either agent, or sending
            `null`, does reach contacts already dialed: an assignment to an agent the
            campaign no longer runs is released, and that contact is assigned again on
            its next attempt. Both agents must have a maximum call duration set and be
            able to take calls, or `launch` refuses.

            Both agents are screened against the do-not-call list at enrolment, so a
            contact is never assigned an agent that is not allowed to call it.
          allOf:
            - $ref: "#/components/schemas/AgentSplit"
        split_agent:
          nullable: true
          description: "The Agent for the second agent in `split`, read like `agent`: the object `GET /agents/{id}` returns for a key holding `agents:read`, `{ id, name }` for a key without it."
          allOf:
            - $ref: "#/components/schemas/Agent"
        from_phone_number_id:
          type: string
          format: uuid
          nullable: true
          description: >
            The number the campaign calls from, when it names one. `null` (the default) calls from the
            agent's own number: a number the agent calls from (its outbound agent, or either half of
            the number's outbound split), else one it answers on; a Yappr number before one on your
            own Telnyx account. An A/B split calls from the first agent's number for both halves. A
            create or edit that leaves it `null` on an agent with no number is `400
            CAMPAIGN_REQUEST_INVALID` (`invalid_from_number` at `/from_phone_number_id`); at launch
            the number must still be active. If this number is released, the campaign calls from
            its agent's own number from then on.
        from_phone_number:
          nullable: true
          description: >
            The PhoneNumber for `from_phone_number_id`. For a key holding
            `phone_numbers:search` it is exactly the object GET /phone-numbers
            returns, and only that. For a key without it, it is
            `{ id, friendly_name, number: null }`: which number, and what it costs,
            are that scope's to show (`friendly_name` is null too when it spells
            the number). The carrier account's own plumbing (provider and order
            ids, SIP trunk/credential identifiers, SIP usernames and secrets) is
            never part of it.
          allOf:
            - $ref: "#/components/schemas/PhoneNumber"
        from_number:
          type: string
          nullable: true
          description: >
            Engine-owned. E.164 number the campaign calls from: `from_phone_number`'s, or its
            agent's own number when `from_phone_number_id` is `null`. Written on create, edit and
            launch, and on every dialling round, so it follows the agent onto a new number; kept for
            audit even if the number is later released. `null` until the campaign has an agent or a
            number that can call, and for a key without `phone_numbers:search`, as
            `from_phone_number.number` is.
          example: "+972551234567"
        variables:
          type: object
          additionalProperties: { type: string }
          description: >
            Values for the agent's `{{placeholders}}` on every call this campaign places.
            `FirstName` and `FullName` are filled on each call from its contact's own name
            (the first word of it, and the whole of it; a household, a title or half of a
            given name keeps the whole name under `FirstName`: "משפחת כהן"); the value here
            is what a contact with no name hears. `{}` when none are set.
        calling_window:
          type: object
          additionalProperties: true
          description: >
            Optional campaign-level narrowing of the workspace calling hours. Omit to
            inherit the workspace schedule (`GET /call-windows`). A campaign can only
            ever dial inside the workspace window — this field cannot widen it.
            `{ tz, days: [0..6], start: "HH:MM", end: "HH:MM" }`. `tz` is an IANA zone
            name and is required whenever `days`, `start` or `end` is present: hours
            without a zone are ambiguous, so they are refused rather than read against
            a zone you did not pick. `days` lists each day once and is never empty;
            `start` and `end` come together and `end` is later than `start` (no
            zero-minute window, none past midnight). Anything else is 400
            CAMPAIGN_REQUEST_INVALID, naming the value.
        stop_disposition_ids:
          type: array
          items: { type: string, format: uuid }
          description: |
            Disposition **IDs** that retire a contact permanently when assigned — the
            campaign's kill switch. Always IDs, never labels: labels are renameable, and a
            rename would silently disarm the rule.

            `No Answer`, `Failed`, `Voicemail` and `Unclassified` are refused here with
            `400`. The platform assigns them by itself (`No Answer` on every unanswered
            ring), so listing one retires the contact the first time it lands, before any
            retry, and `Voicemail` or `Unclassified` can land on a call someone answered.
            Use `stop_on_no_answer`, `stop_on_voicemail` and `stop_on_unclassified` instead.

            Must contain dispositions belonging to your company; anything else is rejected
            with `400`.
        stop_dispositions:
          type: array
          description: "Full Disposition objects for `stop_disposition_ids`."
          items: { $ref: "#/components/schemas/Disposition" }
        stop_on_no_answer:
          type: boolean
          example: false
          description: Retire a contact the first time a call goes unanswered.
        stop_on_voicemail:
          type: boolean
          example: false
          description: Retire a contact the first time a call reaches an answering machine.
        stop_on_unclassified:
          type: boolean
          example: false
          description: >
            What to do when the outcome that arrives is `Unclassified` — the call
            happened but could not be matched to any of your outcomes. `false` retries
            the contact, `true` retires it.

            This is not a timeout. A call's outcome is authoritative and a contact is
            never advanced without one: if classification is slow, only that contact
            waits while the campaign keeps calling everyone else.
        max_attempts:
          type: integer
          minimum: 1
          maximum: 999
          example: 3
          description: >
            Per-contact dial cap. One of the two independent stop conditions — the other is
            the stop-disposition set.
        max_infra_retries:
          type: integer
          minimum: 0
          maximum: 20
          example: 3
          description: >
            The safeguard: how many retries one contact gets after a platform-side failure
            — a call that never reached the person — before the whole campaign pauses as
            `paused_infra`. A count, not money: the money limits are `budget_cents` and the
            workspace's monthly spending limit. These retries do not consume `max_attempts`
            and are never terminal.
        retry_no_answer_seconds:
          type: integer
          minimum: 30
          maximum: 604800
          example: 3600
          description: Delay before retrying a contact who did not answer.
        retry_completed_seconds:
          type: integer
          minimum: 60
          maximum: 604800
          example: 86400
          description: Delay before retrying a contact whose call completed but landed on a non-stop disposition.
        randomize_retry_time:
          type: boolean
          example: false
          description: >
            Which time of day a retry lands on. `false` keeps the wait exact, so a one-week
            wait retries at the same hour a week later. `true` picks a different hour inside
            the campaign's calling window, so repeat attempts do not always arrive at the
            same moment. The wait length itself is unchanged either way — a randomized retry
            is still never earlier than the configured wait.
        double_dial_enabled:
          type: boolean
          example: false
          description: Ring a second time shortly after an unanswered first ring.
        double_dial_gap_seconds:
          type: integer
          minimum: 10
          maximum: 3600
          example: 90
          description: Gap between the two rings when `double_dial_enabled` is true.
        max_calls_per_day:
          type: integer
          minimum: 1
          maximum: 100000
          example: 200
          description: Daily admission cap, counted against the workspace timezone day.
        min_seconds_between_calls:
          type: integer
          minimum: 0
          maximum: 86400
          example: 30
          description: Minimum spacing between two calls handed to the queue by this campaign.
        max_in_flight:
          type: integer
          minimum: 1
          maximum: 8
          example: 2
          description: >
            Calls this campaign may have live at once. Platform concurrency limits still
            apply on top — raising this does not buy the campaign extra capacity.
        budget_cents:
          type: integer
          minimum: 1
          nullable: true
          description: >
            This campaign's LIFETIME spend cap, enforced against `spent_cents` +
            `reserved_cents` (credits are debited when a call ends, so in-flight cost has
            to count) plus the next call's hold: twice the agent's `max_call_duration_secs`,
            in minutes, times your workspace's phone-call price per minute
            (`default_rate_per_minute_cents` times `ai_training_multiplier` on
            `GET /billing/rates`). Counted in credits: a credit is one cent.
            A cap below one call's hold is refused with `400` (it would pause the campaign
            before its first call), and launch refuses one stored before that check.
            `null` means no cap. On hit the campaign moves to `paused_budget`.
            Distinct from the workspace's calendar-month limit
            (`monthly_budget_cents`, PATCH /billing), which covers every outbound call in
            the workspace and resets each month: either can pause this campaign and both
            report `paused_budget`.
        regulatory_basis:
          type: string
          nullable: true
          enum: [lawful_basis_confirmed, consent, existing_customer, non_marketing, registry_screened]
          description: >
            Your lawful basis for calling this list. **Required before launch** — recorded on
            the campaign's launch audit record alongside the enrolled count.

            `lawful_basis_confirmed` is what the dashboard records: a single attestation
            that the caller has consent or another lawful basis for everyone on the list.
            The four specific values are for callers that know which one applies.
        starts_at:
          type: string
          format: date-time
          nullable: true
          description: >
            No call is placed before this moment. It does not launch the campaign: a
            campaign launched earlier reads `running` and waits.
        ends_at:
          type: string
          format: date-time
          nullable: true
          description: >
            No new call is placed from this moment; the campaign then moves to
            `completed`. Later than `starts_at`, not already passed, and the
            `calling_window` must open at least once before it.
        daily_admitted_count:
          type: integer
          description: Engine-owned. Calls handed to the queue during the current day window.
        daily_window_date:
          type: string
          format: date
          nullable: true
          description: Engine-owned. Day `daily_admitted_count` belongs to.
        last_admitted_at:
          type: string
          format: date-time
          nullable: true
          description: Engine-owned. When this campaign last handed a call to the queue.
        estimate_cents:
          type: integer
          nullable: true
          description: Engine-owned. Reserved for a projected campaign cost; nothing computes it yet, so it is `null`.
        spent_cents:
          type: integer
          description: Engine-owned. Settled spend so far.
        reserved_cents:
          type: integer
          description: Engine-owned. Worst-case cost of in-flight calls, held against `budget_cents` until they settle.
        last_tick_at:
          type: string
          format: date-time
          nullable: true
          description: Engine-owned. Last time the engine evaluated this campaign.
        last_tick_result:
          type: string
          nullable: true
          description: >
            Engine-owned. Machine-readable answer to "why is nothing happening right now" —
            e.g. daily cap reached, outside the calling window, waiting on in-flight calls.
            `blocked` means another operation held this campaign during the last evaluation
            and it is retried on the next one. Full vocabulary on the campaign stats page.
        last_error:
          type: string
          nullable: true
          description: Engine-owned. Last error the engine recorded for this campaign.
        started_at: { type: string, format: date-time, nullable: true, description: "Engine-owned. First launch time." }
        completed_at: { type: string, format: date-time, nullable: true, description: "Engine-owned. When the last contact reached a terminal state." }
        total_leads: { type: integer, description: "Engine-owned. Contacts currently enrolled." }
        stats:
          type: object
          additionalProperties: true
          description: Engine-owned counter roll-up. Prefer `GET /campaigns/{id}/stats`.
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        created_by: { type: string, format: uuid, nullable: true, description: "Null when the campaign was created via the API." }

    CampaignContact:
      type: object
      description: |
        One contact enrolled in a campaign — the per-contact state machine. Each row
        binds a `Lead` to the E.164 number snapshotted at enrollment, so later edits to
        the lead cannot change which number gets dialed.

        A number can only be dialed by one live campaign at a time; enrolling it elsewhere
        reports it under `in_another_campaign` with the campaign that holds it. A `draft`
        holds no number: when a draft is launched, a contact whose number another
        campaign is calling by then is retired as `excluded` with `stop_reason`
        `in_another_campaign`.
      properties:
        id: { type: string, format: uuid }
        lead_id: { type: string, format: uuid }
        lead:
          nullable: true
          description: "Full Lead object for `lead_id`. A key without `leads:read` reads `{id}` only; the enrollment's own fields, `to_number_e164` among them, are there either way."
          allOf:
            - $ref: "#/components/schemas/Lead"
        to_number_e164: { type: string, example: "+972501234567", description: "Number snapshotted at enrollment. This is what gets dialed." }
        status:
          type: string
          enum: [pending, scheduled, dialing, awaiting_disposition, completed_success,
                 completed_failed, exhausted, excluded, dnc]
          description: |
            `pending` — eligible, waiting for the pacer.
            `scheduled` — waiting for `next_attempt_at`.
            `dialing` — a call is live.
            `awaiting_disposition` — the call ended and classification hasn't arrived yet.
            Contacts are never redialed from this state.
            `completed_success` — retired on a stop disposition or a human connect.
            `completed_failed` — retired after a terminal failure.
            `exhausted` — `max_attempts` reached without a stop condition.
            `excluded` — removed by `DELETE /campaigns/{id}/leads/{lead_id}`, or retired when
            the campaign was stopped or archived. Terminal.
            `dnc` — the number is on the do-not-call list.
        stop_hit: { type: boolean, description: "True once a stop condition fired. A contact with `stop_hit` is never dialed again by this campaign." }
        stop_reason: { type: string, nullable: true, description: "Why the contact was retired (e.g. `manual`, `disposition`, `attempts_exhausted`; `campaign_stopped` / `campaign_archived` when the campaign was stopped or archived (in the dashboard or through the API) before the contact was reached; `in_another_campaign` when a launched draft found the number already held)." }
        stopped_by_disposition_id: { type: string, format: uuid, nullable: true, description: "Disposition that triggered the stop. Kept even if that disposition is later deleted." }
        attempt_count: { type: integer, description: "Dial attempts consumed against `max_attempts`." }
        infra_retries_used: { type: integer, description: "Platform-side retries consumed against `max_infra_retries`. These do not count as attempts." }
        next_attempt_at: { type: string, format: date-time, nullable: true }
        last_disposition_id: { type: string, format: uuid, nullable: true }
        last_disposition:
          nullable: true
          description: "Full Disposition object for `last_disposition_id`."
          allOf:
            - $ref: "#/components/schemas/Disposition"
        last_disconnect_reason: { type: string, nullable: true, description: "User-friendly reason the last call ended." }
        last_status_at: { type: string, format: date-time, nullable: true }
        completed_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, description: "When the contact was enrolled." }

    CampaignStats:
      type: object
      description: >
        Live progress for one campaign, plus the engine's own account of what it last
        did. When a `running` campaign appears to be doing nothing, `last_tick_result`
        and `last_error` are the fields that explain it.
      properties:
        campaign_id: { type: string, format: uuid }
        status: { type: string, description: "Same value as `Campaign.status`." }
        pause_reason: { type: string, nullable: true, description: "Same value as `Campaign.pause_reason`: why it is paused, or `null`." }
        leads_by_status:
          type: object
          additionalProperties: { type: integer }
          description: "Contact counts keyed by `CampaignContact.status`. Statuses with no contacts are omitted."
          example: { pending: 812, awaiting_disposition: 2, completed_success: 141, exhausted: 45 }
        leads_total: { type: integer }
        attempts_total: { type: integer, description: "Every dial attempt this campaign has made, including platform-side retries." }
        attempts_in_flight: { type: integer, description: "Attempts not yet settled — dialing, live, or awaiting classification." }
        calls_today: { type: integer, description: "Calls handed to the queue in the current day window." }
        max_calls_per_day: { type: integer }
        spent_cents: { type: integer }
        reserved_cents: { type: integer }
        estimate_cents: { type: integer, nullable: true }
        budget_cents: { type: integer, nullable: true }
        last_tick_at: { type: string, format: date-time, nullable: true }
        last_tick_result: { type: string, nullable: true, description: "Machine-readable reason the last evaluation admitted, or did not admit, a call. `blocked` means another operation held this campaign during that evaluation and it is retried on the next one." }
        last_error: { type: string, nullable: true }
        company_id: { type: string, format: uuid }

    EnrollmentReport:
      type: object
      description: |
        Result of `POST /campaigns/{id}/leads`. Enrollment is per-row and
        best-effort: a bad phone number or a number on the do-not-call list is
        reported here rather than failing the whole batch, and re-enrolling an
        existing contact is idempotent.

        Numbers are canonicalized to E.164 before anything is written, so the same
        person cannot be enrolled twice under two formats.
      properties:
        campaign_id: { type: string, format: uuid }
        enrolled: { type: integer, description: "Contacts newly enrolled by this request." }
        already_enrolled: { type: integer, description: "Contacts that were already enrolled — no-ops, not errors." }
        leads_created: { type: integer, description: "New leads created from `phone_numbers` entries with no existing match." }
        leads_matched: { type: integer, description: "`phone_numbers` entries matched to a lead you already had. A number an earlier entry of the same request carried is not counted here; see `duplicates_in_request`." }
        duplicates_in_request: { type: integer, description: "Entries whose number (or lead) an earlier entry of this same request already carried. Each is one contact with the first: reported in `results` as `already_enrolled` at its own `row`, and never counted as a lead you already had." }
        invalid_phone:
          type: array
          description: "Rows rejected before enrollment because nobody can dial the number (the `POST /leads` rule: letters, or an Israeli number of an impossible length or prefix such as `12345`), because the number is outside Israel (calls can only be placed to Israeli numbers, +972), or because the lead could not be created. No lead is created for these."
          items:
            type: object
            properties:
              row: { type: integer, description: "The entry's position in the `phone_numbers` or `lead_ids` array sent, from 1." }
              lead_id: { type: string, format: uuid, description: "Present when the row came from `lead_ids`." }
              phone: { type: string, description: "As sent." }
              name: { type: string, description: "Present when the `phone_numbers` entry carried one." }
              reason:
                type: string
                enum: [missing_phone, not_a_number, impossible_number, country_not_allowed, lead_not_created]
                description: >
                  Why: empty, letters or symbols (`054-71A-4034`), digits nobody can dial
                  (`05012`), a number outside Israel (`+14155550123`; calls can only be placed
                  to Israeli numbers), or the lead could not be created (see `error`).
              error: { type: string, description: "Present when lead creation itself failed, and for `country_not_allowed`, with the sentence that says why." }
        invalid_email:
          type: array
          description: "`phone_numbers` entries whose `email` is not an address (the `POST /leads` rule). The email is never stored; the contact is still enrolled without it (a new lead is created with no email, a matched lead is left as it was), so each entry here also appears in `results`."
          items:
            type: object
            properties:
              row: { type: integer, description: "The entry's position in the `phone_numbers` array sent, from 1." }
              phone: { type: string, description: "As sent." }
              name: { type: string, description: "Present when the entry carried one." }
              email: { type: string, description: "As sent, trimmed." }
              reason: { type: string, enum: [invalid_email] }
        on_do_not_call:
          type: array
          description: >
            Numbers excluded because they are on the workspace do-not-call list. A
            `phone_numbers` entry that matches no lead is screened before a lead is made
            for it, so a number reported here never becomes a new lead. A verbal
            opt-out on a call adds the number to that list automatically, workspace-wide, so
            previously-contacted people can appear here.
          items: { type: string, example: "+972501234567"  }
        not_found:
          type: array
          description: "IDs from `lead_ids` that are not leads in this workspace."
          items: { type: string, format: uuid }
        in_another_campaign:
          type: array
          description: >
            Numbers another live campaign is already calling, each with that campaign.
            Not enrolled here: a number is dialed by one campaign at a time. A `draft`
            holds no number, so a number parked on a draft never appears here.
          items:
            type: object
            properties:
              phone: { type: string, example: "+972501234567" }
              lead_id: { type: string, format: uuid }
              campaign_id: { type: string, format: uuid }
              campaign_name: { type: string, nullable: true }
        results:
          type: array
          description: >
            One entry per number that got past parsing and the do-not-call screen, in the
            order supplied (`lead_ids` first, then `phone_numbers`), each with its `row`:
            `enrolled`, `already_enrolled` (already on this campaign, or the same number
            twice in this request) or `in_another_campaign` (with `campaign_id` and
            `campaign_name`).
          items:
            type: object
            properties:
              row: { type: integer, description: "The entry's position in the `lead_ids` or `phone_numbers` array sent, from 1 — the same count `invalid_phone` and `invalid_email` use." }
              phone: { type: string, example: "+972501234567" }
              lead_id: { type: string, format: uuid }
              result: { type: string, enum: [enrolled, already_enrolled, in_another_campaign] }
              campaign_id: { type: string, format: uuid, description: "Only for `in_another_campaign`." }
              campaign_name: { type: string, nullable: true, description: "Only for `in_another_campaign`." }
        total_leads: { type: integer, description: "Total contacts enrolled in the campaign after this request. Present whenever a number reached the enrolment step — including when every one was already enrolled; omitted when every entry was skipped before it (an undiallable number, an unknown lead, the do-not-call list)." }
        company_id: { type: string, format: uuid }

    CampaignError:
      description: |
        Coded error envelope used by the campaign conflict and preflight responses. `code`
        carries the machine-readable code and `message` the human-readable explanation;
        `error` repeats the code rather than the prose, the one way it reads differently from
        other `Error` bodies, which it extends with `message`. Branch on `code`.

        - `ALREADY_IN_ACTIVE_CAMPAIGN` — no longer returned. Enrolment reports a number
          another campaign holds under `in_another_campaign` and enrolls the rest.
        - `CAMPAIGN_NOT_READY` (422) — launch preflight failed; `message` names the single
          thing to fix.
      allOf:
        - { $ref: "#/components/schemas/Error" }
        - type: object
          required: [error, code, message]
          properties:
            error:
              type: string
              enum: [ALREADY_IN_ACTIVE_CAMPAIGN, CAMPAIGN_NOT_READY]
            code:
              type: string
              enum: [ALREADY_IN_ACTIVE_CAMPAIGN, CAMPAIGN_NOT_READY]
            message: { type: string }
    AffiliateMonth:
      type: object
      description: |
        One calendar month of affiliate activity. Every `*_cents` field is an integer
        number of **US cents**.

        Any `*_cents` field here **can be negative**. A refund or chargeback is booked in
        the month it happens and reverses the commission at the rate that originally
        applied, so a month with more refunds than sales reads negative. That is correct,
        not a bug — the lifetime totals in `summary` already account for it.
      properties:
        month: { type: string, example: "2026-07", description: "Calendar month, `YYYY-MM`." }
        clients_invited: { type: integer, description: "Companies that signed up through your link in this month." }
        referred_revenue_cents: { type: integer, description: "Tier-1 billed revenue — what the customers you referred directly paid us. Negative if refunds outweighed sales." }
        commission_cents: { type: integer, description: "Total commission earned in this month, both tiers. Equals `direct_commission_cents + override_commission_cents`. May be negative." }
        direct_commission_cents: { type: integer, description: "Tier-1 share of `commission_cents`." }
        override_commission_cents: { type: integer, description: "Tier-2 share of `commission_cents`." }
        payable_commission_cents:
          type: integer
          description: >
            The part of `commission_cents` that has cleared the hold window (see `hold_days`)
            and is therefore payable. Recent months read lower than `commission_cents`; the
            gap closes on its own as the hold elapses.
        payout_sent_cents: { type: integer, description: "Payouts recorded against this month, in US cents regardless of the currency actually wired." }

    AffiliateStats:
      type: object
      description: |
        Affiliate commission summary for the API key's own workspace. All money is
        integer **US cents** — divide by 100 for dollars, never parse as a float.
      properties:
        ref_code: { type: string, example: "AB12CD34", description: "Your referral code. Your link is `https://app.goyappr.com/signup?ref=<ref_code>`." }
        commission_rate_pct:
          type: number
          example: 10
          description: >
            Your **direct** (tier-1) commission rate as a percentage, *as it stands today*.
            Every past commission was priced at the rate in force on the day that customer
            paid, so after a rate change `referred_revenue_cents * commission_rate_pct`
            will NOT reproduce `direct_earned_cents`. Use it to say what new revenue will
            earn — never to re-derive history.
        override_rate_pct:
          type: number
          example: 2.5
          description: >
            Your **override** (tier-2) rate, as it stands today. Apply it to the basis
            named by `override_basis`: customer revenue or your partner's earned commission.
            `0` when you have no tier-2 terms. Same caveat as
            `commission_rate_pct`: it does not re-derive `override_earned_cents`.
        override_basis:
          type: string
          enum: [revenue, affiliate_commission]
          description: >
            The tier-2 basis in force today. `revenue` applies your override to paid customer
            revenue. `affiliate_commission` applies it to your partner's earned direct commission,
            after that commission is rounded to cents; their full commission is unchanged and
            yours is paid on top. Historical terms are resolved at the original payment date.
            Partner monthly earnings are rounded before parent eligibility or rate slices;
            the parent share is rounded once per customer/month across its rate slices.
            Refunds reverse the original rounded share; partial refunds cumulatively
            apportion that share, so a full refund cancels it exactly.
            Gifts, promotional credits, unpaid rows and taxes do not earn commission; refunds
            reduce the base at the original rates. Most workspaces have no tier-2 terms.
        hold_days:
          type: integer
          example: 30
          description: >
            Days a commission must age before it becomes payable. Covers the card-dispute
            window. `0` means commission is payable as soon as it is earned.
        months_window_months: { type: integer, example: 12, description: "How many trailing months `months[]` covers — echoes the `months` query parameter." }
        summary:
          type: object
          description: "Lifetime totals. Unbounded — not limited to `months_window_months`."
          properties:
            clients_invited: { type: integer, description: "Companies that signed up through your link, including those that have never paid." }
            sub_affiliates: { type: integer, description: "Enrolled sub-affiliates you earn an override through. `0` for most workspaces." }
            referred_revenue_cents: { type: integer, description: "Lifetime tier-1 billed revenue." }
            override_revenue_cents: { type: integer, description: "Lifetime tier-2 billed revenue." }
            earned_cents: { type: integer, description: "Lifetime commission earned across both tiers. Equals `direct_earned_cents + override_earned_cents`." }
            direct_earned_cents: { type: integer }
            override_earned_cents: { type: integer }
            payable_cents:
              type: integer
              description: >
                The part of `earned_cents` past the hold window. **This is the number payouts
                are drawn from** — `earned_cents` is what you have accrued, `payable_cents` is
                what is currently claimable.
            paid_cents: { type: integer, description: "Lifetime payouts, converted to US cents at the rate recorded on each payout. Voided payouts are excluded." }
            outstanding_cents:
              type: integer
              description: >
                `payable_cents - paid_cents`. **Can be negative** — that means you have been
                paid ahead of the hold window, and the balance works itself off as more
                commission becomes payable. It is not an error and it is not clamped to zero.
            earned_before_window_cents:
              type: integer
              description: >
                Commission earned before the first month in `months[]`. Added to the sum of
                `months[].commission_cents` it reconciles exactly to `earned_cents`.
        months:
          type: array
          description: "Newest month first, `months_window_months` entries, zero-filled for months with no activity."
          items: { $ref: "#/components/schemas/AffiliateMonth" }

    AffiliateDownlineRow:
      type: object
      description: |
        One enrolled sub-affiliate. Only partners deliberately enrolled by Yappr appear
        here — an ordinary customer who happens to share their own referral link does not.
        A freshly enrolled partner is a row of zeros, not an absent row.
      properties:
        company_id: { type: string, format: uuid }
        name: { type: string, description: "The sub-affiliate's company name." }
        ref_code: { type: string, description: "The sub-affiliate's own referral code." }
        customers: { type: integer, description: "Paying customers they have referred that generate an override for you." }
        downline_revenue_cents: { type: integer, description: "Paid revenue those customers generated, in US cents, excluding gifts and taxes. This remains customer revenue when override_basis is affiliate_commission; it is then not the commission base." }
        my_override_cents: { type: integer, description: "Your tier-2 commission earned through this partner." }
        my_override_payable_cents: { type: integer, description: "The part of `my_override_cents` past the hold window." }
        my_direct_cents: { type: integer, description: "Your tier-1 commission on this partner's *own* spend with Yappr — they are also your direct referral." }

paths:
  /mcp:
    servers:
      - url: https://mcp.goyappr.com
        description: Remote MCP server, separate from the REST API
    x-yappr-plane: mcp
    post:
      operationId: mcpRequest
      x-mcp-transport: true
      summary: Use the Yappr MCP connector
      description: >-
        Streamable HTTP endpoint for MCP initialization, tool discovery and individually described tool calls.
        Discover OAuth from the protected-resource metadata in the WWW-Authenticate challenge.
        Each tool enforces the workspace, scopes and optional agent limit approved by the person.
        Authorization codes are single-use and refresh tokens rotate. This transport is not a REST resource tool.
        See /api-reference/mcp/connect for the protocol and /connect-ai for account connection instructions.
      tags: [MCP]
      security:
        - mcpOAuth: [yappr.read]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [jsonrpc, method]
              properties:
                jsonrpc: { type: string, const: "2.0" }
                id: { type: [string, number, "null"] }
                method: { type: string, examples: [initialize, tools/list, tools/call] }
                params: { type: object, additionalProperties: true }
      responses:
        "200":
          description: MCP JSON-RPC result or error; tool failures use isError in the tool result.
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
            text/event-stream:
              schema: { type: string }
        "202":
          description: MCP notification accepted.
        "401":
          description: OAuth authorization required, token expired, or connection revoked.
          headers:
            WWW-Authenticate:
              description: Bearer challenge containing the protected-resource metadata URL.
              schema: { type: string }
        "403":
          description: Origin, workspace or connection is not permitted.
        "429":
          description: Rate limit reached. Retry after the indicated interval.
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
        "503":
          description: The connector is temporarily unavailable.
  /agents/{id}/workflow:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
    get:
      summary: Read canonical workflow draft
      operationId: getWorkflow
      tags: [Workflows]
      description: Requires agents:read. Returns the current saved draft and published pointer. Merely disabled agents remain editable; archived agents are hidden. No provider execution or publication occurs.
      responses:
        '200': { description: Canonical authoring state., content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowState' } } } }
        "400":
          description: "WORKFLOW_REQUEST_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404': { description: 'Agent missing, archived or outside the current company.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Authoring storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
    put:
      summary: Save canonical workflow draft
      operationId: saveWorkflow
      tags: [Workflows]
      description: Requires agents:update. Replaces the complete draft under expected_version compare-and-swap. Document id/name are server-owned for workflow agents - send them back as read, and a save that changes either is refused (422 WORKFLOW_DOCUMENT_INVALID, server_owned at /id or /name); rename the agent with PATCH /agents/{id}. A save refuses the document's shape - a step kind the schema does not have (node_type_unknown at /conversation/nodes/<n>/type), a step without a member its kind requires (field_required, for example /after/0/steps/0/label) - every problem by path in one answer. An action step's hold_line that is not text of 1-28 characters (or null) is refused the same way (field_invalid at /conversation/nodes/<n>/hold_line, the step in node_id), and nothing is written. Saves do not publish; invalid executable graphs (a step nothing reaches, a binding reading a parameter the agent does not collect) can remain drafts, and Check names them. The total UTF-8 JSON request body is limited to600000 bytes; stored PostgreSQL document representation is limited to512KiB. Preserve arbitrary JSON numeric tokens with a lossless client. Never retry a conflict by overwriting the new version automatically; a refused save writes nothing, and re-sending the identical save after a lost answer is answered 200 instead of 409. An after-call input may also be read from the finished call by description - {"kind":"extract","instruction":"the time slot the caller agreed to"} with an optional type (text, number, yes_no, date or datetime; left out, it follows the tool input), on_missing ("skip", the default for a required input, or "fail") or a fallback {"value":…} (not both). The call's analysis answers it in the same single model call; a datetime is a day and a time in the workspace's time zone sent with that zone's offset. A value the call did not say is missing and is never guessed - the step is skipped (a skipped step is not a failure), or fails, or sends the fallback. A failed analysis blocks the step instead. Check refuses it anywhere but a follow-up step (extract_unavailable_phase). A sequence step may carry a when condition and on_succeeded/on_failed routes. A before-call step may route either outcome to "#decline", which refuses the call - an incoming call is refused at the carrier and never answered, and an outgoing one is never dialled and its call request ends failed with error_code before_declined. "#decline" is the only target a before-call step may name, and no other phase routes or carries a condition. An After trigger event may be any_end, which stands for call.ended, call.failed and call.no_answer, or request.failed, which is the request dying before anything was dialled; a <artifact>.ready trigger starts its follow-up only for a result that was actually produced. A document with before-call steps may also offer the web channel - a browser call is created, prepared and then started by the caller, the same way an outgoing call is. The preparation window is the platform's - 30s inbound, 5 minutes for an outgoing or browser call - with no field to set. global_instructions and a conversation step's instructions may quote a before-call result as {{before.step_id.field}} with an optional |fallback text. global_instructions, a conversation step's instructions and a tool binding's fixed input value may quote the call itself as {{call.field}} or {{call.field.subfield}} - {{call.caller_number}}, {{call.call_variables.first_name|there}} - naming a member of the CallPackage schema, or a relative time {{call.time.<when>.<zone>}} - now, start_of_today, end_of_today, start_of_tomorrow, end_of_tomorrow, in_hours.<1-8760> or in_days.<1-366>, then an IANA zone (UTC when left out) - worked out when it is substituted and sent as RFC 3339 with that zone's offset; any other spelling is a publish error (call_placeholder_time). In a fixed input the value is substituted into the request just before it is sent; in instructions it is substituted when the call starts. The field has to be one every phase that text runs in can know - a before-call step's input cannot read the call id, and neither an instruction nor anything that runs before the call ends can read the transcript. Those three places and a transfer tool's spoken line are the only places a call reference may be written; a step name, a route condition or a tool description is a publish error rather than braces the agent reads out. An after-call step reads what the agent extracted as an artifact source on the analysis artifact - kind artifact, artifact analysis, path /extracted_data/<parameter name>, or /extracted_data for the whole set - alongside /summary and /disposition_id on the same artifact. Every parameter the agent collects is a key on every call, and one the conversation never covered is stored as null there, so a fallback on that source never fires and an input reading a single field needs a type that accepts null. Saved context has no writer, so a stored source there is empty on every call. Saving checks none of this; validate and publish do. An action step may carry hold_line - one fixed sentence, said in the agent's voice while that step's tool runs, starting when the tool starts, with the agent's next words held until it has been heard (never more than four seconds past the tool's answer). It must finish inside that wait - about 2.5 seconds of speech, so up to 28 characters (a save refuses more, field_invalid), about 25 in Hebrew or Arabic, about 16 in Korean or Japanese kana, about 10 in Chinese characters, a digit counting as about three; Check refuses a line that takes longer to say (hold_line_too_long). It cannot carry a {{...}} reference or a random variation (hold_line_not_fixed), be blank (hold_line_blank), or sit on a transfer step (hold_line_on_transfer). A step with no hold_line of its own, and a tool a conversation step offers, still gets the call's default line - "One moment please." or the Hebrew "רגע אחד בבקשה." - as a slow tool starts (English and Hebrew calls only, tools that usually take about two seconds or longer, never for End call or a transfer); a hold_line on an action step replaces it, and there is no field to turn the default off.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WorkflowSave' }
      responses:
        '200': { description: 'Saved draft with its new version. Re-sending the identical save after a lost answer returns this same 200 rather than a conflict: the draft already is the document that was asked for.', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowState' } } } }
        '400': { description: 'WORKFLOW_REQUEST_INVALID - a query parameter was sent (the save reads none), the body is not JSON, expected_version is missing or not a positive whole number (or null for a first draft), or a field other than expected_version and document was sent. issues[] names each one by path (/expected_version, /<field>).', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404': { description: 'Agent missing, archived or outside the current company.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'WORKFLOW_CONFLICT; the saved version changed and nothing was written. A refused save never persists, so the draft is exactly what it was before the request. The answer names the draft''s version as current_version, beside issues[0].path /expected_version; when it equals the version sent, something the draft pins changed instead.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '413': { description: WORKFLOW_TOO_LARGE; request or stored document exceeds its technical byte budget., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'RESERVED_BINDING_ID - a binding id of the reserved shapes t_<hex> or o_<letters and digits> that no tool for every step and no step''s own settings owns (issues[].path /bindings/<n>/id): those ids are kept for Tools & integrations, rename it. WORKFLOW_DOCUMENT_INVALID - document is missing or not an object (issues[].path /document), breaks a storage rule (/schema_version, /bindings), has a step kind the schema does not have (node_type_unknown) or a step without a member its kind requires (field_required), changes the server-owned id or name (server_owned, /id or /name), or fixes a calendar on an agent-wide action whose managed tool was set up before it could take one (config_input_needs_update at /bindings/<n>/inputs/<field>: POST /tool-connections/{id}/actions/prepare that action, or set it with PATCH /agents/{id}/integrations/{integration_id}); a reference problem on a binding (reference_is_tool_id, reference_unavailable, reference_invalid, tool_archived, connection_unavailable at /bindings/<n>/tool_revision_id) is named in the same answer. WORKFLOW_REFERENCE_INVALID - a binding names a tool revision this workspace cannot use; issues[] has one entry per binding it could pin, path /bindings/<n>/tool_revision_id, and says when the value is a tool id sent where its revision belongs (reference_is_tool_id, naming the revision to send), when the tool is archived (tool_archived) or when an app tool''s account is no longer connected (connection_unavailable); those two carry node_id, label and tool_name, and say to restore the tool (or reconnect the account) or remove the step. Anything it cannot pin is one issue at /bindings.', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '503': { description: Authoring storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/workflow/rebind:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid } }
    post:
      summary: Point bindings at other tools
      operationId: rebindWorkflowTools
      tags: [Workflows]
      description: >
        Requires agents:update. Moves one or more of the draft's bindings onto another saved tool's current
        revision, under the same expected_version compare-and-swap a save uses, without resending the document.
        Binding inputs, steps and everything else are left exactly as they are, and a binding that already uses
        that tool is not touched - if none of them moved, the draft version does not change. Revisions stay
        immutable: this moves the pointer, it does not edit a revision. Changing the endpoint every agent calls
        is PATCH /tools/{id} instead, because a binding follows its tool unless tool_revision_policy is pinned;
        pinning an older revision stays a whole-document save. Rebinding edits the draft only - publish to serve it.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [expected_version, bindings]
              properties:
                expected_version:
                  type: integer
                  minimum: 1
                  description: The exact draft version from GET /agents/{id}/workflow. Null is not accepted; a rebind always has a draft.
                bindings:
                  type: object
                  minProperties: 1
                  maxProperties: 64
                  additionalProperties: { type: string, format: uuid }
                  description: Each key is a bindings[].id already in the draft; each value is the id of the tool that binding should use.
                  example: { notify: 33333333-3333-4333-8333-333333333333 }
      responses:
        '200': { description: 'The authoring state, as a save returns it.', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowState' } } } }
        '400': { description: 'WORKFLOW_REQUEST_INVALID; a query parameter (the route reads none), expected_version is not a positive whole number, or bindings is empty, over 64 entries, or holds something that is not a tool id.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'AGENT_NOT_FOUND - the agent is not in this workspace. WORKFLOW_NOT_FOUND - a tool named in bindings is not; the message names it, and issues[] has one entry per binding that pointed at it, with code tool_not_found and path /bindings/<binding id>.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'WORKFLOW_CONFLICT (the draft moved on; nothing was written) or WORKFLOW_TOOL_NOT_READY (that tool has no current revision yet - poll GET /tools/{id}).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'WORKFLOW_BINDING_NOT_FOUND (the draft has no binding with that id, and the message names it) or WORKFLOW_DOCUMENT_INVALID (this agent has no workflow draft yet - save one first).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Authoring storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/workflow/validate:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
    post:
      summary: Check a saved workflow
      operationId: validateWorkflow
      tags: [Workflows]
      description: Requires agents:update. Runs the canonical compiler against exactly expected_version and current authorized tool/account/settings inputs. Read-only validation; does not save or publish. Warnings are stable safe codes, never private compiled prompts or connected-app service configuration. Unknown compiler advisories project to workflow_warning. Two codes come from the binding contracts rather than the compiler, and both carry the pointer to the binding and the tool's name. binding_channel_unsupported is an advisory on the 200; binding_phase_unsupported is a refusal, answered 422 WORKFLOW_VALIDATION_FAILED like any other. Every warning carries its message. Two further advisories come from the document itself and point at one input - stored_context_has_no_writer, a stored source, which nothing in the product ever populates, and input_constant_placeholder, a required input frozen to a stand-in such as n/a. An analysis source reading /extracted_data/<name> is read against the agent's extraction parameters and refused the same way, pointing at the input - extracted_field_unknown when the agent collects nothing by that name, extracted_field_type_mismatch when the input's declared type cannot take the parameter's kind.
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowExpectedVersion' } } }
      responses:
        '200': { description: Valid saved draft and safe advisories., content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowValidation' } } } }
        '400': { description: 'WORKFLOW_REQUEST_INVALID - expected_version is missing or not a positive whole number, or another field was sent, or a query parameter (the route reads none). issues[] names each one by path (/expected_version, /<field>).', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404': { description: 'Agent/draft missing, archived or outside this company.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'WORKFLOW_CONFLICT; saved draft changed. The answer names the draft''s version as current_version, beside issues[0].path /expected_version; when it equals the version sent, something the draft pins changed instead.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '413': { description: WORKFLOW_TOO_LARGE or WORKFLOW_SETTINGS_TOO_LARGE. Save smaller settings separately; previous saved data is retained., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422':
          description: |
            WORKFLOW_VALIDATION_FAILED or unavailable references.
            A binding wired onto a channel its tool cannot run on is not refused: it is an
            advisory on the 200, `binding_channel_unsupported`. A binding wired into a phase
            its tool cannot run in is refused here (`binding_phase_unsupported`), and so is an
            input bound to what the agent collected, below; both used to come back as
            `valid: false` on a 200. Every issue arrives in the one answer, the conversation
            graph's all together.
            An input bound to what the agent collected raises, each with the pointer of the input:
            `extracted_field_unknown` — /extracted_data/<name> names nothing the agent collects.
            `extracted_field_type_mismatch` — the input's declared type cannot take the parameter's kind.
            An input read from the call by description (`{"kind":"extract","instruction":…}`, follow-up steps only) raises, each with the pointer of the input:
            `extract_unavailable_phase` — the step is not a follow-up step. `extract_type_unsupported` — the input is a list, an object, declares no type, or cannot take the `type` written. `extract_missing_policy` — both `fallback` and `on_missing` were written. `extract_instruction_empty` — the `instruction` is blank. `extract_too_many` — more than 64 different descriptions. `extract_unavailable` — the workspace's voice engine does not read it yet; nothing was published.
            `stored_context_has_no_writer` — a required input's only source is saved context (kind stored, no fallback), which nothing writes; the save keeps the draft. On an optional input, or one with a fallback, it stays an advisory on the 200.
            `missing_request_field` — a required input reads a call-request field (kind request, no fallback) that request_schema does not declare, so it would arrive empty; the save keeps the draft. Declare the field under request_schema.properties, or give the source a fallback. On an optional input it stays an advisory on the 200, naming the path, the field and the tool.
            `tool_archived` / `connection_unavailable` — see WORKFLOW_REFERENCE_INVALID: a binding's tool is archived, or its app account is no longer connected; restore the tool (or reconnect), or remove the step.
            Every 422 carries `warnings[]` - strict_off_guidance and the binding and input advisories; the compiler's own graph advisories arrive once the document compiles.
            Sequence branching raises these `issues[]` codes, each with the JSON pointer of the step or condition part to change:
            `sequence_route_target` — a route names something that is not a step of this sequence.
            `entry_step_routed` — a route points back at the sequence's first step.
            `sequence_cycle` — declared dependencies and routes together form a loop.
            `failure_route_conflict` — on_failed is declared while on_failure is stop.
            `condition_depth` — the condition nests more than four levels.
            `condition_size` — the condition declares more than 32 parts.
            `condition_value_required` / `condition_value_unexpected` — this operator does, or does not, compare against a value.
            `condition_value_type` — in and not_in need a list on the value side.
            `condition_type_mismatch` — the declared types disagree, or the operator does not apply to the declared type.
            `branch_dependent_source` — a value produced on a branch is read with no declared fallback.
            `transfer_in_sequence` — a branching sequence cannot contain a transfer step.
            `input_dependency` — a step reads an output it is neither a declared dependant nor a route successor of.
            The Before and After phases raise these `issues[]` codes:
            `before_budget_exceeded` — the chain of before-call steps cannot finish inside the preparation window of either direction.
            `guard_phase` — a before-call or follow-up step carries a when condition.
            `route_phase` — a follow-up step declares an outcome route.
            `before_route_target` — a before-call step routes to another step instead of to "#decline".
            `decline_phase` — "#decline" is used inside a sequence, where the call is already connected.
            A follow-up's "Only if" (`when` on an After trigger) raises these `issues[]` codes, at path `/after/<trigger id>/when/...`:
            `trigger_filter_unavailable` — the condition reads a call fact the trigger's event cannot guarantee (naming the field, the event and where to move it).
            `trigger_filter_type` — the fact and the operator or value do not fit.
            `trigger_filter_value` — a fixed value the fact can never have.
            `trigger_filter_source` — not a call fact compared with a fixed value.
            `trigger_filter_reader_unavailable` — the workspace's voice engine does not read an "Only if" yet.
            `call_source_placement` — a call fact read from a sequence condition.
            A result route's condition (`when` on a `result` edge, which raises the document to compiler level 1.10.0) raises these `issues[]` codes:
            `result_guard_outcome` — a condition on a `failed` route; only a `succeeded` route can have one.
            `result_guard_needs_strict` — Strict routing is off.
            `result_guard_needs_otherwise` — a step with conditions on its `succeeded` routes has no `succeeded` route without one.
            `result_guard_source` — the condition reads something other than fixed values and that step's own answer.
            `result_guard_reader_unavailable` — the workspace's voice engine does not read a route condition yet; nothing was published.
            `ambiguous_result_edge` — two `succeeded` routes without a condition, or two `failed` routes, leave the same step.
            A before-call reference written into instructions raises these `issues[]` codes:
            `placeholder_syntax`, `placeholder_unknown_step`, `placeholder_phase`, `placeholder_unknown_path`,
            `placeholder_unsupported_field`, `placeholder_reserved_variable`, `placeholder_limit`, `placeholder_too_long`.
            The same codes at path `/settings/greeting_message` are about the agent's opening line (a workflow
            agent's `greeting_message` may read a Before-call step's result): the step it names is not one of
            this document's Before steps, or the field is not one its tool returns. Fix the line on
            PATCH /agents/{id}, or the step, and check again.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }
        '503': { description: WORKFLOW_COMPILER_UNAVAILABLE; no publication occurred., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/workflow/publish:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
    post:
      summary: Publish a saved workflow
      operationId: publishWorkflow
      tags: [Workflows]
      description: Requires agents:update. Compiles and atomically rechecks the exact draft, references, connection epochs and effective settings before publishing. Nothing is published if checks fail. Already accepted runs retain frozen artifacts; changing Strict affects future accepted calls only after publication. Publishing an inactive unarchived agent does not reactivate it or start any call.
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowExpectedVersion' } } }
      responses:
        '201':
          description: Immutable published version, or its matching existing publication.
          content:
            application/json:
              schema:
                type: object
                required: [revision, execution_version]
                properties:
                  revision: { $ref: '#/components/schemas/WorkflowRevisionSummary' }
                  execution_version: { const: workflow_v1, readOnly: true }
                  settings_updated_at:
                    type: string
                    format: date-time
                    readOnly: true
                    description: >
                      The agent settings token as of this publication. Publishing records which
                      version the agent runs, which writes the agent row, so an updated_at read
                      before publishing is stale afterwards and PATCH /agents/{id} would answer
                      409 WORKFLOW_SETTINGS_CONFLICT. Replaying an identical publish changes
                      nothing and returns the same value. Send this value as expected_updated_at on
                      the next settings save. Absent only when the timestamp could not be read;
                      the publication itself is unaffected, so re-read GET /agents/{id}/settings.
        '400': { description: 'WORKFLOW_REQUEST_INVALID - expected_version is missing or not a positive whole number, or another field was sent, or a query parameter (the route reads none). issues[] names each one by path (/expected_version, /<field>).', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404': { description: 'Agent/draft missing, archived or outside this company.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'WORKFLOW_CONFLICT; draft or an effective dependency changed. The answer names the draft''s version as current_version, beside issues[0].path /expected_version; when it equals the version sent, something the draft pins changed instead.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '413': { description: WORKFLOW_TOO_LARGE or WORKFLOW_SETTINGS_TOO_LARGE; retained saved state requires a smaller technical snapshot., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422':
          description: |
            Invalid graph/schema or unavailable account/tool. Nothing is published while an issue stands.
            A required input whose only source is saved context (kind stored, no fallback) is refused with
            `stored_context_has_no_writer`, and a required input reading a call-request field request_schema
            does not declare (kind request, no fallback) with `missing_request_field`. A binding to an archived
            tool is WORKFLOW_REFERENCE_INVALID `tool_archived` at /bindings/<n>/tool_revision_id, naming the
            step and the tool. Every WORKFLOW_VALIDATION_FAILED carries `warnings[]` beside `issues[]`.
            Sequence branching raises these `issues[]` codes, each with the JSON pointer of the step or condition part to change:
            `sequence_route_target` — a route names something that is not a step of this sequence.
            `entry_step_routed` — a route points back at the sequence's first step.
            `sequence_cycle` — declared dependencies and routes together form a loop.
            `failure_route_conflict` — on_failed is declared while on_failure is stop.
            `condition_depth` — the condition nests more than four levels.
            `condition_size` — the condition declares more than 32 parts.
            `condition_value_required` / `condition_value_unexpected` — this operator does, or does not, compare against a value.
            `condition_value_type` — in and not_in need a list on the value side.
            `condition_type_mismatch` — the declared types disagree, or the operator does not apply to the declared type.
            `branch_dependent_source` — a value produced on a branch is read with no declared fallback.
            `transfer_in_sequence` — a branching sequence cannot contain a transfer step.
            `input_dependency` — a step reads an output it is neither a declared dependant nor a route successor of.
            The Before and After phases raise these `issues[]` codes:
            `before_budget_exceeded` — the chain of before-call steps cannot finish inside the preparation window of either direction.
            `guard_phase` — a before-call or follow-up step carries a when condition.
            `route_phase` — a follow-up step declares an outcome route.
            `before_route_target` — a before-call step routes to another step instead of to "#decline".
            `decline_phase` — "#decline" is used inside a sequence, where the call is already connected.
            A follow-up's "Only if" (`when` on an After trigger) raises these `issues[]` codes, at path `/after/<trigger id>/when/...`:
            `trigger_filter_unavailable` — the condition reads a call fact the trigger's event cannot guarantee (naming the field, the event and where to move it).
            `trigger_filter_type` — the fact and the operator or value do not fit.
            `trigger_filter_value` — a fixed value the fact can never have.
            `trigger_filter_source` — not a call fact compared with a fixed value.
            `trigger_filter_reader_unavailable` — the workspace's voice engine does not read an "Only if" yet.
            `call_source_placement` — a call fact read from a sequence condition.
            A result route's condition (`when` on a `result` edge, which raises the document to compiler level 1.10.0) raises these `issues[]` codes:
            `result_guard_outcome` — a condition on a `failed` route; only a `succeeded` route can have one.
            `result_guard_needs_strict` — Strict routing is off.
            `result_guard_needs_otherwise` — a step with conditions on its `succeeded` routes has no `succeeded` route without one.
            `result_guard_source` — the condition reads something other than fixed values and that step's own answer.
            `result_guard_reader_unavailable` — the workspace's voice engine does not read a route condition yet; nothing was published.
            `ambiguous_result_edge` — two `succeeded` routes without a condition, or two `failed` routes, leave the same step.
            A before-call reference written into instructions raises these `issues[]` codes:
            `placeholder_syntax`, `placeholder_unknown_step`, `placeholder_phase`, `placeholder_unknown_path`,
            `placeholder_unsupported_field`, `placeholder_reserved_variable`, `placeholder_limit`, `placeholder_too_long`.
            The same codes at path `/settings/greeting_message` are about the agent's opening line (a workflow
            agent's `greeting_message` may read a Before-call step's result): the step it names is not one of
            this document's Before steps, or the field is not one its tool returns. Fix the line on
            PATCH /agents/{id}, or the step, and check again.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }
        '503': { description: Compiler/storage unavailable; no new publication acknowledged., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/tools-and-integrations:
    get:
      operationId: listAgentToolsAndIntegrations
      summary: List everything an agent can use on calls
      description: >
        Requires agents:read. The agent's Tools & integrations in one list, grouped by integration, in
        the order the dashboard shows them: what the agent has for every step first (connected apps and
        webhooks or call transfers given to the whole agent, in the order they were added), then what it
        uses only on some steps (each with the steps in used_in, in the order a call reaches them), then
        End call, which every agent has. An app is one entry per connected account, titled
        "<App> · <account>", with its enabled actions; each action carries where each of its inputs comes
        from, as in a workflow binding - literal (fixed), request or stored (from the call), model (filled
        by the agent from the conversation; with options, chosen from that list) - and, under overrides,
        the conversation steps that set their own. A webhook or call transfer is one entry per tool, with
        one action per binding. Reads the saved draft; status says whether the published version has it.
        An agent on the previous engine answers engine legacy with the tools attached to it (a flow
        agent: the tools its steps use), read-only. Ids shaped i_<hex>, i_<hex>_<action>, tg_<hex> and
        t_<hex> belong to the agent's integrations; do not use them for bindings of your own. Takes no
        query parameters.
      tags: [Agents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The agent's tools & integrations.
          content:
            application/json:
              schema:
                type: object
                required: [engine, data]
                properties:
                  engine: { type: string, enum: [workflow_v1, legacy] }
                  draft_version: { type: [integer, 'null'], description: The saved draft version this was read from (send it as expected_version on a write). Null for an agent on the previous engine or without a draft. }
                  live_version: { type: [integer, 'null'], description: "The published version, or null." }
                  draft_has_changes: { type: boolean, description: The draft holds changes the published version does not. }
                  channels: { type: array, items: { type: string, enum: [phone, web] }, description: 'How calls reach the agent (its workflow''s channels). phone covers incoming calls and the calls the agent places; web covers browser calls and needs no number. A call on a channel the published version leaves out fails at preparation (artifact_unavailable). A call transfer needs phone.' }
                  data:
                    type: array
                    items:
                      type: object
                      required: [id, kind, title, scope, status, actions, used_in]
                      properties:
                        id: { type: string, description: 'The integration id (i_... for an app, tg_... for a webhook or transfer on every step), a binding id for an entry used on some steps only, or end_call.' }
                        kind: { type: string, enum: [app, webhook, transfer, end_call] }
                        title: { type: string, description: 'One line: "<App> · <account>" for an app, "Webhook · <name>", "Call transfer · <name>", or "End call".', example: Google Calendar · Simons Calendar }
                        scope: { type: string, enum: [agent, steps], description: agent = every step; steps = only the steps listed in used_in. }
                        status: { type: string, enum: [live, not_live, building, reconnect_required, always_on], description: 'live: the published version has it; not_live: saved, publish the agent to use it; building: an action''s tool is being made again; reconnect_required: the account must be reconnected; always_on: End call.' }
                        app: { type: string, example: googlecalendar }
                        app_name: { type: string, example: Google Calendar }
                        connection_id: { type: string, format: uuid }
                        account_label: { type: string, example: Simons Calendar }
                        tool_id: { type: string, format: uuid }
                        actions:
                          type: array
                          items:
                            type: object
                            required: [name, binding_id, inputs, overrides]
                            properties:
                              action: { type: [string, 'null'], description: The app action slug; null for a webhook or a call transfer. }
                              name: { type: string, example: Find free time }
                              name_he: { type: [string, 'null'] }
                              binding_id: { type: string }
                              tool_id: { type: string, format: uuid, description: The tool this binding runs (its current revision). }
                              bindable: { type: boolean, description: 'Apps only: whether the action''s tool can take a fixed configuration input (which calendar) per agent yet. False on a tool made before that existed: a write that sets one updates it first.' }
                              inputs: { type: object, additionalProperties: { type: object, description: 'One source, as in a workflow binding: {kind: literal, value} (fixed), {kind: request|stored, path} (from the call), {kind: model, path} (the agent fills it), or {kind: model, path, options: [{value, label}]} (the agent picks one of the options).' }, description: "Each input's source by input name, as in a workflow binding." }
                              overrides:
                                type: array
                                description: Conversation steps that set their own sources for this action (binding_overrides).
                                items:
                                  type: object
                                  properties:
                                    node_id: { type: string }
                                    binding_id: { type: string }
                                    inputs: { type: object, additionalProperties: { type: object }, description: The step's own sources; inputs it does not name come from the agent's. }
                        used_in:
                          type: array
                          description: 'For scope steps: where it is used, in the order a call reaches it. node_id is the conversation step''s id, before:<step> for a before-call step, after:<trigger>/<step> for an after-call step.'
                          items:
                            type: object
                            properties:
                              phase: { type: string, enum: [before, during, after] }
                              node_id: { type: string }
                              label: { type: string }
              example:
                engine: workflow_v1
                draft_version: 12
                live_version: 3
                draft_has_changes: false
                channels: [phone, web]
                data:
                  - id: i_d3d44b7a
                    kind: app
                    app: googlecalendar
                    app_name: Google Calendar
                    connection_id: d3d44b7a-a820-4012-9a57-5e793b3719e2
                    account_label: Simons Calendar
                    title: Google Calendar · Simons Calendar
                    scope: agent
                    status: live
                    used_in: []
                    actions:
                      - action: GOOGLECALENDAR_FIND_FREE_SLOTS
                        name: Find free time
                        binding_id: i_d3d44b7a_find_free_slots
                        bindable: true
                        inputs:
                          items: { kind: literal, value: [primary] }
                          time_min: { kind: model, path: /time_min }
                          time_max: { kind: model, path: /time_max }
                        overrides: []
                  - id: tg_5c1e9a20
                    kind: webhook
                    tool_id: 5c1e9a20-0000-4000-8000-000000000001
                    title: Webhook · Send lead to CRM
                    scope: agent
                    status: live
                    used_in: []
                    actions: [{ action: null, name: Send lead to CRM, binding_id: t_5c1e9a20, inputs: {}, overrides: [] }]
                  - id: handoff_tool
                    kind: transfer
                    tool_id: 7f000000-0000-4000-8000-000000000002
                    title: Call transfer · Front desk
                    scope: steps
                    status: live
                    used_in: [{ phase: during, node_id: handoff, label: Hand off }]
                    actions: [{ action: null, name: Front desk, binding_id: handoff_tool, inputs: {}, overrides: [] }]
                  - { id: end_call, kind: end_call, title: End call, scope: agent, status: always_on, actions: [], used_in: [] }
        '400': { description: 'AGENTS_QUERY_INVALID: a query parameter was sent; this read takes none, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE: agents:read is required.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'AGENT_NOT_FOUND: no agent with this id in this workspace.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: 'WORKFLOW_STORAGE_UNAVAILABLE: storage could not be read; try again.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/integrations:
    get:
      operationId: listAgentIntegrations
      summary: List the apps an agent uses on calls
      description: >
        Requires agents:read. Each integration is one connected account given to the whole agent: the
        agent can use the listed actions of that account on every step of its calls. status is live
        (the published version has exactly these actions), not_live (saved in the draft, publish the
        agent to use them on calls), building (an action's tool is being rebuilt, for example after a
        reconnect) or reconnect_required (the account needs to be reconnected). separate_action_tools
        names accounts the agent uses through tools of their own, one per action, and whether they can
        be replaced by the whole integration (POST with replace_action_tools). Each action carries the
        agent's source for each of its inputs (inputs), how the catalogue says each input is set
        (input_specs) and the steps that have their own settings for it (overrides). tool_grants lists the
        saved webhooks and call transfers given to every step. An agent on the previous engine answers 422
        AGENT_ENGINE_UNSUPPORTED. Takes no query parameters.
      tags: [Agents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The agent's integrations.
          content:
            application/json:
              schema:
                type: object
                required: [data, draft_version, draft_has_changes, separate_action_tools]
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Integration' } }
                  tool_grants: { type: array, items: { $ref: '#/components/schemas/ToolGrant' }, description: 'Saved webhooks and call transfers on every step.' }
                  draft_version: { type: integer, minimum: 1, description: The draft version to send as expected_version. }
                  draft_has_changes: { type: boolean, description: The draft holds changes the published version does not. }
                  separate_action_tools:
                    type: array
                    items:
                      type: object
                      properties:
                        connection_id: { type: string, format: uuid }
                        app: { type: string, example: googlecalendar }
                        count: { type: integer, minimum: 1 }
                        switchable: { type: boolean, description: 'Every one of these tools is only offered on steps, with no inputs filled in, so POST with replace_action_tools can swap them for the whole integration.' }
        '401': { description: 'Missing, unknown or expired API key.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE: agents:read is required.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'AGENT_NOT_FOUND: no agent with this id in this workspace.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'AGENT_ENGINE_UNSUPPORTED: the agent runs on the previous engine and cannot use integrations until it moves.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Storage or the action service is unavailable. Nothing was changed., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
    post:
      operationId: addAgentIntegration
      summary: Give an agent a connected app
      description: >
        Requires agents:update. Gives the agent a connected account: its default actions (or the ones
        named in actions) are made ready, bound once each and offered on every conversation step. The
        draft is saved, and published in the same request when the draft had no other unpublished
        change and publish is not false; otherwise live is false and not_live_reason says why
        (draft_has_other_changes, agent_not_published, publish_not_requested, publish_refused with the
        compiler's issues, publish_unavailable, or inputs_missing - a required configuration ID with no
        default, such as a spreadsheet, is never guessed: the action names it in missing_inputs and the
        write is not published until you set it) and the draft keeps the change - publish with
        POST /agents/{id}/workflow/publish; when live is true the answer carries settings_updated_at, the
        agent's new settings token. A default action the app cannot offer to a voice agent is left
        out and named in skipped_actions with why; one named in actions is refused. When the actions are still being prepared after about
        twelve seconds, or the app's default actions are not chosen yet because its action list is
        still being read (an app outside the curated list, the first time), the answer is 503
        WORKFLOW_TOOL_CONTROL_UNAVAILABLE with Retry-After and nothing is saved: send the same request
        again. An API key that makes an app's actions ready for the
        first time also needs tools:create (tools:update to rebuild them).

        Action inputs: an item of actions may be {"action": slug, "inputs": {"<input>": source}} to set
        how some of its inputs are filled - Fixed (literal), AI (model), Choose from a list (model with
        options) or from the call (request, stored, step); see ActionInputSource. Inputs you leave out
        take the catalogue's default (GET /tool-connections/{id}/actions, inputs[].default_source): a
        calendar is Fixed to the main one, everything the conversation fills is AI. A Fixed or from-the-call
        input is never asked of the agent.

        A saved webhook or call transfer is given to every step with {"tool_id": ..., "inputs": {...}}
        instead of connection_id (entry id tg_..., its binding t_...); a call transfer needs the phone
        channel. This is the default place for a call transfer, as it is in the dashboard (Tools &
        integrations, and the canvas section "Available to every conversation step"); bind one to chosen
        steps in the workflow only when those steps need it alone, such as a different destination on
        each. A transfer runs on phone calls only: on a browser call the agent's call to it is refused
        with error_code unsupported_transfer_channel, and the agent is told to say that transfers work on
        phone calls. Ids of the shapes i_..., tg_... and t_... (and o_... for a step's own settings) are kept
        for these entries: do not use them for bindings of your own.
      tags: [Agents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                connection_id: { type: string, format: uuid, description: 'The connected account, as GET /tool-connections lists it. It must be ready. Send this or tool_id.' }
                tool_id: { type: string, format: uuid, description: 'A saved webhook or call transfer (GET /tools) to give every step. Send this or connection_id; with it, only inputs, publish and expected_version are read.' }
                inputs:
                  type: object
                  description: 'With tool_id only: the tool''s inputs, by name. Inputs left out are filled by the agent (AI).'
                  additionalProperties: { $ref: '#/components/schemas/ActionInputSource' }
                actions:
                  description: '"default" (or left out) for the app''s default actions, or 1-24 distinct actions from GET /tool-connections/{id}/actions, each a slug or {"action": slug, "inputs": {"<input>": source or null}}.'
                  oneOf:
                    - { type: string, const: default }
                    - type: array
                      minItems: 1
                      maxItems: 24
                      items:
                        oneOf:
                          - { type: string, pattern: '^[A-Z0-9_]{1,200}$' }
                          - type: object
                            additionalProperties: false
                            required: [action]
                            properties:
                              action: { type: string, pattern: '^[A-Z0-9_]{1,200}$' }
                              inputs: { type: object, additionalProperties: { oneOf: [{ $ref: '#/components/schemas/ActionInputSource' }, { type: 'null' }] } }
                publish: { type: boolean, default: true, description: Publish the agent when its draft had no other unpublished change. }
                expected_version: { type: integer, minimum: 1, description: 'The draft version you read; a different one is 409 WORKFLOW_CONFLICT.' }
                replace_action_tools: { type: boolean, default: false, description: 'Replace the agent''s separate tools for this account (see separate_action_tools) with the whole integration. Their actions join the default set.' }
            examples:
              defaults: { value: { connection_id: 0b8f4c2e-5a1d-4e6b-9c3f-7d2a1e9b4c60 } }
              calendarFixed:
                summary: Find free time on one calendar; the agent fills the times
                value: { connection_id: 0b8f4c2e-5a1d-4e6b-9c3f-7d2a1e9b4c60, actions: [{ action: GOOGLECALENDAR_FIND_FREE_SLOTS, inputs: { items: { kind: literal, value: [c_1a2b3c@group.calendar.google.com] } } }] }
              webhook:
                summary: A saved webhook on every step
                value: { tool_id: 5c1e9a20-3b4d-4e5f-8a6b-7c8d9e0f1a2b, inputs: { phone: { kind: literal, value: '{{call.caller_number}}' } } }
              transfer:
                summary: A saved call transfer on every conversation step (the default place for one)
                value: { tool_id: 7d2a1e9b-4c60-4b8f-9c3f-0b8f4c2e5a1d }
      responses:
        '201':
          description: The integration (or the webhook or call transfer) was added to the draft, and live says whether it is on calls now.
          content:
            application/json:
              schema:
                oneOf:
                  - { $ref: '#/components/schemas/IntegrationWriteResult' }
                  - { $ref: '#/components/schemas/ToolGrantWriteResult' }
        '400': { description: 'AGENT_INTEGRATION_REQUEST_INVALID: the body is not JSON, holds a field this request does not read (inputs at the top level with connection_id, or connection_id, actions or replace_action_tools with tool_id), or publish, replace_action_tools or expected_version has the wrong type. Each field is named in issues.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE (agents:update), WORKFLOW_ACTOR_DENIED (the key may not build an app''s actions: add tools:create), or WORKFLOW_ENVIRONMENT_MISMATCH (the account is connected on another plane).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'AGENT_NOT_FOUND, TOOL_CONNECTION_NOT_FOUND or TOOL_NOT_FOUND (no saved tool with tool_id).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'INTEGRATION_ALREADY_ASSIGNED: the account (or the webhook or transfer) is already given to this agent; change it with PATCH. WORKFLOW_CONFLICT: expected_version is not the draft version (current_version names it).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'AGENT_ENGINE_UNSUPPORTED, TOOL_CONNECTION_NOT_READY (reconnect the account), INTEGRATION_ACTION_UNKNOWN or INTEGRATION_ACTION_UNAVAILABLE (each action named in issues at /actions/<n>), INPUT_SOURCE_INVALID (an input the action does not take, a source kind not allowed here, a malformed fixed value or list; each named in issues by path, such as /actions/0/inputs/items), INTEGRATION_LIMIT (at most 8 integrations and 64 integration actions per agent, and 8 webhooks and call transfers on every step), TOOL_GRANT_KIND (tool_id is not a webhook or a call transfer), TOOL_GRANT_CHANNEL (a call transfer on an agent without phone calls), INTEGRATION_SWITCH_UNAVAILABLE (replace_action_tools with nothing replaceable), WORKFLOW_DOCUMENT_INVALID (the agent has no draft).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: 'WORKFLOW_TOOL_CONTROL_UNAVAILABLE: the actions are still being prepared (Retry-After) or the action service is away. Nothing was saved.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/integrations/{integration_id}:
    patch:
      operationId: updateAgentIntegration
      summary: Change an integration's actions or how their inputs are filled
      description: >
        Requires agents:update. With actions: replaces the integration's actions ("default" for the app's
        defaults); each item may carry inputs as in POST. Actions kept keep their binding and the sources
        their inputs have (except those you send); dropped ones leave every step, with any step's own
        settings for them. With inputs alone: the actions stay and only the named inputs change, keyed by
        action slug ({"GOOGLECALENDAR_FIND_FREE_SLOTS": {"items": source}}); null puts an input back to the
        catalogue's default. For a webhook or call transfer on every step (tg_...), inputs is keyed by its
        binding id ({"t_5c1e9a20": {"<input>": source}}). A write that fixes a calendar on an action whose
        tool was built before it could take one rebuilds that tool first (a new revision of the same tool).
        Saved and published by the same rule as POST.
      tags: [Agents]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: integration_id, in: path, required: true, schema: { type: string, example: i_0b8f4c2e } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              description: Send actions or inputs, not both.
              properties:
                actions:
                  oneOf:
                    - { type: string, const: default }
                    - type: array
                      minItems: 1
                      maxItems: 24
                      items:
                        oneOf:
                          - { type: string, pattern: '^[A-Z0-9_]{1,200}$' }
                          - type: object
                            additionalProperties: false
                            required: [action]
                            properties:
                              action: { type: string, pattern: '^[A-Z0-9_]{1,200}$' }
                              inputs: { type: object, additionalProperties: { oneOf: [{ $ref: '#/components/schemas/ActionInputSource' }, { type: 'null' }] } }
                inputs:
                  type: object
                  description: 'Only how inputs are filled: {"<action slug>": {"<input>": source or null}}, or for a webhook or transfer {"<binding_id>": {...}}.'
                  additionalProperties: { type: object, additionalProperties: { oneOf: [{ $ref: '#/components/schemas/ActionInputSource' }, { type: 'null' }] } }
                publish: { type: boolean, default: true }
                expected_version: { type: integer, minimum: 1 }
            examples:
              actions: { value: { actions: [GOOGLECALENDAR_FIND_FREE_SLOTS, GOOGLECALENDAR_EVENTS_LIST] } }
              chooseCalendar:
                summary: Let the agent choose between two calendars
                value: { inputs: { GOOGLECALENDAR_FIND_FREE_SLOTS: { items: { kind: model, path: /items, options: [{ value: primary, label: Front desk }, { value: c_1a2b3c@group.calendar.google.com, label: Clinic }] } } }, expected_version: 13 }
      responses:
        '200':
          description: The integration (or webhook or transfer) as it is now.
          content:
            application/json:
              schema:
                oneOf:
                  - { $ref: '#/components/schemas/IntegrationWriteResult' }
                  - { $ref: '#/components/schemas/ToolGrantWriteResult' }
        '400': { description: 'AGENT_INTEGRATION_REQUEST_INVALID (actions and inputs both sent), each field named in issues.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'AGENT_NOT_FOUND, INTEGRATION_NOT_FOUND, or TOOL_NOT_FOUND (the webhook or transfer was deleted: remove the entry).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'WORKFLOW_CONFLICT.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'AGENT_INTEGRATION_REQUEST_INVALID (neither actions nor inputs; actions on a webhook or transfer), INPUT_SOURCE_INVALID (each bad source named by path, such as /inputs/GOOGLECALENDAR_FIND_FREE_SLOTS/items), TOOL_CONNECTION_NOT_READY, INTEGRATION_ACTION_UNKNOWN, INTEGRATION_ACTION_UNAVAILABLE, INTEGRATION_LIMIT.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: 'WORKFLOW_TOOL_CONTROL_UNAVAILABLE: still preparing, or "default" asked while an app outside the curated list is still having its action list read (Retry-After); nothing was saved.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
    delete:
      operationId: removeAgentIntegration
      summary: Stop an agent using an app
      description: >
        Requires agents:update. Takes the integration and its actions off every step, with any step's own
        settings for them (also for a webhook or transfer on every step, tg_...). The account stays
        connected and other agents keep it. Saved, and published by the same rule as POST unless
        publish=false.
      tags: [Agents]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: integration_id, in: path, required: true, schema: { type: string } }
        - { name: publish, in: query, required: false, schema: { type: boolean, default: true } }
        - { name: expected_version, in: query, required: false, schema: { type: integer, minimum: 1 } }
      responses:
        '200':
          description: Removed.
          content:
            application/json:
              schema:
                type: object
                required: [removed, draft_version, live]
                properties:
                  removed: { type: boolean, const: true }
                  draft_version: { type: integer }
                  live: { type: boolean, description: The removal is on calls now. }
                  not_live_reason: { type: string }
                  settings_updated_at: { type: string, format: date-time, description: 'Present when live is true: the agent''s new settings token (see POST /agents/{id}/workflow/publish).' }
        '400': { description: 'AGENTS_QUERY_INVALID: a query parameter other than publish and expected_version, or one of those malformed.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'AGENT_NOT_FOUND or INTEGRATION_NOT_FOUND.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'WORKFLOW_CONFLICT.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/workflow/versions:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
    get:
      summary: List published workflow versions
      operationId: listWorkflowVersions
      tags: [Workflows]
      description: Requires agents:read. Newest first; this lists publication summaries, not runtime receipts or call history.
      parameters:
        - { in: query, name: cursor, schema: { type: integer, minimum: 1 }, description: Exclusive version cursor from next_cursor. }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        '200':
          description: Published versions.
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  next_cursor: { type: [integer, 'null'] }
                  data:
                    type: array
                    items:
                      allOf:
                        - $ref: '#/components/schemas/WorkflowRevisionSummary'
                        - type: object
                          properties:
                            draft_version: { type: integer, minimum: 1 }
                            compiler_version: { type: string }
                            environment: { type: string }
                        - $ref: '#/components/schemas/WorkflowVersionProvenance'
        '400': { description: 'WORKFLOW_REQUEST_INVALID: a limit outside 1-100 (refused, not clamped), a cursor that is not a version number from next_cursor, or a query parameter this route does not read (it reads limit and cursor), refused by name rather than ignored; issues[0].path names the parameter.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404': { description: Agent unavailable in this company., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/workflow/versions/{version_id}:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: path, name: version_id, required: true, schema: { type: string, format: uuid }, description: "A version's id, from `data[].id` of GET /agents/{id}/workflow/versions." }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
    get:
      summary: Read one published workflow version
      operationId: getWorkflowVersion
      tags: [Workflows]
      description: >
        Requires agents:read. Returns one published version of the agent with its complete workflow
        document, the exact text that version ran. Use it to look at an older version before restoring
        it. `is_current` says whether callers reach this version now. Takes no query parameters.
      responses:
        '200':
          description: The version and its document.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowVersionDetail' } } }
        '400': { description: 'WORKFLOW_REQUEST_INVALID: a query parameter (this route reads none).', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API key belongs to.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'WORKFLOW_NOT_FOUND: the agent is unavailable in this company, or the id is not a version of this agent (an id that is not a UUID, an unknown id and another agent''s version all answer the same).', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
  /agents/{id}/workflow/restore:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
    post:
      summary: Restore an earlier workflow version
      operationId: restoreWorkflowVersion
      tags: [Workflows]
      description: >
        Requires agents:update. Makes an earlier version's workflow live again by publishing a copy of it
        as a NEW version (roll-forward): version numbers only go up, the version you restored from stays in
        the history, and callers reach the new version on their next call. A call already in progress keeps
        the version it started on. The copy is built again from the old document, so it is not guaranteed
        to be byte-identical to the old version: an agent whose version was rebuilt on 2026-11-12 can
        differ in compiled details, and the restore is refused when the old document no longer passes
        today's checks (for example a tool in it was archived). Name the version with exactly one of
        version_id or version. Not idempotent: each successful call creates one more version, so do not
        retry a request whose answer you did not receive without reading the version list first. Refused
        with 409 WORKFLOW_DRAFT_HAS_UNPUBLISHED_CHANGES while the saved draft holds changes that are not
        published, unless discard_draft is true (the draft is then replaced by the restored workflow).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WorkflowRestoreRequest" }
      responses:
        '201':
          description: The restored workflow is live as a new version.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowRestoreResponse' } } }
        '400': { description: 'WORKFLOW_REQUEST_INVALID: both or neither of version_id and version, a malformed field, another field, or a query parameter. issues[] names each by path.', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API key belongs to.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'WORKFLOW_NOT_FOUND: the agent is unavailable in this company, or no version of this agent has that id or number.', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '409':
          description: |
            One of three refusals; nothing was published and the draft is untouched.
            `WORKFLOW_CONFLICT` — `expected_version` is not the saved draft's version now (`current_version` names it).
            `WORKFLOW_DRAFT_HAS_UNPUBLISHED_CHANGES` — the saved draft differs from the published version; the body carries `reason: "draft_has_unpublished_changes"`. Publish or discard the draft first, or send `discard_draft: true`.
            `WORKFLOW_VERSION_IS_CURRENT` — the named version is the one callers reach now; there is nothing to restore.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowError' }
              examples:
                draftHasUnpublishedChanges:
                  summary: The draft holds changes that are not published
                  value: { error: "The saved draft has changes that are not published. Publish or discard them first, or restore with discard_draft set to true.", code: WORKFLOW_DRAFT_HAS_UNPUBLISHED_CHANGES, reason: draft_has_unpublished_changes }
        '422': { description: 'WORKFLOW_REFERENCE_INVALID or WORKFLOW_VALIDATION_FAILED: the old document no longer passes today''s checks (an archived tool, a connection that moved), with issues[]. Nothing was published and the draft is put back as it was.', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '503': { description: 'WORKFLOW_COMPILER_UNAVAILABLE: no version was published; read the version list before retrying.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /agents/{id}/workflow/train:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
    post:
      summary: Teach the agent from a test call
      operationId: trainWorkflow
      tags: [Workflows]
      description: >
        Requires agents:update and calls:read (it reads the call's transcript). Reads a finished web test call (a call made from the dashboard's test
        panel or a test link; never a phone call) and, when the person testing told the agent how to
        behave, rewrites that agent's instructions and publishes the result live. The call must be a recent
        browser test call of this agent (any owner or admin of the workspace can teach from it, not only
        the person who took it), the API key's owner must be an owner or admin of the workspace, the agent must
        run a published workflow, and the call must have run on the agent's current version. The edit is
        small and checked (a few changes at most, wording that was not asked for is refused, tools and
        numbers are protected); when it cannot be applied safely the run ends held and nothing changes.
        Idempotent per call_id: sending the same request again returns the same run, so repeat it to
        poll. The answer is 200 when the run has finished and 202 while it is working (wait retry_after_ms
        and send it again). To undo an applied run, restore its base_revision with POST
        /agents/{id}/workflow/restore.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/WorkflowTrainRequest" }
      responses:
        '200':
          description: The run has finished (applied, no_change, held, failed or reverted).
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowTrainResponse' } } }
        '202':
          description: The run is still working, or the call has not ended yet (run null, wait call_running). Send the same request again after retry_after_ms.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowTrainResponse' } } }
        '400': { description: 'WORKFLOW_REQUEST_INVALID: call_id missing or not a UUID, another field, or a query parameter.', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'TEACH_FORBIDDEN_ROLE (the key''s owner is not an owner or admin), TEACH_DISABLED (teaching is switched off), TEACH_ACTOR_REQUIRED (the key has no owner to act as) or WORKSPACE_MISMATCH.', content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
        '404': { description: 'AGENT_NOT_FOUND, TEACH_CALL_NOT_FOUND or TEACH_RUN_NOT_FOUND.', content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
        '409': { description: 'TEACH_AGENT_BUSY (another run is working on this agent), TEACH_CALL_NOT_ON_LIVE_VERSION (the call ran on an older version than the one live now) or TEACH_RETRY_NOT_ALLOWED.', content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
        '422': { description: 'AGENT_ENGINE_UNSUPPORTED, TEACH_AGENT_NOT_PUBLISHED, TEACH_CALL_AGENT_MISMATCH (the call is another agent''s), TEACH_CALL_NOT_WEB (a phone call), TEACH_CALL_TOO_OLD (older than 30 minutes), TEACH_CALL_RUN_UNAVAILABLE or TEACH_ENVIRONMENT_MISMATCH.', content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
        '429': { description: 'TEACH_DAILY_LIMIT: three applied runs for this agent in the last 24 hours.', content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
        '500': { description: TEACH_INTERNAL., content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
    get:
      summary: Read the result of teaching from a call
      operationId: getWorkflowTraining
      tags: [Workflows]
      description: Requires agents:read and calls:read (the run carries quotes from the call's transcript). Returns the run for a call without starting or changing anything (run is null when the call was never taught from). For a run that is working, retry_after_ms says when to ask again.
      parameters:
        - { in: query, name: call_id, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: The run, or null.
          content: { application/json: { schema: { type: object, required: [run], properties: { run: { oneOf: [{ type: 'null' }, { $ref: '#/components/schemas/WorkflowTrainRun' }] } } } } }
        '400': { description: 'WORKFLOW_REQUEST_INVALID: call_id missing or not a UUID, or another query parameter.', content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'TEACH_FORBIDDEN_ROLE, TEACH_ACTOR_REQUIRED or WORKSPACE_MISMATCH.', content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
        '404': { description: 'AGENT_NOT_FOUND or TEACH_CALL_NOT_FOUND.', content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
        '422': { description: TEACH_CALL_AGENT_MISMATCH or TEACH_CALL_NOT_WEB., content: { application/json: { schema: { $ref: '#/components/schemas/TeachError' } } } }
  /tools/workflow-catalog:
    get:
      summary: List safe workflow binding revisions
      operationId: listWorkflowCatalog
      tags: [Workflows]
      description: Requires tools:read. Safe company catalog used by the builder. Current revisions are selectable; explicit historical references describe existing/pinned bindings only. No raw execution configuration, private credential or provider account ID is included. Intrinsic End is not a tool. Responses have a1MiB technical budget; reduce limit/references on413.
      parameters:
        - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 50, default: 20 } }
        - { in: query, name: cursor, schema: { type: string, maxLength: 512 }, description: Opaque continuation bound to company and unchanged query. }
        - { in: query, name: revision_ids, schema: { type: string, maxLength: 369 }, description: Up to10 comma-separated local revision UUIDs; do not use vendor identifiers. }
      responses:
        '200':
          description: Current and explicitly referenced safe revisions.
          content:
            application/json:
              schema:
                type: object
                required: [data, references, unavailable_revision_ids, next_cursor]
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/WorkflowCatalogRevision' } }
                  references: { type: array, items: { $ref: '#/components/schemas/WorkflowCatalogRevision' } }
                  unavailable_revision_ids: { type: array, items: { type: string, format: uuid } }
                  next_cursor: { type: [string, 'null'] }
        '400': { description: 'WORKFLOW_CATALOG_QUERY_INVALID - an unknown or repeated parameter, a limit outside 1-50, malformed revision_ids, or a cursor issued for another query. The message says what the parameter takes and issues[0].path names it; tool_id is not a parameter here - read one tool with GET /tools/{id}.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '413': { description: WORKFLOW_CATALOG_TOO_LARGE or WORKFLOW_CATALOG_ITEM_TOO_LARGE., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: WORKFLOW_CATALOG_UNAVAILABLE., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /billing:
    get:
      summary: Get billing status
      description: >
        Returns current balance, payment method status, and auto top-up settings.
        Required scope `billing:read`. No personal data comes back on this read:
        `billing_email` is masked to its first character and domain, so a balance
        check never hands out the address the workspace is billed to.
        For what was actually spent, and on what, use GET /billing/consumption.
      operationId: getBilling
      tags: [Billing]
      responses:
        "200":
          description: Billing status
          content:
            application/json:
              schema:
                type: object
                properties:
                  has_payment_method:
                    type: boolean
                    description: >
                      True when a card is saved for the workspace's billing - the card automatic
                      top-ups and phone-number rent are charged to. False when none is. It does not say
                      whether the next charge will succeed.
                  billing_email:
                    type: string
                    nullable: true
                    description: >
                      The billing address, masked to its first character and its domain
                      (`s***@example.com`). Null when no address is set. The whole address is
                      never returned here - read it in the dashboard's billing settings.
                    example: "s***@example.com"
                  balance_cents: { type: integer }
                  balance: { type: number, description: "balance_cents / 100" }
                  currency: { type: string, example: usd  }
                  is_suspended: { type: boolean }
                  auto_topup_enabled: { type: boolean, description: "False until auto top-up is switched on, and on a workspace that never set it up." }
                  auto_topup_amount_cents:
                    type: integer
                    nullable: true
                    description: >
                      What an automatic top-up charges, before VAT. Kept while auto top-up is off - the
                      stored default or the last amount saved, such as 5000 - so read it only when
                      `auto_topup_enabled` is true. Null only before the workspace has a credit account.
                    example: 5000
                  low_balance_threshold_cents:
                    type: integer
                    nullable: true
                    description: >
                      The balance below which an automatic top-up is charged. Kept while auto top-up is
                      off, like `auto_topup_amount_cents`. Null only before the workspace has a credit
                      account.
                    example: 500
                  monthly_budget_cents:
                    type: integer
                    nullable: true
                    description: >
                      The workspace's own CALENDAR-MONTH spending limit, in cents, covering
                      every outbound PHONE call in the workspace — the ones asked for through
                      the API or by a campaign. Calls coming in, browser rehearsals
                      (`POST /calls {"type":"web"}`) and the calls a shared link places keep
                      working while it is reached. Null means no limit is set, which is the
                      default. Change it with PATCH /billing. Not the same as a campaign's
                      `budget_cents`, which is one campaign's lifetime budget.
                    example: 5000
                  monthly_spend_cents:
                    type: integer
                    description: >
                      Charges completed since the start of the current calendar month (UTC).
                      Reported whether or not a spending limit is set.
                      Top-ups and refunds are not spend and are not counted.
                    example: 1240
                  monthly_budget_remaining_cents:
                    type: integer
                    nullable: true
                    description: Limit minus spend, never below zero. Null when no limit is set.
                    example: 3760
                  monthly_budget_reached:
                    type: boolean
                    description: >
                      True when the limit is set and this month's spend has reached it. While
                      true, POST /calls answers 402 SPEND_BUDGET_REACHED and queued outbound
                      calls (campaigns included) are failed with the same sentence. Calls
                      coming in are unaffected.
                  monthly_period_start:
                    type: string
                    format: date-time
                    description: Start of the month the spend was measured over.
                  upcoming_charges:
                    type: array
                    nullable: true
                    description: >
                      What the card is due to be charged, soonest first: each number whose rent Yappr
                      charges, on its next renewal (a number whose release is scheduled does not renew,
                      and is not listed), then the automatic top-up while it is on (due when
                      the balance falls below its threshold). Before VAT. Empty when nothing is due;
                      null when it could not be read - the rest of this read still answers.
                    items: { $ref: "#/components/schemas/UpcomingCharge" }
        "400":
          description: "BILLING_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "401":
          description: Unauthorized
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

    patch:
      summary: Set the monthly spending limit
      description: |
        Sets, changes or removes the workspace's own monthly spending limit — the one
        writable field on the billing status. Required scope `billing:manage`.

        Send `monthly_budget_cents` as a whole number of cents to limit this calendar
        month's spending to, or `null` to turn the limit off. `0` is a valid limit and
        stops outbound calling immediately.

        While the limit is reached, `POST /calls` answers `402 SPEND_BUDGET_REACHED` and
        queued outbound calls — campaigns included — are failed with the same sentence.
        Three things keep working and are not exemptions that were forgotten: calls coming
        in, browser rehearsals (`POST /calls {"type":"web"}`, which is what the dashboard's
        Test Call places) and the calls a shared link places. The limit lifts by itself at
        the start of the next calendar month.

        Balances, suspension and the auto top-up settings are not writable here: money
        moves through POST /billing/topup and the Stripe Checkout it returns.
      operationId: updateBilling
      tags: [Billing]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [monthly_budget_cents]
              properties:
                monthly_budget_cents:
                  type: integer
                  nullable: true
                  minimum: 0
                  maximum: 2147483647
                  example: 5000
                  description: Cents to limit this month's spending to, or null for no limit.
      responses:
        "200":
          description: The saved limit, and where the month stands against it
          content:
            application/json:
              schema:
                type: object
                properties:
                  monthly_budget_cents: { type: integer, nullable: true }
                  monthly_spend_cents: { type: integer }
                  monthly_budget_remaining_cents: { type: integer, nullable: true }
                  monthly_budget_reached: { type: boolean }
                  monthly_period_start: { type: string, format: date-time }
        "400":
          description: "`monthly_budget_cents` is missing, negative, past 2147483647, or not a whole number of cents (`SPEND_BUDGET_INVALID`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "401":
          description: Unauthorized
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /billing/setup:
    post:
      summary: Setup payment method
      description: >-
        Requires billing:manage. Generates a hosted Stripe Checkout URL to add or replace the
        workspace's card. Nothing is charged. Send a JSON body; `{}` is enough.
      operationId: setupBilling
      tags: [Billing]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                returnUrl: { type: string, format: uri, description: "Where Checkout sends the person back, on success and on cancel. Defaults to the dashboard." }
                locale: { type: string, enum: [en, he], description: The language kept for the workspace's billing emails when the billing account is first created. }
      responses:
        "200":
          description: Checkout URL
          content:
            application/json:
              schema:
                type: object
                required: [checkoutUrl, sessionId]
                properties:
                  checkoutUrl: { type: string, format: uri }
                  sessionId: { type: string }
                  customerId: { type: string, description: The workspace's Stripe customer. }

  /billing/topup:
    post:
      summary: Top up credits
      description: |
        Requires billing:manage. Creates a hosted Checkout URL for an interactive credit
        purchase. This endpoint never charges the saved card off-session; send the user to the
        returned URL to confirm the payment. `amount_cents` is the credit bought; 18% VAT is
        added on top at Checkout.
      operationId: topupBilling
      tags: [Billing]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [amount_cents]
              properties:
                amount_cents:
                  type: integer
                  minimum: 100
                  example: 2000
                  description: Credit to buy, in cents (e.g. 2000 = $20.00). 18% VAT is added on top.
                returnUrl: { type: string, format: uri, description: "Where Checkout sends the person back, on success and on cancel. Defaults to the dashboard." }
                locale: { type: string, enum: [en, he], description: The language kept for the workspace's billing emails when the billing account is first created. }
      responses:
        "200":
          description: Hosted Checkout created
          content:
            application/json:
              schema:
                type: object
                required: [checkoutUrl, sessionId]
                properties:
                  checkoutUrl: { type: string, format: uri }
                  sessionId: { type: string }

  /agents:
    get:
      summary: List agents
      description: Requires agents:read. Newest first. name narrows the list to agents whose name contains that text; pagination.total counts the matches, not the whole workspace.
      operationId: listAgents
      tags: [Agents]
      parameters:
        - in: query
          name: name
          schema: { type: string, minLength: 1, maxLength: 200 }
          description: "Only agents whose name contains this text, case-insensitively, anywhere in the name. Every character matches itself: %, _ and * are not wildcards. Leading and trailing spaces are ignored."
        - in: query
          name: limit
          schema: { type: integer, default: 20, maximum: 100 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: List of agents
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Agent" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean }
        "400":
          description: >
            AGENTS_QUERY_INVALID — a parameter other than `limit`, `offset` and `name` (there is
            no `search` or status filter), a parameter sent twice or with no value, a `name`
            longer than 200 characters or with a control character, or a `limit` / `offset`
            that is not a whole number. Refused rather than answered with every agent.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

    post:
      summary: Create agent
      description: >
        Requires agents:create. Creates one unpublished workflow agent and its canonical initial draft
        atomically: Strict Mode off, one conversation step and a closing route, empty Before and After
        phases. Only name, description, language, authoring_locale, greeting_message, model, template and workflow
        are accepted; identity and execution ownership are assigned by Yappr, and an agent created without a model
        is automatic (see `model`). An agent has no direction: a phone
        number's inbound_agent_id or a SIP address endpoint makes it answer calls (a username-and-password trunk too, once the workflow is published), and POST /calls (or a number's
        outbound_agent_id) makes it place them. Save and explicitly publish through the workflow endpoints —
        creation alone starts nothing. Creating a prompt or flow agent is gone: a body carrying system_prompt,
        type, flow_config, tools or another field only that agent had answers 410 AGENT_LEGACY_CREATION_GONE.
      operationId: createAgent
      tags: [Agents]
      parameters:
        - in: header
          name: Idempotency-Key
          required: true
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{16,128}$' }
          description: Scoped to this company and creation endpoint. The same normalized accepted body returns the original agent with 200; a changed body returns 409. Retry a lost response with the same key. An archived or removed original returns 410 AGENT_CREATION_GONE without recreating it; a merely disabled original returns 200 unchanged.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              additionalProperties: false
              description: Send workflow or template.
              properties:
                name: { type: string, minLength: 1, maxLength: 200, example: "Reception assistant" }
                description: { type: string, nullable: true, maxLength: 2000 }
                language:
                  type: string
                  enum: [he, en, ar, ru, fr, es, de, it, pt, nl, tr, pl, uk, hi, ja, ko, zh, multi, he-IL, iw, en-US, en-GB]
                  default: he
                  description: The language the agent speaks and listens for on calls, or multi for a multilingual agent that answers in the caller's language (see the Languages page). he-IL and iw are read as he, en-US and en-GB as en, as PATCH /agents/{id} reads them; the agent stores and answers the short form. An en agent opens and talks in English, from its first word; a he agent in Hebrew; an fr agent in French. The dashboard's Call language (New Agent, Agent settings) is the same field.
                greeting_message:
                  type: string
                  nullable: true
                  description: >
                    The opening line, said word for word when the agent speaks first (a second-family voice
                    can still word it slightly differently), with {{FirstName}}
                    filled in from the call's variables or the lead's name, or left out with the space before
                    it. Saved the way PATCH /agents/{id} saves it, so the key needs agents:update as well as
                    agents:create; null or omitted leaves the agent without one. It is not part of what the
                    Idempotency-Key matches: a replay with the same key saves it only while the agent has no
                    opening line and is unchanged since it was created (the first answer was lost before
                    the line was saved), and otherwise answers 200 with the agent as it is, never 409, even
                    when this line differs from the first request's. Random variations: {{Hi|Hello|Hey}}
                    (two or more options separated by |) says one option, picked once per call; see
                    [Random variations](/api-reference/agents/create#random-variations).
                model:
                  type: string
                  nullable: true
                  enum: [gemini-3.1-flash-live, gemini-3.8-live]
                  description: >
                    The voice model the new agent runs on. Omit it or send null for automatic: Yappr picks
                    by the agent's language. `gpt-live` is not accepted here, because it needs one of its own
                    voices and a new agent starts on a Gemini voice: create the agent, then send `model`
                    `gpt-live` with a voice to PATCH /agents/{id}. Part of what the Idempotency-Key matches
                    when sent; a request without it matches one made before models could be chosen.
                authoring_locale:
                  type: string
                  enum: [he, en]
                  description: >
                    The language Yappr writes the starting step names, their instructions and the closing
                    route condition in. Nobody speaks these; they are read by whoever opens the workflow.
                    Defaults to he for a Hebrew agent and en for any other language (multi included).
                    Sending it does not change what the call is spoken in.
                template:
                  type: string
                  enum: [inbound, qualify, reminder]
                  description: >
                    Start from one of the dashboard's starters: inbound answers incoming calls, qualify calls
                    a lead back, reminder confirms a booked appointment. Yappr writes the starter's text into
                    workflow.global_instructions, in authoring_locale. Takes the place of workflow; sending
                    both with non-empty instructions is refused.
                workflow:
                  type: object
                  additionalProperties: false
                  properties:
                    global_instructions: { type: string, maxLength: 100000, default: "", description: "The agent's instructions. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations)." }
      responses:
        "201":
          description: Agent created as an unpublished draft.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CreatedAgent" }
        "200":
          description: Idempotent replay; the original agent is returned without reactivation.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CreatedAgent" }
        "400":
          description: >
            AGENT_IDEMPOTENCY_DUPLICATED — the Idempotency-Key header arrived more than once, so no
            one key makes the request repeatable; send exactly one.
            AGENT_IDEMPOTENCY_REQUIRED — the Idempotency-Key header is missing or outside 16–128 letters,
            digits, underscores or hyphens. WORKFLOW_AGENT_REQUEST_INVALID — a field outside name,
            description, language, authoring_locale, greeting_message, model, template and
            workflow.global_instructions, one of
            them out of range, neither workflow nor template, or a template beside non-empty instructions.
            Every problem in the body is named in the one answer: issues[] holds one entry per field at
            fault (code field_unknown, field_required or field_invalid, path such as /language or
            /workflow/global_instructions, message), and error repeats the first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }
        "403":
          description: INSUFFICIENT_SCOPE — the key lacks agents:create, or the body carries greeting_message and the key lacks agents:update, which saving the opening line needs. Nothing was created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: WORKFLOW_NOT_FOUND — the workspace does not exist for this credential.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: AGENT_IDEMPOTENCY_CONFLICT — the creation key was used with a different name, description, language, authoring_locale, model or instructions. greeting_message is not compared.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "410":
          description: >
            AGENT_LEGACY_CREATION_GONE — the body carries system_prompt, type, flow_config, tools,
            tool_ids, prompt, webhook_url, webhook_events or webhook_headers, which asks for the retired
            prompt or flow agent; send name plus workflow.global_instructions or a template instead. A body
            that merely left something out is the 400 above, not this. AGENT_CREATION_GONE — the
            agent this key created was archived or removed; the key cannot create another.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: WORKFLOW_STORAGE_UNAVAILABLE — draft persistence is unavailable, or the agent was created and its greeting_message could not be saved. Retry the exact request with the same Idempotency-Key; the retry returns the agent, with the opening line saved.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /agents/{id}/extraction/dry-run:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Dry-run extraction
      description: >
        Requires agents:read. Reads a transcript you supply for the values this agent collects, and
        returns them. It places no call, writes no call row, and changes nothing about the agent - a
        browser session minted with POST /calls {"type":"web"} writes nothing until a browser
        connects it, so an integration with no browser had no way to prove its extraction parameters
        work before a real caller met them. The transcript is read the way a finished call's is - the
        same instructions to the model, the same model and settings, the same coercion a real call's
        extracted_data goes through, and the same day to count dates from (reference_time standing in
        for the call's start) - so what comes back is what the agent will collect from that
        conversation. It costs a model call.
      operationId: dryRunAgentExtraction
      tags: [Agents]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [transcript]
              properties:
                transcript:
                  description: >
                    The conversation to read - either an array of {"role","text"} turns, the shape
                    GET /calls/{id} returns, or text with one turn per line, each line opening with its
                    speaker and a colon (Agent, User, Caller, Customer, Voicemail, סוכן, משתמש, מתקשר,
                    לקוח or תא קולי, any case); a line that does not is refused with
                    EXTRACTION_DRY_RUN_TRANSCRIPT_UNLABELLED. In the array, role is agent, user or
                    voicemail; anything else reads as the caller. At most 400 turns and 40000
                    characters.
                  oneOf:
                    - type: string
                    - type: array
                      maxItems: 400
                      items:
                        type: object
                        required: [text]
                        properties:
                          role: { type: string, enum: [agent, user, voicemail] }
                          text: { type: string }
                reference_time:
                  type: string
                  description: >
                    The day the conversation happened on, which its dates ("tomorrow", "next Sunday",
                    "the first of November") are read from - a plain YYYY-MM-DD taken as that day, or a
                    timestamp with its zone, read in the workspace's time zone as a real call's start is.
                    Left out, it is today. A timestamp with no zone is refused.
                  example: "2026-09-23T12:44:00+03:00"
                extraction_parameters:
                  type: array
                  description: >
                    A set to try instead of the agent's own, so a parameter can be seen working
                    before it is saved with PATCH /agents/{id}. Held to exactly what PATCH accepts -
                    an entry PATCH refuses, such as "type": "bool", is refused here with PATCH's
                    message. Leave it out to use the agent's.
                  items:
                    type: object
                    required: [name, description]
                    properties:
                      name: { type: string }
                      description: { type: string }
                      type: { type: string, enum: [text, number, yes_no, date] }
      responses:
        "200":
          description: The values the transcript gave up.
          content:
            application/json:
              schema:
                type: object
                properties:
                  agent_id: { type: string, format: uuid }
                  transcript_turns: { type: integer, description: "How many non-empty turns were read." }
                  extraction_parameters:
                    type: array
                    description: >
                      The parameters that were read for, each with the kind it was read as. A type sent
                      in extraction_parameters must be one of the four (anything else is 400); a
                      parameter saved on the agent with no type is read, and echoed, as text.
                    items:
                      type: object
                      properties:
                        name: { type: string }
                        type: { type: string, enum: [text, number, yes_no, date] }
                  extracted_data:
                    type: object
                    description: >
                      Keyed by your parameters and by nothing else - a key the model invented is
                      dropped, and a parameter it left out is still a key, with null. null means the
                      conversation never said it, which is different from a key that is absent because
                      you never asked for it. A number is one number - "about 12" is 12, a half is kept
                      ("two and a half" is 2.5), a range is its middle ("3-4" is 3.5). A date is a
                      YYYY-MM-DD day or null - a month with no day is null, and extracted_data_precision
                      says it was a month.
                  extracted_data_precision:
                    type: object
                    description: >
                      One entry per date parameter, saying how precisely the caller gave it: day, month
                      or unknown, with the reader's role for the day (event or message) when it gave one.
                      Present only when a date parameter was read for.
                    additionalProperties: { $ref: "#/components/schemas/ExtractedDatePrecision" }
                    example: { interview_date: { precision: month, month: "2026-11" }, arrival_date: { precision: month, month: "2024-03", approximate: true }, surgery_date: { precision: day, month: "2026-12", role: event } }
                  extracted_data_ranges:
                    type: object
                    description: >
                      One entry per number parameter whose answer is the middle of a range the caller
                      gave, with the range's two ends. Present only when there is one.
                    additionalProperties: { $ref: "#/components/schemas/ExtractedNumberRange" }
                    example: { pain_level: { low: 6, high: 7 } }
                  reference_date:
                    type: string
                    format: date
                    description: The day the transcript's dates were read from - reference_time, or today.
                  timezone:
                    type: string
                    description: >
                      The IANA zone reference_date is in - the workspace's, or UTC when it has none. A
                      workspace left on UTC reads a call made in Israel after midnight as the day before.
        "400":
          description: >
            `EXTRACTION_DRY_RUN_INVALID` - no transcript, an empty one, a turn with no text, a
            transcript over the size limits, an extraction_parameters entry PATCH /agents/{id} would
            refuse (in PATCH's words), a reference_time that is neither a date nor a timestamp with its
            zone, or a field this endpoint does not take. The message names it.
            `EXTRACTION_DRY_RUN_TRANSCRIPT_UNLABELLED` - a transcript sent as text has a line that does
            not open with a speaker; the message gives the line number.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: >
            `INSUFFICIENT_SCOPE` - the key has no agents:read. `AGENT_OUTSIDE_KEY_SCOPE` - the key is
            limited to some agents and this is not one of them; the same answer whether it exists or not.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "`AGENT_NOT_FOUND` - no such agent in this workspace, or it is archived."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "405":
          description: "`METHOD_NOT_ALLOWED` - any method but POST; the Allow header says POST. Nothing was read."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: >
            `EXTRACTION_NOT_CONFIGURED` - the agent has no extraction parameters and the request sent
            no extraction_parameters either, so there is nothing to read the transcript for. A
            malformed entry in extraction_parameters is 400 EXTRACTION_DRY_RUN_INVALID instead: it is
            a fact about the request, not about the agent.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: >
            `EXTRACTION_DRY_RUN_UNAVAILABLE` - the reader could not be reached. Nothing was read and
            nothing was changed; send the same request again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /agents/{id}/duplicate:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Duplicate agent
      description: >
        Requires agents:create. Copies the source agent's ordinary settings (voice, model, VAD,
        timeouts, background sound, extraction parameters, and the rest) and its current draft
        workflow document — bindings, positions, everything — into one new agent, created switched
        off and unpublished. Editing the source afterwards never changes the copy and editing the
        copy never changes the source: the two agents are independent from the moment this call
        returns, though the tools behind them are shared (below). What is not copied is the phone side and everything that names the source
        specifically: no phone number or SIP endpoint is repointed, no shared web-call link is
        minted, and history (call logs, workflow revisions, eval suites, in-flight promotions) starts
        empty on the copy. By default the copy's workflow bindings keep the source's exact
        tool_revision_id pins, so it shares its source's tools rather than getting new ones. One
        live tool serves both agents: a later PATCH /tools/{id} — the natural first move for giving
        the second client its own webhook — changes it for the first agent too, and archiving a
        shared tool affects both. Send fork_tools true to give the copy tools of its own in the same
        call: every tool the copy would share becomes a new tool named "<tool> (copy)", then
        "(copy 2)", "(copy 3)" for later forks of the same tool, and the copy's bindings (and the
        step labels that still carry the source tool's name) are repointed at them. The fork runs on
        the server to the end even if you disconnect. What it cannot carry: header values and the
        private part of a URL are never readable, so each forked HTTP tool keeps its header names with
        empty values and its address without the private query — tool_fork lists which ones need a
        value entered (PATCH /tools/{id}) before the copy takes calls. fork_tools also needs
        tools:create on the key. Publishing the copy, and pointing any number at it, are separate
        calls you make afterwards.
      operationId: duplicateAgent
      tags: [Agents]
      parameters:
        - in: header
          name: Idempotency-Key
          required: true
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{16,128}$' }
          description: Scoped to this company and this endpoint, and keyed together with the source agent id — the same key replayed against the same source returns the same copy with 200; the same key aimed at a different source, or already spent on POST /agents, is a 409. Retry a lost response with the same key.
      requestBody:
        required: false
        description: The body, or no body at all, is optional — "copy this agent" is the whole request in the common case.
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                name: { type: string, minLength: 1, maxLength: 200, description: "Defaults to \"<source name> (copy)\", or the Hebrew equivalent when the copy's language is he." }
                description: { type: string, nullable: true, maxLength: 2000, description: "Omit to copy the source's description verbatim; send null to clear it on the copy." }
                language:
                  type: string
                  enum: [he, en, ar, ru, fr, es, de, it, pt, nl, tr, pl, uk, hi, ja, ko, zh, multi, he-IL, iw, en-US, en-GB]
                  description: Omit to copy the source's language. Any of the call languages, or multi; he-IL and iw are stored as he, en-US and en-GB as en.
                model:
                  type: string
                  nullable: true
                  enum: [gemini-3.1-flash-live, gemini-3.8-live, gpt-live]
                  description: >
                    Omit to copy the source's `model`. Send one to give the copy a different model of the
                    source's own voice family — the way to run the same agent on both Gemini models side by
                    side — or null to make the copy automatic. The copy keeps the source's voice, so the
                    model has to be one that voice belongs to: a Gemini model (or null) for a Gemini voice,
                    `gpt-live` for a GPT Live voice. To move the copy to the other family, duplicate it and
                    then PATCH /agents/{id} with `model` and a voice of that family.
                fork_tools:
                  type: boolean
                  default: false
                  description: >
                    true gives the copy its own copy of every tool it would otherwise share with the
                    source, in this same call, and adds tool_fork to the response. Not part of the
                    copy's identity: repeating the request with the same Idempotency-Key and
                    fork_tools true returns the same copy and finishes a fork that was partial —
                    tools it already made are replayed, never made twice. Forked tools are named in
                    the copy's language. Requires tools:create as well as agents:create.
      responses:
        "201":
          description: The copy, in the same body shape POST /agents returns, plus idempotency_key echoing the Idempotency-Key you sent. published_workflow_revision_id is null and is_active is false. With fork_tools true, tool_fork says what the fork did.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DuplicatedAgent" }
        "200":
          description: Idempotent replay of the same key with the same request; the original copy is returned unchanged, with idempotency_key echoing the key that made it. With fork_tools true the fork runs again and finishes whatever the first request left shared.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DuplicatedAgent" }
        "400":
          description: >
            AGENT_IDEMPOTENCY_REQUIRED — the Idempotency-Key header is missing or outside 16–128 letters,
            digits, underscores or hyphens. AGENT_IDEMPOTENCY_DUPLICATED — it arrived more than once;
            send exactly one.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: INSUFFICIENT_SCOPE — fork_tools true was sent with a key that lacks tools:create. Nothing was copied.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: AGENT_NOT_FOUND — the source agent is absent, archived, or belongs to another company. WORKFLOW_NOT_FOUND — it is there but is not a workflow agent.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: >
            AGENT_IDEMPOTENCY_CONFLICT — the Idempotency-Key was already used for a different copy (a
            different source, or a different accepted body). WORKFLOW_REFERENCE_INVALID — the source's
            workflow binds a tool that is archived, or an app tool whose account is no longer connected;
            nothing is written. The error names the step and the tool, and issues[] has one entry per
            binding (tool_archived or connection_unavailable at /bindings/<n>/tool_revision_id, with
            node_id, label and tool_name). Restore the tool, or remove the step on the source, then
            duplicate again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "410":
          description: AGENT_CREATION_GONE — the copy this key made has since been archived or removed. The key cannot be reused; use a new key to make another copy.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: >
            WORKFLOW_DUPLICATE_REQUEST_INVALID — the body is not JSON, or carries a field other than
            name, description, language, model or fork_tools, or one of them out of range (fork_tools is
            true or false; model is one of the three ids or null); the message starts with the field at
            fault. WORKFLOW_DUPLICATE_MODEL_INVALID — the model is not one the source's voice belongs to
            (a Gemini model or null on a GPT Live source, or `gpt-live` on a Gemini-voice source);
            nothing was copied. WORKFLOW_DOCUMENT_INVALID —
            the source's own workflow document fails its shape check; open it, save it once, and
            duplicate again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: WORKFLOW_STORAGE_UNAVAILABLE — copying is unavailable. Retry the exact request with the same Idempotency-Key.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }


  /agents/{id}/test-call:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Which line rings a test call
      description: >
        Requires calls:create. Says which number a test call to this agent would come from,
        without placing anything: the workspace's own number when it has one (a number the
        agent calls from, including as the other half of an outbound split; then the from-number
        of a campaign it runs; then a number it answers on; then any active number in the
        workspace; at each step a Yappr-hosted number before one on your own Telnyx account),
        otherwise a Yappr test line. A key limited to agents only ever calls from a number one of
        its agents answers or calls from, and is never told about any other: with none, the Yappr
        test line calls. available is false when neither exists.
      operationId: getAgentTestCallCaller
      tags: [Agents]
      responses:
        "200":
          description: The line a test call would ring from.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AgentTestCallCaller" }
        "400":
          description: AGENTS_QUERY_INVALID — this read takes no query parameters.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: AGENT_NOT_FOUND — no agent with this id in this workspace, or it is archived.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: TEST_CALL_UNAVAILABLE — the workspace's numbers could not be read just now. Retry.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Test an agent by phone
      description: >
        Requires calls:create. Rings the phone number in `to` with this agent, so you hear it the
        way a caller will. The call comes from the workspace's own number when it has one, and
        from a Yappr test line when it has none, so a workspace without a number can still test
        on a real phone. The Yappr test line places calls only; it never answers one. A key
        limited to agents calls only from a number one of its agents answers or calls from, as
        on POST /calls; with none, the Yappr test line calls. GET on this path says which line
        it will be.

        A test call is an ordinary outbound phone call for the workspace: billed per minute at the
        workspace's phone-call price, from the workspace's credit, whichever line it comes
        from, and recorded with source "test" on GET /calls. It is checked like any other
        outbound call (a diallable number, the Do-Not-Call list, the outbound call window, the
        monthly spending limit and the credit floor, and capacity), with no limit of its own on
        how many you place. Two answers differ from POST /calls because someone is waiting on
        the phone: outside the call window, and when every line is busy, the test is refused
        rather than scheduled or queued.

        For an agent that does not run a workflow the call is created at once (201, with its
        id). A workflow agent's call is a phone call request (202, with request_id and call_id
        null) that the workflow prepares and dials within seconds; follow it with
        GET /call-requests/{id} until call_id is set, then GET /calls/{id}.
      operationId: testAgentByPhone
      tags: [Agents]
      parameters:
        - in: header
          name: Idempotency-Key
          required: false
          schema: { type: string }
          description: Workflow agents only. Replaying the same key returns the same call request instead of ringing again.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [to]
              properties:
                to:
                  type: string
                  description: The phone to ring, in E.164 format (e.g. +972501234567). The number that calls is chosen for you; there is no from.
                variables:
                  type: object
                  additionalProperties: { type: string }
                  description: Values for the agent's template variables, as on POST /calls.
            example:
              to: "+972501234567"
              variables: { FirstName: "Dana" }
      responses:
        "201":
          description: The call was placed (an agent that does not run a workflow).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AgentTestCall" }
        "202":
          description: >
            A workflow agent's call request was accepted (request_id set, call_id null), or the
            calling service was briefly unavailable and the call was queued.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AgentTestCall" }
        "400":
          description: >
            invalid_destination — `to` is not a number that can be dialled (E.164, and calls can
            only be placed to Israeli numbers: +972 followed by 8 or 9 digits). SELF_CALL_NOT_ALLOWED — `to` is the number the
            test calls from. TEST_CALL_INVALID — the body carried a field other than `to` and
            `variables`. AGENTS_QUERY_INVALID — a query parameter was sent.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "402":
          description: >
            BILLING_ERROR — the workspace cannot pay for a call now (a call needs at least $1.00 of
            credit, after any auto top-up). SPEND_BUDGET_REACHED — the workspace's own monthly
            spending limit is reached.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: AGENT_NOT_FOUND — no agent with this id in this workspace, or it is archived.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: >
            AGENT_INACTIVE — the agent is switched off. WORKFLOW_UNPUBLISHED — a workflow agent with
            no published version.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: >
            NO_CALLER_NUMBER — the workspace has no number and no Yappr test line is available; add
            a number, or test in the browser. DESTINATION_ON_DNC — `to` is on the workspace's
            Do-Not-Call list. OUTSIDE_CALL_WINDOW — it is outside the workspace's outbound call
            window. TEST_CALL_INVALID — `to` is missing or not text, or `variables` is not an object
            of text values. DESTINATION_OUTSIDE_PHONE_SYSTEM_COUNTRY — the number that would
            call goes out through your phone system's extension in `national` dial format and
            `to` is outside Israel; today such a number is refused first with
            `400 invalid_destination`, in either dial format. A carrier refusal of the
            number itself is answered as on POST /calls.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: >
            AT_CAPACITY — every line is busy; try again in a minute. BILLING_UNAVAILABLE — a top-up
            is still settling; retry shortly. TEST_CALL_UNAVAILABLE or
            WORKFLOW_ADMISSION_UNAVAILABLE — the call could not be placed just now; no call was
            placed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /agents/{id}/settings:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
      - in: header
        name: x-company-id
        schema: { type: string, format: uuid }
        description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH."
    get:
      summary: Read workflow agent settings
      operationId: getAgentSettings
      tags: [Agents]
      description: Requires agents:read. Reads ordinary settings and their original timestamp, including an unarchived disabled agent. Does not read or change a workflow document, validate, publish, or enable calls.
      responses:
        '200':
          description: Allowlisted ordinary settings, with no legacy prompt, graph, webhook credentials, or compiled runtime data.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AgentSettings' }
        '400': { description: 'AGENTS_QUERY_INVALID — a query parameter was sent; this read takes none, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: "INSUFFICIENT_SCOPE — the key does not hold agents:read, and the message names it. Original authority was revoked or expired, or WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API key belongs to.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'Agent absent, archived, foreign-company, or not workflow-owned.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Settings storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }

  /agents/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get agent
      operationId: getAgent
      tags: [Agents]
      responses:
        "200":
          description: Agent with attached tools
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Agent" }
        "400":
          description: "AGENTS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    patch:
      summary: Update agent
      description: >
        Requires agents:update. Send only changed fields, using snake_case. Workflow-owned agents accept only ordinary
        voice, technical and analysis settings: no system_prompt, flow_config, legacy native webhook fields, bindings,
        routing or publication pointers. Use the canonical workflow API for document changes. The optional
        expected_updated_at must exactly match the original settings read; a stale value returns 409 without changes.
        Omission preserves the public API's existing partial-field last-write behavior. Dashboard and chat workflow edits
        require the original timestamp and never silently refresh it on conflict. The total JSON body is limited to
        600000 UTF-8 bytes. Settings changes queue validated effective-snapshot promotion; accepted calls keep their
        immutable snapshots. Saving settings alone does not publish the workflow or enable unready calls.
      operationId: updateAgent
      tags: [Agents]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                expected_updated_at: { type: string, format: date-time, description: "Workflow settings CAS token from the original GET /agents/{id}/settings or Agent response. Do not replace a stale token by silently re-reading." }
                name: { type: string }
                description: { type: string }
                system_prompt: { type: string, description: "Legacy agents only. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations)." }
                flow_config:
                  $ref: "#/components/schemas/FlowConfig"
                  description: >
                    Replace the agent's flow graph (only valid when `type='flow'`). Each successful
                    update writes a new `flow_versions` row, deduped by SHA-256 of the canonical JSON.
                    `type` itself is immutable and rejected if present in the body.
                voice:
                  type: string
                  enum: [Michal, Yonatan, David, Rachel, Gil, Noa, Maya, Adam, Shira, Avigail, Amir, Liat, Omer,
                         Tamar, Tom, Benny, Nir, Natan, Yael, Dvora, Yosef, Shir, Anat, Ariel, Roi, Shlomo, Dana, Alon, Ruth, Yuval,
                         Keren, Eitan, Hila, Ido, Boaz, Tali, Erez, Efrat]
                  description: >
                    The persona the agent speaks in. Sent on its own it still works exactly as before: a voice
                    belongs to one family, so naming one chooses the family. There is no separate engine field,
                    and `engine` / `engine_voice` are rejected if you send them.

                    `Keren, Eitan, Hila, Ido, Boaz, Tali, Erez, Efrat` are the voices of `gpt-live`, available
                    to every workspace. Agents on these voices handle their own turn-taking and
                    expressiveness, so `temperature`, `vad_stop_secs`, `vad_start_secs` and
                    `vad_confidence` are rejected on them, and they cannot be used on a `type='flow'`
                    agent. Any other name returns `400` listing every voice you may use.

                    Naming a voice from the other family MOVES the agent onto it, and a pinned Gemini `model`
                    is dropped on the way (the agent is then `gpt-live`; moving back leaves it automatic).
                    The move is lossless for the voice in both directions: the Gemini voice is kept aside
                    while the agent is on `gpt-live`, so switching back restores it.
                model:
                  type: string
                  nullable: true
                  enum: [gemini-3.1-flash-live, gemini-3.8-live, gpt-live]
                  description: >
                    Choose the voice model. `gemini-3.1-flash-live` or `gemini-3.8-live` pins a Gemini model,
                    null returns the agent to automatic, and `gpt-live` selects GPT Live.

                    Each model speaks with its own family of voices, and the two Gemini models share one list.
                    Changing between `gemini-3.1-flash-live`, `gemini-3.8-live` and automatic keeps the voice.
                    Moving to or from `gpt-live` also changes the voice, so send `voice` with it, one of that
                    model's voices; `model` alone across the two families is `400` and lists the voices to
                    choose from. A `model` and a `voice` of different families are `400` too. Settings that
                    `gpt-live` does not read (`temperature`, `vad_*`) are refused with it, and it cannot be
                    used on a `type='flow'` agent.
                background_sound:
                  type: string
                  nullable: true
                  enum: [call_center, open_office, cafe, outdoor]
                  description: Ambient background sound mixed under the agent's voice during calls. Null means silent (default).
                background_sound_volume:
                  type: number
                  minimum: 0.0
                  maximum: 0.6
                  default: 0.3
                  description: Volume of the background sound, 0.0–0.6. Capped to protect turn-taking.
                language: { type: string, enum: [he, en, ar, ru, fr, es, de, it, pt, nl, tr, pl, uk, hi, ja, ko, zh, multi, he-IL, iw, en-US, en-GB], description: "One of the call languages (he, en, ar, ru, fr, es, de, it, pt, nl, tr, pl, uk, hi, ja, ko, zh), or multi for a multilingual agent that answers in the caller's language. he-IL and iw are stored as he, en-US and en-GB as en." }
                temperature: { type: number, minimum: 0, maximum: 2, description: "How varied the agent's wording is. On the Gemini voices a value below 0.3 is stored and returned as you sent it, and the agent speaks as if it were 0.3: lower values sometimes made a call open on a word or two and a pause. The expressive voices do not take it." }
                greeting_message: { type: string, nullable: true, description: "The line the agent opens the call with when agent_speaks_first is true, said word for word (a second-family voice can still word it slightly differently), with {{FirstName}} filled in from the call's variables or the lead's name, or left out with the space before it. Send null to clear it. Random variations: {{Hi|Hello|Hey}} (two or more options separated by |) says one option, picked once per call; see [Random variations](/api-reference/agents/create#random-variations). A workflow agent's line may read a Before-call step's result, {{before.<step_id>.<field>|<fallback>}}; see [Opening line from a Before step](/api-reference/workflows/greeting-from-before)." }
                agent_speaks_first: { type: boolean }
                is_active: { type: boolean }
                lead_memory_enabled: { type: boolean }
                noise_cancellation_enabled: { type: boolean }
                extraction_parameters: { $ref: '#/components/schemas/Agent/properties/extraction_parameters' }
                vad_stop_secs: { type: number, minimum: 0.05, maximum: 5.0 }
                vad_start_secs: { type: number, minimum: 0.05, maximum: 2.0 }
                vad_confidence: { type: number, minimum: 0.0, maximum: 1.0 }
                silence_timeout_secs: { type: number, minimum: 10, maximum: 900 }
                idle_reminder_count: { $ref: '#/components/schemas/Agent/properties/idle_reminder_count' }
                idle_reminder_text: { $ref: '#/components/schemas/Agent/properties/idle_reminder_text' }
                max_continuous_speech_secs: { type: number, minimum: 0, maximum: 300 }
                max_call_duration_secs: { type: number, minimum: 0, maximum: 3600 }
                webhook_url: { type: string, format: uri, nullable: true }
                webhook_events:
                  type: array
                  items:
                    type: string
                    enum: [call.started, call.answered, call.ended, call.failed, call.no_answer, call.dnc_blocked, transcript.ready, call.analyzed]
                webhook_headers:
                  type: object
                  nullable: true
                  additionalProperties: { type: string }
                  description: |
                    Legacy agents only. Write-only: it replaces the stored headers and is never returned; the
                    response carries `configured_webhook_header_names`. Leave it out to keep the stored headers.
                    Custom HTTP headers sent with every webhook delivery for this agent (e.g. an auth token).
                    Flat name → string-value map, or null to clear. Headers that would override request routing
                    or HTTP framing (Host, Content-Length, Transfer-Encoding, Connection, Expect, Keep-Alive,
                    TE, Trailer, Upgrade, Proxy-*) are rejected with 400.
                  example: { "Authorization": "Bearer sk_live_…", "X-Source": "yappr" }
      responses:
        "200":
          description: The updated agent. A workflow agent answers with the workflow Agent object, without system_prompt, flow_config, webhook_url, webhook_events, webhook_headers or tools. A legacy agent answers with its fields, webhook header names in configured_webhook_header_names and never a value.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Agent" }
        "400":
          description: |
            Validation error. An unknown or retired field, `engine`, `engine_voice` or `live_model` is
            `WORKFLOW_SETTINGS_REQUEST_INVALID`, naming the field. A `model` that is not one of the three
            ids, that crosses voice families without a voice, or that disagrees with the `voice` sent
            beside it is `WORKFLOW_SETTINGS_MODEL_INVALID`, and the message lists what to send. Same two shapes as `POST /agents`:
              - General request validation → `Error`.
              - Flow graph validation failure on a `flow_config` payload → `FlowInvalidError` shape (see
                `error: "FLOW_INVALID"` with an `issues[]` array of `FlowValidationIssue`).
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/Error"
                  - $ref: "#/components/schemas/FlowInvalidError"
        '403': { description: Original settings authority was revoked or expired., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'Agent not found, foreign-company or archived.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: WORKFLOW_SETTINGS_CONFLICT; reload and review the newer settings before a deliberate retry., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'An ordinary setting with a value it cannot hold (WORKFLOW_SETTINGS_REQUEST_INVALID, WORKFLOW_SETTINGS_UNSUPPORTED). No document or settings were changed. A field a workflow agent has no place for - webhook_url, webhook_events, webhook_headers, system_prompt, flow_config, tools, or any field an agent does not have - is 400 WORKFLOW_SETTINGS_REQUEST_INVALID (it was 422), with an issues[] entry per field at fault, each with code field_unknown, a JSON pointer such as /webhook_url and the place that field moved to.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Settings write or response unavailable. Read saved settings before retrying an uncertain write; do not silently overwrite newer data., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
    delete:
      summary: Remove agent
      operationId: deleteAgent
      description: Archives the agent, hides it from ordinary lists and blocks new calls; history is retained and running calls are not aborted. PATCH cannot clear the archive. Use PATCH is_active=false for reversible deactivation.
      tags: [Agents]
      responses:
        "200":
          description: >
            Agent archived: archived is true and archived_at says when (null on the rare occasion it could
            not be read back). It used to answer is_active false, which read like a switch-off. An agent from
            before the workflow engine is switched off rather than archived and answers archived false with
            is_active false; it stays listed.
          content:
            application/json:
              schema:
                type: object
                required: [success, id, archived]
                properties:
                  success: { type: boolean, example: true }
                  id: { type: string, format: uuid }
                  archived: { type: boolean, example: true }
                  archived_at: { type: string, format: date-time, nullable: true, example: "2026-10-02T08:00:00.123456+00:00" }
                  is_active: { type: boolean, example: false, description: "Only on an agent from before the workflow engine, which is switched off rather than archived." }
        "400":
          description: "AGENTS_QUERY_INVALID - a query parameter; the delete reads none (?bogus=1 used to archive the agent). The message names it, and the agent is unchanged. Every write refuses a query parameter it does not read."
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "404":
          description: AGENT_NOT_FOUND - the agent is not in this workspace, or is already archived. A second delete of the same agent answers this, as GET and PATCH do; it used to answer 200 and archive it again.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "503":
          description: WORKFLOW_STORAGE_UNAVAILABLE - the archive could not be confirmed, so it may not have gone through. Send the same delete again; a 404 AGENT_NOT_FOUND on that retry means the first delete archived the agent. An archive that went through and is read back answers 200.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /tools:
    get:
      summary: List tools
      description: Requires tools:read. Every row, on both lists, is the same object that tool's own GET /tools/{id} answers with - a workflow-owned tool carries workflow_version and its workflow object, a legacy row carries type and config. Use workflow=true for the canonical revision catalog; its cursor is opaque, signed, and bound to the list it was cut for - workspace, environment, limit, status and name - so a cursor from any other list is refused with 422 WORKFLOW_TOOL_CURSOR_INVALID. Archived workflow tools are omitted from both lists unless status=archived asks for exactly them, each in the short form GET /tools/{id} gives an archived tool (with archived_at). The default mixed list remains a temporary legacy migration boundary.
      operationId: listTools
      tags: [Tools]
      parameters:
        - in: header
          name: x-company-id
          schema: { type: string, format: uuid }
          description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH."
        - in: query
          name: workflow
          schema: { type: boolean }
          description: Select canonical tools. Response is data plus next_cursor, not offset pagination.
        - in: query
          name: cursor
          schema: { type: string }
          description: Opaque, signed continuation for workflow=true. Send it back unchanged with the same limit (1–50), status and name; a cursor from any other list, or one that was edited, is refused with 422 WORKFLOW_TOOL_CURSOR_INVALID.
        - in: query
          name: status
          schema: { type: string, enum: [failed, archived, all] }
          description: "archived lists only the tools archived with DELETE /tools/{id}, each in its short form with archived_at, to find one to restore with POST /tools/{id}/restore - on workflow=true by cursor, most recently archived first, narrowed by name if sent, on the mixed list by limit/offset, where it is the only value (failed or all there, or status with agent_id, is 400 TOOLS_QUERY_INVALID). The rest is for workflow=true. Omitted, the page leaves out tools whose creation failed - workflow.status failed with workflow.current null; failed returns only those; all returns everything that is not archived. A tool whose later edit failed keeps its promoted head and stays on the default list. Any other value is refused with 422 WORKFLOW_TOOL_REQUEST_INVALID. With failed, the failed creations are read directly, so a page holds up to limit of them. Omitted or all, filtering happens after the page is read, so a page can be shorter than limit while next_cursor still says there is more."
        - in: query
          name: agent_id
          schema: { type: string, format: uuid }
          description: "Filter tools attached to a specific agent. When provided, also returns `execution_order` and `config_override` per tool."
        - in: query
          name: name
          schema: { type: string, minLength: 1, maxLength: 200 }
          description: "For the default list and agent_id. Only tools whose name contains this text, case-insensitively, anywhere in the name — newest first, with pagination.total counting the matches. Every character matches itself: %, _ and * are not wildcards. Leading and trailing spaces are ignored. On workflow=true it narrows only status=archived; the rest of that catalog has no name filter, so name with workflow=true and any other status is refused with 400 TOOLS_QUERY_INVALID rather than ignored."
        - in: query
          name: limit
          schema: { type: integer, default: 50, maximum: 100 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: List of tools
          content:
            application/json:
              schema:
                type: object
                properties:
                  next_cursor: { type: [string, 'null'], description: Canonical workflow list continuation. }
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Tool" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean }
        "400":
          description: >
            TOOLS_QUERY_INVALID — a parameter this list does not read (`search`, `q`, or one that
            belongs to the other list: `cursor` is for `workflow=true`, `agent_id`
            and `offset` are for the mixed list), a `status` other than `archived` on the mixed
            list or `status` with `agent_id`, a parameter sent twice or with no value, a
            `name` longer than 200 characters, with a control character, or with `workflow=true` but without `status=archived`,
            a `workflow` other than `true` / `false`, or a `limit` / `offset` that is not a whole number.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "422":
          description: >
            WORKFLOW_TOOL_REQUEST_INVALID — `status` was not `failed`, `archived` or `all`, or `limit`
            was outside 1–50 on the canonical list. WORKFLOW_TOOL_CURSOR_INVALID — a cursor
            this list did not issue for this query: another status, name, limit, workspace or
            environment, an edited cursor, or one handed out before 2 October 2026. Each names the parameter in `issues[0].path`.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

    post:
      summary: Create tool
      description: >
        Requires tools:create. Supply workflow for the canonical HTTP/app/transfer tool variant and an Idempotency-Key header.
        Identity and revision numbers are server-owned. Creates never execute the action.
        A 202 response is durable acceptance: poll GET /tools/{id} until current or a terminal failure.
        Retrying the unchanged body/key never creates a second tool; changing the accepted body conflicts.
        Legacy type/config bodies and their camelCase normalization - of the tool name as well as its payload
        parameter names - remain a temporary migration boundary only; a body without `type` is read as the
        workflow variant, so what a tool does always belongs under `workflow`.
      operationId: createTool
      tags: [Tools]
      parameters:
        - in: header
          name: Idempotency-Key
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{16,128}$' }
          description: Required for the workflow variant. Preserve the same key and accepted body after a lost response.
        - in: header
          name: x-company-id
          schema: { type: string, format: uuid }
          description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              oneOf:
                - $ref: '#/components/schemas/WorkflowToolCreate'
                - required: [type, config]
                  not: { required: [workflow] }
              properties:
                name:
                  type: string
                  example: "capture_lead"
                  description: >-
                    Stored verbatim for the workflow variant. A legacy type/config body has its name normalized
                    to camelCase before it is stored - "critic-ron-notify-noshow" is created as
                    "criticRonNotifyNoshow" - so read the stored name back from the response rather than
                    assuming the one you sent.
                description:
                  type: string
                  description: "Required and non-empty when type is webhook; optional for function tools."
                type: { type: string, enum: [webhook, function] }
                idempotency_key: { type: string }
                config:
                  type: object
                  description: "Webhook configuration is validated as described below; function-tool configuration is stored as an arbitrary JSON object."
              allOf:
                - if:
                    properties:
                      type: { const: webhook }
                    required: [type]
                  then:
                    required: [description]
                    properties:
                      description:
                        type: string
                        pattern: '\S'
                      config:
                        type: object
                        required: [url, method]
                        properties:
                          url:
                            type: string
                            format: uri
                            description: "Final public HTTP(S) endpoint. Local and non-public targets are rejected when saved, including a hostname whose DNS answers include one (127.0.0.1.nip.io); dispatch reads the DNS answers again, rejects non-public or mixed ones and does not follow redirects."
                          method: { type: string, enum: [GET, POST, PUT, PATCH, DELETE] }
                          headers:
                            type: object
                            additionalProperties: { type: string }
                            description: "String-valued request headers. Routing/framing headers such as Host, Content-Length, Transfer-Encoding, Connection, Expect, Keep-Alive, Proxy-*, TE, Trailer, and Upgrade are rejected."
                          timeout_seconds: { type: integer, minimum: 1, maximum: 60, default: 30 }
                          payload_config:
                            type: object
                            properties:
                              include_standard_metadata: { type: boolean, default: true }
                              static_parameters:
                                type: array
                                items:
                                  type: object
                                  required: [name, value]
                                  properties:
                                    name: { type: string, description: "Normalized to camelCase" }
                                    value: { type: string }
                              extraction_parameters:
                                type: array
                                items:
                                  $ref: "#/components/schemas/ToolExtractionParameter"
      responses:
        "200":
          description: Idempotent replay of an already-materialized tool.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowTool' }
        "202":
          description: >-
            Queued, not built yet - the build service could not take the create right now, or it
            was still building after the few seconds the request waits for it. Poll GET /tools/{id}
            until workflow.status is current (or failed). A create that is built while the request
            waits is 201, never 202. Carries warnings[] when the name is already in use by another
            tool here.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowTool' }
        "400":
          description: >-
            WORKFLOW_TOOL_IDEMPOTENCY_REQUIRED - a missing or invalid Idempotency-Key. Or
            WORKFLOW_TOOL_REFERENCE_INVALID - an app tool whose metadata_id names no action, or whose
            connection_id names no account in this workspace; issues[] carries one entry per field at fault
            (/workflow/metadata_id, /workflow/connection_id) and nothing is written.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }
        "403": { description: "Original author is no longer authorized, or WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API key belongs to.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "409": { description: The accepted key belongs to a different body. Deliberately start a new change; do not retry modified content with this key., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "422": { description: 'Invalid request or durable materialization failure. A body Yappr can read but not accept is WORKFLOW_TOOL_REQUEST_INVALID with an issues[] entry per field at fault, each carrying a JSON pointer such as /workflow/configuration/url or /workflow/effect, and no tool is created. Every field at fault is named in one answer, and an HTTP configuration.url on localhost, a private network, a link-local, a cloud-metadata or another reserved address is refused the same way with issues[].code url_not_public (so is a hostname whose DNS answers include one, such as 127.0.0.1.nip.io), and a host written as a shortened, octal or hexadecimal number (1.2.3) with url_host_form. What can only be found while materializing - an ineligible action, an account that exists but is not connected, a schema the builder rejects - answers WORKFLOW_TOOL_NOT_BUILT: the safe WorkflowTool at workflow.status=failed with its workflow.error_code, plus error (what to do) and issues[0] naming the field (/workflow/connection_id, /workflow/fixed_inputs, /workflow/metadata_id or /workflow), whose code is that same error_code. Such a tool is fixed with PATCH /tools/{id} (send the whole tool again, no expected head) or removed with DELETE /tools/{id}.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "503": { description: Storage or control unavailable. Preserve the same key and unchanged body when retrying., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "201":
          description: >-
            Tool created and built: it has a current revision and can be bound now. Every create
            the build service takes answers this, after waiting a few seconds at most for the build.
            Names are not unique here: when another tool in this workspace already
            carries the same name the tool is still created, and the response carries a warnings[]
            entry naming it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Tool" }

  /tools/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get tool
      description: Requires tools:read. Workflow-owned tools return safe current/candidate schemas and durable change/promotion status. URL queries, userinfo, fragments and header values remain private. GET does not execute actions or start another change. An archived workflow tool answers its short form - id, name, description, workflow_version, is_active false, created_at, updated_at, archived true, archived_at and workflow.kind - so a lost tool can be found and restored with POST /tools/{id}/restore.
      operationId: getTool
      tags: [Tools]
      responses:
        "200":
          description: Tool details
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Tool" }
        "400":
          description: "TOOLS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    patch:
      summary: Update tool
      description: Requires tools:update. For workflow tools submit a WorkflowToolUpdate with the current head ID/generation and Idempotency-Key, carrying the fields below that a change must carry plus the ones being changed. The old head stays active until every affected follow-current workflow validates. Explicitly pinned revisions and accepted runs do not change. Each compiler case has a 1 MiB technical input budget, not a tool-fanout cap. A PATCH changes what it sends and nothing else - every field the request leaves out keeps the value the tool already has - description, effect, timeout_ms, configuration.method, include_call_context, an app tool's fixed_inputs and a transfer tool's announce_transfer/announce_message and its own transfer code (transfer_method, pbx_feature_code, pbx_feature_code_hangup_after_secs; transfer_method auto removes the code). A description sent as "" clears it on purpose. A change that sends workflow still has to carry name, workflow.kind and the two revision tokens, plus what its kind is built from - an HTTP tool's input_schema, output_schema and configuration ({} keeps the endpoint), an app tool's metadata_id and connection_id, a transfer tool's destination - or it is a 422 naming the missing field. The one exception - to change only an HTTP tool's description (or name), leave workflow out altogether, with the two revision tokens - the tool keeps what it does, and a name left out keeps its value; it still answers 202 and makes a new revision, like any change; description is top-level, and one sent under workflow is a 422 at /workflow/description that says so. Omitted HTTP URL/headers preserve their private values, and inside a submitted headers object a null value keeps the header already stored under that exact name. A tool whose creation failed (workflow.status failed, workflow.current null) has no head - send a WorkflowToolRetry, the whole tool again with neither expected-head field, and it is built under the same id; this needs tools:create as well as tools:update.
      operationId: updateTool
      tags: [Tools]
      parameters:
        - in: header
          name: Idempotency-Key
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{16,128}$' }
          description: Required for workflow tools; exact same-body retry only.
      requestBody:
        content:
          application/json:
            schema:
              type: object
              oneOf:
                - $ref: '#/components/schemas/WorkflowToolUpdate'
                - $ref: '#/components/schemas/WorkflowToolRetry'
                - not: { required: [workflow] }
              properties:
                name:
                  type: string
                  description: >-
                    A legacy type/config body has its name normalized to camelCase before it is stored, the
                    same way POST /tools does. Read the stored name back from the response.
                description: { type: string }
                config: { type: object }
                is_active: { type: boolean }
      responses:
        "202":
          description: >-
            The change is accepted but is not the tool's current revision yet - `workflow.status` is
            `accepted`, `claimed`, `queued`, `compiling` or `ready`, and the new revision is under
            `workflow.candidate` while `workflow.current` is still the old one. Poll GET /tools/{id}
            until `workflow.status` is `current`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowTool' }
        "403": { description: Original author is no longer authorized., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "400": { description: 'Missing or invalid Idempotency-Key, or WORKFLOW_TOOL_REFERENCE_INVALID - an app tool naming an action or account that does not exist (issues[] names the field; nothing is written).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "404": { description: "WORKFLOW_NOT_FOUND - the tool is not in this workspace. WORKFLOW_TOOL_ARCHIVED - the tool is archived, answered before the body is read; nothing is saved. Restore it with POST /tools/{id}/restore, re-read it with GET /tools/{id}, then send the change.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "409": { description: 'Head/key conflict, or a failed creation that is being built again right now. Reload before a deliberate new change. INTEGRATION_ACTION_MANAGED - the tool runs an action for an integration (GET /tools/{id} carries `integration`) and belongs to it; nothing is saved. Change which actions an agent uses with PATCH /agents/{id}/integrations/{integration_id}; the integration rebuilds the tool itself.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "422": { description: 'Invalid candidate. No partial promotion is applied. WORKFLOW_TOOL_REQUEST_INVALID names every field at fault in issues[]; sending an expected-head field for a tool whose creation failed is refused here, naming the field. A tool whose creation failed and still cannot be built answers WORKFLOW_TOOL_NOT_BUILT, as on create.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "503": { description: Storage unavailable; preserve the accepted request key., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "200":
          description: Updated tool - for a workflow tool, the change is its current revision.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Tool" }
    delete:
      summary: Archive tool
      description: Requires tools:update. Workflow-owned tools are archived and unavailable for new authoring selections and test admission; immutable revisions, accepted runs and execution history remain. A tool whose creation failed is removed the same way and then answers 404 on GET. Existing legacy tools keep their temporary deactivation semantics.
      operationId: deleteTool
      tags: [Tools]
      responses:
        "200":
          description: |
            Tool archived. Archiving is idempotent: a tool that is already archived answers
            `200` with the same body and keeps the moment it was first archived, so a lost
            response is safe to repeat.
          content:
            application/json:
              schema:
                type: object
                properties:
                  archived: { type: boolean, description: True for an archived workflow tool. }
                  archived_at: { type: string, format: date-time, description: 'When a workflow tool was first archived. Repeating the archive answers the same moment.' }
                  warnings:
                    type: array
                    description: 'Present when agents still bind the tool. A version they already have live keeps running it on calls until they are published again, and they refuse to publish or duplicate (WORKFLOW_REFERENCE_INVALID) until the tool is restored with POST /tools/{id}/restore or the steps are removed.'
                    items:
                      type: object
                      properties:
                        code: { type: string, enum: [tool_in_use] }
                        message: { type: string }
                        agents:
                          type: array
                          items:
                            type: object
                            properties:
                              id: { type: string, format: uuid }
                              name: { type: string }
                  success: { type: boolean }
                  id: { type: string, format: uuid }
                  is_active: { type: boolean, example: false  }
        "401": { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "404":
          description: |
            `WORKFLOW_NOT_FOUND` — the tool is not in this workspace. An already-archived
            tool is not a `404`; it answers `200` again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }
        "409":
          description: |
            `WORKFLOW_TOOL_CONFLICT` — a creation that is still being built. Wait for
            `GET /tools/{id}` to settle, then remove it.

            `INTEGRATION_ACTION_MANAGED` — the tool runs an action for an integration
            (`GET /tools/{id}` carries `integration`) and agents still use it. Nothing is
            archived. Remove the integration, or that action, from those agents with
            `DELETE` or `PATCH /agents/{id}/integrations/{integration_id}` first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }
        "503":
          description: |
            `WORKFLOW_STORAGE_UNAVAILABLE` — temporary. Retry the same request; archiving
            the same tool twice is harmless.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }

  /tools/{id}/restore:
    post:
      summary: Restore tool
      description: Requires tools:update. Puts an archived workflow tool back, switched on, exactly as it was archived - its revisions, bindings and history were kept. Agents whose steps bind it can be published and duplicated again. Restoring a tool that is not archived is harmless and answers restored=false. Takes no body - send none, or {}; any field is refused by name with 422 WORKFLOW_TOOL_REQUEST_INVALID.
      operationId: restoreTool
      tags: [Tools]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: The tool, as GET /tools/{id} answers with it, and whether it had been archived.
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Tool" }
                  - type: object
                    properties:
                      restored: { type: boolean, description: True when the tool was archived and is now back; false when it was not archived. }
        "401": { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "404":
          description: '`WORKFLOW_NOT_FOUND` - no archived tool with this id in this workspace, so nothing to restore. The message points at GET /tools?workflow=true&status=archived, which lists the archived tools with their ids.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }
        "409":
          description: '`WORKFLOW_TOOL_NOT_READY` - the tool''s creation never built (workflow.status failed, workflow.current null), so it was never archived and there is nothing to restore. The message names its error_code: fix it and send the whole tool again with PATCH /tools/{id}, or remove it with DELETE /tools/{id}. A creation still being built answers the same; read it again with GET /tools/{id}.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }
        "422":
          description: '`WORKFLOW_TOOL_REQUEST_INVALID` - the request carried a body, and the route takes none. The message names the fields to remove.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }
        "503":
          description: '`WORKFLOW_TOOL_STORAGE_UNAVAILABLE` - temporary. Send the same request again.'
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }

  /tools/{id}/schema:
    get:
      operationId: getWorkflowToolSchema
      summary: Get current tool input and output schemas
      description: Requires tools:read. Safe full public schemas for the exact current revision; fixed app fields are composed privately before raw validation and cannot be supplied again. A tool from before the workflow engine (a legacy row, with type and config) has no revisions and answers the tool itself, as GET /tools/{id} does.
      tags: [Tools]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Exact current revision schemas.
          content:
            application/json:
              schema:
                type: object
                properties:
                  tool_id: { type: string, format: uuid }
                  revision_id: { type: string, format: uuid }
                  input_schema: { type: object, additionalProperties: true }
                  output_schema: { type: object, additionalProperties: true }
        "400":
          description: "TOOLS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '404': { description: "WORKFLOW_NOT_FOUND — the tool is not in this workspace. WORKFLOW_TOOL_ARCHIVED — it is archived: it has no current schema until it is restored with POST /tools/{id}/restore, which the message names.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409':
          description: |
            `WORKFLOW_TOOL_NOT_READY` — the tool was saved but its current version is still
            being prepared, so there is no schema to return yet. Poll `GET /tools/{id}` until
            `workflow.current` is set, then read the schema again. Never guess the schema.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }
        '503':
          description: "WORKFLOW_STORAGE_UNAVAILABLE — temporary; retry the same request."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }

  /tools/{id}/bindings:
    get:
      operationId: listWorkflowToolBindings
      summary: List the agents bound to a tool
      description: |
        Requires tools:read. Answers "who is using this tool" — and, after a credential
        rotation, "who still holds the old one". One row per agent binding, from the agent's
        saved draft and from the revision it publishes calls from. Header values are never
        part of this answer. A tool from before the workflow engine (a legacy row, with type and
        config) answers the tool itself, as GET /tools/{id} does.
      tags: [Tools]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The bindings that reference this tool.
          content:
            application/json:
              schema:
                type: object
                properties:
                  tool_id: { type: string, format: uuid }
                  head_revision_id:
                    type: string
                    format: uuid
                    nullable: true
                    description: The tool's current revision — what a follow-current binding resolves to.
                  total: { type: integer, description: "Every binding that references this tool, including any past the page." }
                  has_more: { type: boolean }
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        agent_id: { type: string, format: uuid }
                        agent_name: { type: string }
                        environment: { type: string, enum: [local, testing, production], description: "The Yappr deployment the binding belongs to. The hosted API answers production." }
                        binding_id: { type: string }
                        tool_revision_policy:
                          type: string
                          enum: [follow_current, pinned]
                          description: follow_current moves with the tool; pinned stays on the revision it names.
                        tool_revision_id:
                          type: string
                          format: uuid
                          description: The revision the binding names in the document.
                        effective_revision_id:
                          type: string
                          format: uuid
                          nullable: true
                          description: The revision calls actually use — the head for follow_current, the named one for pinned.
                        rotation_reaches:
                          type: boolean
                          description: false means this binding still carries the header values stored on an older revision.
                        published: { type: boolean, description: This binding is in the revision the agent publishes calls from. }
                        draft: { type: boolean, description: This binding is in the agent's saved draft. }
        "400":
          description: "TOOLS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '404': { description: "WORKFLOW_NOT_FOUND — the tool is not in this workspace. An archived tool is answered like any other: it keeps its bindings, so this lists the agents whose steps still name it.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503':
          description: "WORKFLOW_TOOL_STORAGE_UNAVAILABLE — temporary; retry the same request."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/WorkflowError" }

  /tools/{id}/workflow-revisions:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: header, name: x-company-id, schema: { type: string, format: uuid }, description: "Explicit active workspace. Optional; when sent it must be the API key's own workspace — any other value is refused with 403 WORKSPACE_MISMATCH." }
    get:
      operationId: listWorkflowToolRevisions
      summary: List a tool's contract revisions
      description: >
        Requires tools:read. Returns the 100 most recent contract revisions of one saved tool,
        newest first. A revision records the input and output schemas the agent is held to, and
        where the tool may run. Private endpoint configuration is never returned.
      tags: [Tools]
      responses:
        '200':
          description: Contract revisions, newest first.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowToolContractRevisionList' }
        "400":
          description: "WORKFLOW_REQUEST_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404':
          description: WORKFLOW_NOT_FOUND — no such tool in this workspace. WORKFLOW_TOOL_ARCHIVED — it is archived; its revisions are not read until it is restored with POST /tools/{id}/restore, which the message names.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }
        '503':
          description: WORKFLOW_STORAGE_UNAVAILABLE — temporary; retry the same request.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }
    post:
      operationId: createWorkflowToolRevision
      summary: Add a contract revision to a tool
      description: >
        Requires tools:update. Adds one immutable revision to a saved tool that was created
        through the earlier tool endpoints, so it can be used inside a workflow. Send the
        revision number you last read as expected_revision (null when the tool has none yet);
        if another writer has added a revision since, nothing is written. Name, description and
        private endpoint configuration come from the saved tool and are refused if sent.
        Transfer tools always come back restricted to a live call on a phone, whatever the
        request asked for. Previously published workflows keep the exact revision they pinned.
      tags: [Tools]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WorkflowToolContractRevisionCreate' }
      responses:
        '201':
          description: The new revision.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowToolContractRevision' }
        '400':
          description: WORKFLOW_REQUEST_INVALID — the body has an unexpected property, a missing or non-object input_schema/output_schema, an include_call_context that is not true or false, or an expected_revision that is neither null nor a positive whole number. For an unexpected property, a missing or non-object contract, or a bad expected_revision, issues[] names the field by path (/<field>, /contract, /expected_revision).
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WORKSPACE_MISMATCH — `x-company-id` named a workspace other than the one this API
            key belongs to.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404':
          description: WORKFLOW_NOT_FOUND — no such tool in this workspace. WORKFLOW_TOOL_ARCHIVED — it is archived, and takes no revision until it is restored with POST /tools/{id}/restore, which the message names.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }
        '409':
          description: WORKFLOW_CONFLICT — expected_revision is not the tool's current revision. Re-read the list and send the highest revision you see.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }
        '422':
          description: WORKFLOW_TOOL_IMPORT_REQUIRED — this tool's type cannot take a contract revision. Only tools that call your own endpoint, or transfer a call, can.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }
        '503':
          description: WORKFLOW_STORAGE_UNAVAILABLE — temporary; retry the same request.
          content: { application/json: { schema: { $ref: '#/components/schemas/WorkflowError' } } }

  /tools/attach:
    post:
      summary: Attach tool to agent
      operationId: attachTool
      tags: [Tools]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [agent_id, tool_id]
              properties:
                agent_id: { type: string, format: uuid }
                tool_id: { type: string, format: uuid }
                execution_order: { type: integer, default: 0 }
                config_override: { type: object, description: "Per-attachment config overrides (merges with tool's base config)" }
      responses:
        "201":
          description: Tool attached
        "400":
          description: TOOL_ATTACHMENT_REQUEST_INVALID — a body field other than agent_id, tool_id, execution_order and config_override, a query parameter, a missing agent_id or tool_id, an execution_order that is not a whole number of 0 or more, or a body that is not JSON. The message names what to fix.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401": { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "404": { description: The agent or the tool is not in this workspace. Attaching checks both., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "409":
          description: |
            The `code` field identifies the failure:
            - `WORKFLOW_TOOL_OWNER_REQUIRED` — the agent or the tool is a workflow one. Workflow
              agents choose their tools inside the workflow itself, so this endpoint does not
              apply. Edit the workflow instead.
            - `WORKFLOW_AGENT_BUSY` — the agent is being changed right now. Reload it and retry.
            - `WORKFLOW_BINDINGS_REQUIRED` — the agent has moved to workflow tool selection.
              Edit the workflow instead.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /tools/detach:
    post:
      summary: Detach tool from agent
      operationId: detachTool
      tags: [Tools]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [agent_id, tool_id]
              properties:
                agent_id: { type: string, format: uuid }
                tool_id: { type: string, format: uuid }
      responses:
        "200":
          description: |
            Tool detached. Detaching checks the agent only, so a `tool_id` that is not attached —
            or does not exist — also answers `200`. Read the agent's tools to confirm the result.
        "400":
          description: TOOL_ATTACHMENT_REQUEST_INVALID — a body field other than agent_id and tool_id, a query parameter, a missing agent_id or tool_id, or a body that is not JSON. The message names what to fix.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401": { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "404": { description: The agent is not in this workspace. The tool is not checked here., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "409":
          description: |
            The `code` field identifies the failure:
            - `WORKFLOW_TOOL_OWNER_REQUIRED` — the agent is a workflow one. Workflow
              agents choose their tools inside the workflow itself, so this endpoint does not
              apply. Edit the workflow instead.
            - `WORKFLOW_AGENT_BUSY` — the agent is being changed right now. Reload it and retry.
            - `WORKFLOW_BINDINGS_REQUIRED` — the agent has moved to workflow tool selection.
              Edit the workflow instead.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /tools/{id}/test:
    post:
      summary: Test a saved tool
      description: |
        Requires `tools:update`. Workflow-owned tools accept a WorkflowToolTestRequest
        and mandatory Idempotency-Key, returning 202. The request freezes one exact
        revision, inputs, policy and original author in the shared execution journal.
        Mock is the default; only policy=allowlist with allowed_binding_ids=["test_tool"]
        permits the fixed binding's real effect. `test_tool` is a fixed sentinel, not
        one of your workflow's binding ids: a saved-tool test has exactly one binding
        and that is its name. Any other value is refused 422 WORKFLOW_TOOL_TEST_INVALID
        with issues[0].path "/allowed_binding_ids", and so is an empty allowlist, which
        grants nothing. Unless revision_id pins another revision, inputs and mock_output
        are read against the tool's current schemas before the test is accepted: a
        missing required input, an unknown field, a wrong type or a value outside its
        enum is 422 WORKFLOW_TOOL_TEST_INVALID with issues[0].path at that value
        (/inputs/order_id), not a 202 that settles failed as tool_test_validation_failed.
        A field a test does not take, a missing or unknown phase or channel, inputs that is
        missing or not an object, and a revision_id that is not an id are 422
        WORKFLOW_TOOL_TEST_INVALID with issues[0].path naming it (/colour, /phase, /channel,
        /inputs, /revision_id).
        Standalone transfers are mock-only.
        No fake call/agent is created. Poll the exact Tools-scoped test endpoint.
        A lost response must be retried with the same body/key; changed content is 409.
        Replaying that key as a different original user/API key returns 404 without
        revealing the existing test. Other currently authorized workspace members
        may read or cancel with the appropriate Tools scope.
        An unknown outcome requires reconciliation, never automatic redispatch.
        503 WORKFLOW_TOOL_TEST_UNAVAILABLE means tool testing is temporarily
        unavailable; retry the same request.
        A tool whose creation failed has no revision to test: 409 WORKFLOW_TOOL_NOT_READY,
        with the failure named in `error`. Fix it with PATCH /tools/{id} first.

        **Temporary legacy webhook migration boundary only:** sends one request to the saved tool's
        configured webhook and returns the exact payload plus a sanitized preview
        of the downstream response. The test follows the same payload contract
        and HTTP semantics as a live call, including the configured method and
        `timeout_seconds`.

        Omitted extraction arguments receive `<test_name>` placeholders. Supplied
        `arguments` may contain only names declared in the tool's effective
        `payload_config.extraction_parameters`. When `agent_id` is supplied, that
        agent must belong to the API key's company and supplies the standard
        `agent_id` / `agent_name` fields.

        **Production tool-webhook payload shape** (this is what your webhook URL receives when the agent actually invokes the tool during a call, when `config.payload_config.include_standard_metadata` is `true`, the default):

        ```json
        {
          "company_id": "uuid",
          "agent_id": "uuid",
          "agent_name": "string",
          "call_id": "uuid",
          "call_direction": "outbound" | "inbound" | "web_call",
          "caller_number": "+972...",
          "callee_number": "+972...",
          "call_metadata":  { "...": "exactly what you passed at POST /calls body.metadata" },
          "call_variables": { "LeadName": "...", "AppointmentDate": "..." },
          "<your_extraction_param>": "<what the AI extracted>"
        }
        ```

        - **`call_metadata`** — the object you passed at call creation. Use this to carry CRM IDs (appointment_id, contact_id, calendar_id, etc.) that tool receivers need to route updates back to the right record. The agent never sees these keys (they're not injected into the prompt).
        - **`call_variables`** — the `{{VariableName}}` values substituted into the system prompt. Useful for echoing context (e.g. Slack alerts: "Noa booked an appointment for {{LeadName}}").
        - **Both are forwarded in real-time** — your webhook doesn't need a follow-up `GET /calls/{id}` fetch.

        Setting `include_standard_metadata: false` strips the 9 standard-envelope
        fields and sends only static + extraction params. For `POST`, `PUT`,
        `PATCH`, and `DELETE`, the flat payload is sent as JSON. For `GET`, the
        same fields are encoded as query parameters (objects/arrays are compact
        JSON strings) and no request body is sent.
      operationId: testTool
      tags: [Tools]
      parameters:
        - in: header
          name: Idempotency-Key
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{16,128}$' }
          description: Required for workflow tools. Bound to workspace, tool, environment, original author and normalized accepted request.
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/WorkflowToolTestRequest'
                - $ref: '#/components/schemas/LegacyToolTestRequest'
            example:
              agent_id: "11111111-1111-1111-1111-111111111111"
              arguments:
                callerName: "Test Caller"
              context:
                call_direction: outbound
                caller_number: "+972500000000"
                callee_number: "+972500000001"
                call_metadata: { contact_id: "test-contact" }
                call_variables: { LeadName: "Test Caller" }
      responses:
        "202":
          description: Workflow tool test accepted or exact idempotent replay. Poll the returned test ID.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowToolTest' }
        "403": { description: Original test author or current workspace authorization is denied., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "409": { description: Idempotency-Key body conflict., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "422": { description: "WORKFLOW_TOOL_TEST_INVALID - invalid typed request, placement, policy, a missing or repeated key, or a query parameter (a test reads none). issues[] names every problem at once. Maximum request 512 KiB; inputs and mock output each at most 256 KiB.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "429": { description: Eight active unexpired tests already exist in this workspace., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "503": { description: Isolated test control/worker environment unavailable. Preserve the same accepted request key., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "200":
          description: Downstream endpoint returned an HTTP 2xx status
          content:
            application/json:
              schema:
                type: object
                required: [success, status_code, response_body, payload_sent, delivery_id]
                properties:
                  success: { type: boolean, const: true }
                  status_code: { type: integer }
                  response_body:
                    type: string
                    description: "Sanitized, length-capped preview of the downstream response body."
                  payload_sent:
                    type: object
                    additionalProperties: true
                    description: "Exact flat payload delivered to the tool's webhook URL."
                  delivery_id:
                    type: [string, "null"]
                    format: uuid
                    description: "Webhook-delivery log ID. Null only if logging failed; logging does not change delivery success."
        "400":
          description: "Invalid JSON, context, arguments, saved configuration, a local/non-public literal webhook target, or a host that resolves to a non-public address, checked again when the request connects (nothing is sent). On a workflow tool, 400 WORKFLOW_TOOL_TEST_INVALID is a mock test (the default policy) that sent no mock_output while the tool's output schema has required members, which a mock cannot invent: issues[0] is field_required at /mock_output and names them. With no required members no mock_output is needed; the mock answers the schema's minimal value ({} for {type: object})."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "401":
          description: Missing, unknown or expired API key. A key without tools:update is 403 INSUFFICIENT_SCOPE, naming the scope.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Tool not found, or supplied agent not found in the API key's company. WORKFLOW_TOOL_ARCHIVED - the tool is archived, so it cannot be tested; this is answered before the body is read. Restore it with POST /tools/{id}/restore first; GET /tools?workflow=true&status=archived lists the archived tools.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "502":
          description: Redirect or other downstream non-2xx status, or network failure
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ToolTestFailure" }
        "504":
          description: Webhook timed out after the configured timeout_seconds
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ToolTestFailure" }
        "500":
          description: Internal webhook-test service returned an invalid response
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /tools/{id}/tests/{test_id}:
    get:
      operationId: getWorkflowToolTest
      summary: Read a saved tool test
      description: Requires tools:read and current authorization for the exact workspace/tool/test. Returns the shared durable outcome projection; never raw credentials, URLs or private vendor evidence. A run_id is not call-history authority. This read takes no body and no Idempotency-Key, so beyond the account-wide 401 it answers only 200, 400, 403, 404 and 503.
      tags: [Tools]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
        - { in: path, name: test_id, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Safe saved test state, including unknown/manual reconciliation and late-receipt distinction.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowToolTest' }
        '400': { description: 'TOOLS_QUERY_INVALID — a query parameter was sent; this read takes none, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: "INSUFFICIENT_SCOPE — the key does not hold tools:read, and the message names it. WORKFLOW_TOOL_TEST_DENIED — this key is not authorized for the workspace that owns the test.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: "WORKFLOW_TOOL_TEST_NOT_FOUND — that tool and test pair is not in this workspace. Check both ids.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: "WORKFLOW_TOOL_TEST_UNAVAILABLE — tool testing is off for this workspace, or temporarily unavailable; retry the same request.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tools/{id}/tests/{test_id}/cancel:
    post:
      operationId: cancelWorkflowToolTest
      summary: Cancel a pending tool test
      description: Requires tools:update. Cancels future dispatch without undoing an action already started. Terminal results and receipts are retained; no retry is created. Cancelling is idempotent and takes no body, so beyond the account-wide 401 it answers only 200, 403, 404 and 503 — an already-finished test comes back as its saved state, not as a conflict.
      tags: [Tools]
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
        - { in: path, name: test_id, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Idempotent saved test state after cancellation.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WorkflowToolTest' }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: "INSUFFICIENT_SCOPE — the key does not hold tools:update, and the message names it. WORKFLOW_TOOL_TEST_DENIED — this key is not authorized for the workspace that owns the test.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: "WORKFLOW_TOOL_TEST_NOT_FOUND — that tool and test pair is not in this workspace. Check both ids. WORKFLOW_TOOL_ARCHIVED — the tool is archived, so it has no test to cancel; restore it with POST /tools/{id}/restore.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: "WORKFLOW_TOOL_TEST_UNAVAILABLE — tool testing is off for this workspace, or temporarily unavailable; retry the same request.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }

  /phone-numbers:
    get:
      summary: List owned numbers
      operationId: listPhoneNumbers
      tags: [Phone Numbers]
      responses:
        "200":
          description: List of phone numbers
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/PhoneNumber" }

        "400":
          description: "PHONE_NUMBERS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `phone_numbers:search`. API_KEY_AGENT_SCOPED — the key is
            limited to agents, and numbers belong to the whole workspace, so such a key cannot list them
            whatever its scopes.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "500":
          description: The read failed. Retry; nothing was changed.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
  /phone-numbers/search:
    post:
      summary: Search available numbers
      description: Search for available Israeli phone numbers to purchase.
      operationId: searchPhoneNumbers
      tags: [Phone Numbers]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                areaCode:
                  type: string
                  description: Israeli mobile prefix (50, 52, 53, 54, 55, 58). Omit to see all.
                  example: "55"
                limit: { type: integer, default: 10 }
                page: { type: integer, default: 1 }
      responses:
        "200":
          description: >
            Available Israeli numbers: mobile numbers, or local (landline) numbers when no
            mobile number matches - `numberType` says which. The camelCase fields here surface
            the internal number-search response as-is.
          content:
            application/json:
              schema:
                type: object
                properties:
                  numbers:
                    type: array
                    items:
                      type: object
                      properties:
                        phoneNumber: { type: string, example: "+972551234567"  }
                        friendlyName: { type: string }
                        locality: { type: string }
                        region: { type: string, example: "IL"  }
                        capabilities:
                          type: object
                          properties:
                            voice: { type: boolean }
                            sms: { type: boolean }
                        pricing:
                          type: object
                          properties:
                            basePriceCents: { type: integer }
                            finalPriceCents: { type: integer }
                            priceDisplay: { type: string }
                            currency: { type: string, example: "USD"  }
                            markupPercentage: { type: number }
                  numberType: { type: string, enum: [Mobile, Local] }
                  pricing:
                    type: object
                    description: The monthly price every number on this page is sold at, in US cents, before VAT.
                    properties:
                      basePriceCents: { type: integer, example: 1000 }
                      finalPriceCents: { type: integer, example: 1000 }
                      priceDisplay: { type: string, example: "$10" }
                      currency: { type: string, example: "USD" }
                      markupPercentage: { type: number, example: 0 }
                      priceUnit: { type: string, example: "USD" }
                      fromCache: { type: boolean }
                  pagination:
                    type: object
                    properties:
                      currentPage: { type: integer }
                      totalPages: { type: integer }
                      totalNumbers: { type: integer }
                      limit: { type: integer }

  /phone-numbers/purchase:
    post:
      summary: Purchase number
      description: >
        Purchase an available Israeli number. Requires a payment method. Only
        Israeli numbers are supported — a non-Israeli `phone_number` is rejected
        with `400 {"error":"Only Israeli phone numbers are supported"}`.
      operationId: purchasePhoneNumber
      tags: [Phone Numbers]
      parameters:
        - in: header
          name: Idempotency-Key
          required: false
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{16,128}$' }
          description: >
            Makes the purchase safe to retry. A repeat with the same key, for the same number,
            charges once and orders one number: it answers the finished purchase with 200, 409
            PURCHASE_IN_PROGRESS while the first request is still completing it, or 409
            PURCHASE_FAILED when the first request's purchase did not go through. After
            PURCHASE_FAILED or any other error, send a new key. Without the header every request is
            a new purchase.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [phone_number]
              properties:
                phone_number: { type: string, example: "+972551234567"  }
      responses:
        "200":
          description: >
            Purchase result. Israeli numbers always start as `pending_requirements`
            — they are never `active` at purchase time. Activation happens later,
            once regulatory requirements clear (usually 1–3 business days), promoted
            by a background job.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  phoneNumber: { type: string }
                  monthlyPrice: { type: integer, description: "Monthly cost in cents" }
                  currency: { type: string }
                  status: { type: string, enum: [pending_requirements], description: "Always pending_requirements at purchase time for Israeli numbers." }
                  message: { type: string, description: "Human-readable status note (e.g. regulatory-review notice)." }
        "400":
          description: >
            IDEMPOTENCY_KEY_INVALID — the Idempotency-Key header is not 16 to 128 letters, digits,
            underscores or hyphens, or was sent more than once. Nothing was bought.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "409":
          description: >
            PURCHASE_IN_PROGRESS — a request with this Idempotency-Key is still completing the
            purchase; check your numbers in a minute. PURCHASE_FAILED — the purchase an earlier
            request with this key made did not go through (the card was declined, or it was rolled
            back); send a new key to try again. IDEMPOTENCY_KEY_REUSED — the key was already used
            for a different purchase; use a new key. Nothing was charged a second time.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /phone-numbers/{id}:
    patch:
      summary: Update number
      description: |
        Update one number's agent bindings, its friendly name, and its A/B
        tests. Send `inbound_split` / `outbound_split` as
        `{ "agent_id": "...", "percent": 30 }` to run two agents on that
        direction, or `null` to go back to one.

        `percent` is the share the SECOND agent takes. Both agents must belong
        to your workspace and must differ from the agent already bound to that
        direction.
      operationId: updatePhoneNumber
      tags: [Phone Numbers]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                friendly_name: { type: string, nullable: true }
                inbound_agent_id: { type: string, format: uuid, nullable: true }
                outbound_agent_id: { type: string, format: uuid, nullable: true }
                inbound_split:
                  nullable: true
                  allOf: [{ $ref: "#/components/schemas/AgentSplit" }]
                outbound_split:
                  nullable: true
                  allOf: [{ $ref: "#/components/schemas/AgentSplit" }]
              additionalProperties: false
            examples:
              start_a_test:
                summary: Send 30% of incoming calls to a second agent
                value: { inbound_split: { agent_id: "6f1b...", percent: 30 } }
              stop_a_test:
                summary: Go back to one agent
                value: { inbound_split: null }
      responses:
        "200":
          description: The updated number
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PhoneNumber" }
        "404":
          description: No such number in this workspace
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "422":
          description: |
            `INVALID_SPLIT` — the split is not an object or `null`, carries a key
            other than `agent_id` / `percent`, the share is outside 1–99, the second
            agent is the one already answering. The message says which. An agent
            field that names no agent in this workspace is 404 `AGENT_NOT_FOUND`,
            naming the field.
            A number from your own Telnyx account (`provider: external`) takes an
            `inbound_agent_id` and an `inbound_split` like any other; the agent
            answers once the number is configured (`carrier_state.state` is
            `ready`). `INBOUND_NOT_AVAILABLE_ON_EXTERNAL_NUMBER` is retired.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /phone-numbers/{id}/release:
    post:
      summary: Release number
      description: |
        Release a number bought from Yappr. Requires `phone_numbers:purchase`.

        A number whose subscription is paid up is **kept until the end of the period already
        paid for**, then released: it keeps answering and placing calls until then, and its rent
        does not renew. The answer is `released: false` with `release_at`, and
        GET /phone-numbers lists the same date as `scheduled_release_at`. A number whose payment
        is overdue, or that has no subscription, is released now: `released: true`, and it is no
        longer listed.

        [POST /phone-numbers/{id}/keep](/api-reference/phone-numbers/keep) undoes a scheduled
        release until `release_at`. Releasing a number that is already scheduled answers the same
        date and changes nothing.

        A campaign that still calls from the number, or a call on it in progress, refuses the
        release; nothing is changed. A number from your own Telnyx account (`provider: external`)
        is removed with DELETE /carrier-accounts/{id}/numbers/{phone_number_id} instead, and a
        `phone_system` number is switched off on its SIP endpoint. It takes no body and no query
        parameters.
      operationId: releasePhoneNumber
      tags: [Phone Numbers]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: >
            Scheduled (`released: false`, `release_at` the end of the paid period) or released now
            (`released: true`, `release_at: null`).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PhoneNumberRelease" }
              examples:
                scheduled:
                  summary: Kept until the end of the paid period
                  value: { phone_number_id: c0ffee00-0000-4000-8000-000000000001, released: false, release_at: "2026-11-18T04:16:32.000Z" }
                released_now:
                  summary: Payment overdue, released now
                  value: { phone_number_id: c0ffee00-0000-4000-8000-000000000001, released: true, release_at: null }
        "400":
          description: "PHONE_NUMBER_REQUEST_INVALID: a body field or query parameter was sent. It takes neither. Nothing was changed. issues[] names each one."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `phone_numbers:purchase`. API_KEY_AGENT_SCOPED — the key
            is limited to agents, and numbers belong to the whole workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "NOT_FOUND: no such number in this workspace (or it was released already). RESOURCE_ID_INVALID: the id in the path is not an id."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "409":
          description: |
            Nothing changed.
            - `NUMBER_IN_CAMPAIGN` — a campaign that has not ended calls from this number. Give it another caller number, or stop or delete it, first.
            - `NUMBER_ON_LIVE_CALL` — a call on this number is in progress. Try again when it ends.
            - `PHONE_SYSTEM_NUMBER` — the number calls out through your phone system (`provider: phone_system`). Switch outbound calls off on its SIP endpoint (PATCH /sip-endpoints/{id}, `register.outbound.enabled: false`), or delete that endpoint.
            - `NUMBER_FROM_OWN_CARRIER` — the number is in your own Telnyx account (`provider: external`). Remove it from this workspace with DELETE /carrier-accounts/{id}/numbers/{phone_number_id}.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "500":
          description: |
            - `PHONE_RELEASE_FAILED` — a release that runs now could not run. Try again in a minute.
            - `PHONE_RELEASE_INCOMPLETE` — a release that runs now did not finish at the carrier, or the number is still listed. Yappr has been notified; contact support if it stays listed.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "503":
          description: "BILLING_UNAVAILABLE: billing, or the number's checks, could not be reached. Nothing was changed. Try again in a minute."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /phone-numbers/{id}/keep:
    post:
      summary: Keep number
      description: |
        Undo a scheduled release: the number renews as before, and `scheduled_release_at` is
        null again. Requires `phone_numbers:purchase`. Keeping a number that is not scheduled to
        be released, but still has its subscription, answers the same and changes nothing. A
        number already released cannot be kept: buy a new one. It takes no body and no query
        parameters.
      operationId: keepPhoneNumber
      tags: [Phone Numbers]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Kept. `released` is false and `release_at` null.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PhoneNumberRelease" }
              example: { phone_number_id: c0ffee00-0000-4000-8000-000000000001, released: false, release_at: null }
        "400":
          description: "PHONE_NUMBER_REQUEST_INVALID: a body field or query parameter was sent. It takes neither. Nothing was changed. issues[] names each one."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `phone_numbers:purchase`. API_KEY_AGENT_SCOPED — the key
            is limited to agents, and numbers belong to the whole workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "NOT_FOUND: no such number in this workspace (or it was released already). RESOURCE_ID_INVALID: the id in the path is not an id."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "409":
          description: |
            Nothing changed.
            - `RELEASE_NOT_SCHEDULED` — the number has no subscription to keep (a number from your own carrier, one that calls out through your phone system, or one Yappr set up for you).
            - `SUBSCRIPTION_ENDED` — the number's subscription has already ended. Buy a new number.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "503":
          description: "BILLING_UNAVAILABLE: billing could not be reached. Nothing was changed. Try again in a minute."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /phone-numbers/configure:
    post:
      summary: Configure number
      description: |
        Assign inbound/outbound agents to a phone number. Accepts the same
        `inbound_split` / `outbound_split` objects as
        `PATCH /phone-numbers/{id}`, which is the preferred shape for new
        integrations.

        **The takeover is immediate.** As soon as this returns `200`, the
        number's next call goes to the agent named here; calls already
        connected finish with the agent that answered them. Nothing warns you
        that the number was already carrying traffic — read the number first
        if it is in production.
      operationId: configurePhoneNumber
      tags: [Phone Numbers]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [phone_number_id]
              properties:
                phone_number_id: { type: string, format: uuid }
                inbound_agent_id: { type: string, format: uuid, nullable: true }
                outbound_agent_id: { type: string, format: uuid, nullable: true }
                friendly_name: { type: string, nullable: true }
                inbound_split:
                  nullable: true
                  allOf: [{ $ref: "#/components/schemas/AgentSplit" }]
                outbound_split:
                  nullable: true
                  allOf: [{ $ref: "#/components/schemas/AgentSplit" }]
      responses:
        "200":
          description: >
            Number configured. The body echoes `success`, `phone_number_id` and the two
            `sip_*` flags as they already stood — carrier routing is set up once, at activation,
            not on every agent change. Re-read GET /phone-numbers to see the new bindings.
        "400":
          description: >
            `phone_number_id` is missing, the body did not parse, or the number is still
            `pending_requirements` and the request sets `inbound_agent_id` or `outbound_agent_id`.
            A request that only changes `friendly_name` or a split is accepted while pending.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "403":
          description: The number exists but belongs to another workspace.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "404":
          description: >
            No number with that id. The lookup is by id alone, so a wrong or stale
            `phone_number_id` lands here rather than on a validation error.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "422":
          description: |
            - `INVALID_SPLIT` — see PATCH /phone-numbers/{id}.

            A number from your own Telnyx account (`provider: external`) takes an
            `inbound_agent_id` and an `inbound_split` like any other.
            `INBOUND_NOT_AVAILABLE_ON_EXTERNAL_NUMBER` is retired.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /sip-endpoints:
    get:
      summary: List SIP endpoints
      description: |
        The workspace's SIP endpoints, newest first: username-and-password trunks,
        SIP address endpoints and extension endpoints. They let your own phone
        system send calls to a Yappr agent, with no Yappr phone number. A trunk's
        password is never listed; it is returned only by create and by
        [rotate-password](/api-reference/sip-endpoints/rotate-password), and an
        extension's password is never returned at all. An extension endpoint
        carries a `register` object with its settings and `register.status`;
        Yappr re-reads the status from its carrier when it is more than 15 seconds
        old, but not for a list of more than 20 extension endpoints, so check
        `register.status_checked_at`. Requires `sip_endpoints:read`.

        A SIP address endpoint's `sip_uri` (and the `slug` inside it) is its only
        credential, and a trunk's `sip_username` is half of its, so they go only
        to a key that also holds `sip_endpoints:manage`. A key with
        `sip_endpoints:read` alone (the Read-only preset) gets every endpoint with
        `slug`, `sip_uri` and `sip_username` set to `null`.

        Paging by `offset` is not a snapshot: an endpoint created while you page
        repeats a row on the next page, and one deleted skips one. There is no
        cursor yet; page until you have `total`, drop repeats by `id`, and read
        once more if `total` changed.
      operationId: listSipEndpoints
      tags: [SIP Endpoints]
      parameters:
        - in: query
          name: limit
          schema: { type: integer, default: 50, minimum: 1, maximum: 200 }
          description: Page size. A value above 200 is capped at 200.
        - in: query
          name: offset
          schema: { type: integer, default: 0, minimum: 0 }
        - in: query
          name: name
          schema: { type: string, minLength: 1, maxLength: 200 }
          description: |
            Only the endpoints with exactly this name, letter case included. Names
            are not unique, so it can match more than one.
      responses:
        "200":
          description: The workspace's SIP endpoints
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/SipEndpoint" }
                  total: { type: integer }
                  limit: { type: integer }
                  offset: { type: integer }
        "400":
          description: >
            `SIP_ENDPOINT_QUERY_INVALID` — a parameter other than `limit`,
            `offset` and `name`, one sent twice or with no value, or one of those two that is
            not a whole number (`limit` at least 1). It is refused rather than
            answered with every endpoint. `issues[]` names each parameter at fault
            (`query_param_unknown`, `query_param_repeated`, `query_param_blank`,
            `query_param_invalid`); `error` says the first.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "403":
          description: "`INSUFFICIENT_SCOPE` — the API key does not hold `sip_endpoints:read`, and the message names it."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "500":
          description: "`INTERNAL_ERROR` — Yappr could not load your SIP endpoints. Try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Create SIP endpoint
      description: |
        Create a SIP endpoint, so that calls from your own phone system reach an
        agent. Requires `sip_endpoints:manage`. Limit: 20 create attempts per
        workspace in 24 hours that run from the first attempt, all three kinds
        together. The limit counts attempts, not endpoints created.

        - `auth_mode: "credentials"` creates a **username-and-password
          trunk**. The response carries the username, the server settings and the
          password, **the password only this once**. In the dashboard, only
          workspace owners and admins can create one. While
          [GET /sip-endpoints/status](/api-reference/sip-endpoints/status) answers
          `credentials_available: false`, nothing is created: this answers
          `403 SIP_TRUNKS_NOT_ENABLED` (trunks aren't switched on for your
          workspace) or `409 VOICE_NOT_READY` (Yappr can't take trunk calls right
          now). A trunk only brings calls in: it can't place calls. An agent on a
          trunk call can hand the caller back to your phone system with a
          [SIP-address transfer destination](/concepts/sip-trunks#transfers). Any agent of the
          workspace can answer, including one that runs a workflow: publish its
          workflow first, because calls to an agent that is switched off, or whose
          workflow has never been published, are refused with SIP `603 Decline`,
          and the create doesn't check this.
        - `auth_mode: "uri"` (the default) creates a **SIP address endpoint**. The
          response carries the `sip_uri` your phone system dials, with no username
          or password. It works with any agent, including one that runs a
          workflow. The address is the endpoint's only credential: anyone who has
          it can call the agent.
        - `auth_mode: "register"` creates an **extension endpoint**, for a hosted
          phone system that only gives you an extension account. Send the
          extension's `register.server`, `register.username` and
          `register.password`; Yappr registers to your phone system like a
          softphone, and the agent answers the calls it routes to that extension.
          Yappr does not store the password or return it; its carrier holds it to
          keep the extension registered and to place transfers, so send the new one
          with an update whenever it changes on your phone system. Registration
          takes a few minutes: poll `register.status`. A workspace can hold 5.
          While [GET /sip-endpoints/status](/api-reference/sip-endpoints/status)
          answers `register_available: false`, nothing is created: this answers
          `403 SIP_REGISTER_NOT_ENABLED` or `409 VOICE_NOT_READY`.

        A field the endpoint does not read is refused by name with
        `400 SIP_ENDPOINT_REQUEST_INVALID`, and so is a value for a field of the
        other kind of endpoint. That includes `sip_username` and `sip_password`
        (Yappr issues both on a username-and-password trunk; a SIP address endpoint
        and an extension endpoint have neither: an extension's login goes inside
        `register`) and a top-level `transport`, which is not a setting.

        The [setup guide](/concepts/sip-trunks) says what to enter in your phone
        system, and which platforms can send calls to a username-and-password trunk.
      operationId: createSipEndpoint
      tags: [SIP Endpoints]
      parameters:
        - in: header
          name: Idempotency-Key
          required: false
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{16,128}$' }
          description: |
            Makes a retry safe. The same key and the same accepted body within 24
            hours answer 200 with the endpoint the first request created and
            `replayed: true`, never a trunk's password (issue a new one with
            rotate-password); the same key with another body is 409
            `IDEMPOTENCY_KEY_REUSED`. Scoped to this workspace. After 24 hours the
            key makes a new endpoint. Without it, every create makes a new endpoint.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [name, inbound_agent_id]
              properties:
                name:
                  type: string
                  minLength: 1
                  maxLength: 200
                  description: A label, shown in the dashboard.
                  example: "Main office PBX"
                inbound_agent_id:
                  type: string
                  format: uuid
                  description: An agent in this workspace. It answers every call on the endpoint. Any agent can answer, a workflow agent included; publish its workflow first (an agent that is switched off, or whose workflow has never been published, can't take calls, and a trunk refuses them with SIP `603 Decline`).
                auth_mode:
                  type: string
                  enum: [credentials, uri, register]
                  default: uri
                  description: |
                    `credentials`: a username-and-password trunk. `uri`: a SIP
                    address endpoint. `register`: an extension endpoint, with
                    `register`. Any kind answers with any agent. Without `auth_mode` you get
                    `uri`, exactly as before username-and-password trunks existed.
                max_concurrent_calls:
                  type: integer
                  minimum: 1
                  maximum: 8
                  default: 2
                  description: |
                    Username-and-password trunks and extension endpoints only. The most
                    calls the endpoint takes at once (ringing and in progress), 1 to
                    8; the next one is refused (a trunk answers SIP `486 Busy Here`). Omit it for
                    2. `null` is refused: every endpoint has a limit.
                  example: 5
                register: { $ref: "#/components/schemas/SipRegisterCreate" }
                slug:
                  type: string
                  minLength: 2
                  maxLength: 12
                  pattern: '^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$'
                  description: |
                    SIP address endpoints only. An optional readable start for the
                    address: 2 to 12 letters, digits and single hyphens, starting and
                    ending with a letter or digit. Yappr lowercases it and adds a
                    hyphen and 24 random characters after it. It can't be a reserved
                    word, or start with one followed by a hyphen: `yappr`, `admin`,
                    `internal`, `system`, `api`, `sip`, `telnyx`, `trunk`, `root`,
                    `test`, `sudo`, `support`. Derived from `name` when omitted. A
                    prefix that does not fit is refused, never rewritten.
                  example: "after-hours"
                allowed_source_ips:
                  type: [array, "null"]
                  deprecated: true
                  maxItems: 50
                  description: |
                    SIP address endpoints only. Source addresses to record with the
                    endpoint: IPv4 or IPv6 addresses, each optionally with a /prefix.
                    Recorded only — calls are not checked against them. `[]` and
                    `null` both mean none is recorded. An entry that is not an
                    address is refused.
                  items: { type: string, example: "203.0.113.0/24" }
            examples:
              credentials:
                summary: Username-and-password trunk
                value:
                  name: "Main office PBX"
                  inbound_agent_id: "3f1c2b9e-7a4d-4e21-9c55-1b2d3e4f5a6b"
                  auth_mode: "credentials"
                  max_concurrent_calls: 5
              uri:
                summary: SIP address endpoint
                value:
                  name: "After-hours"
                  inbound_agent_id: "3f1c2b9e-7a4d-4e21-9c55-1b2d3e4f5a6b"
              register:
                summary: Extension endpoint
                value:
                  name: "Hosted PBX extension"
                  inbound_agent_id: "3f1c2b9e-7a4d-4e21-9c55-1b2d3e4f5a6b"
                  auth_mode: "register"
                  max_concurrent_calls: 2
                  register:
                    server: "sip1.example.net"
                    username: "101"
                    password: "ExtensionPasswordFromYourPhoneSystem"
                    transport: "udp"
                    region: "middle_east"
      responses:
        "200":
          description: |
            A retry with the same `Idempotency-Key` and body, within 24 hours: the
            endpoint the first request created, with `replayed: true`. Nothing new
            was created. A trunk's `sip_password` is not in it.
          content:
            application/json:
              schema:
                type: object
                required: [data, replayed]
                properties:
                  data: { $ref: "#/components/schemas/SipEndpoint" }
                  replayed: { type: boolean, enum: [true] }
        "201":
          description: |
            Created. A username-and-password trunk carries `sip_password`: store it
            now, it is never shown again. A SIP address endpoint carries its
            `sip_uri`: hand it to whoever runs the phone system. An extension
            endpoint carries its `register` object, with `status` `pending` until
            the carrier has applied it (a few minutes); it has no password in the
            response.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/SipEndpointWithPassword" }
              examples:
                credentials:
                  summary: Username-and-password trunk
                  value:
                    data:
                      id: "8d0c5f4e-2b1a-4c3d-9e8f-7a6b5c4d3e2f"
                      name: "Main office PBX"
                      auth_mode: "credentials"
                      slug: null
                      sip_uri: null
                      sip_username: "yp4k7d2m9x1q8w3z"
                      max_concurrent_calls: 5
                      sip_connection:
                        server: "sip.telnyx.com"
                        alternate_servers: ["sip.telnyx.eu", "sip.telnyx.me"]
                        transports:
                          - { protocol: tls, port: 5061, recommended: true }
                          - { protocol: tcp, port: 5060 }
                          - { protocol: udp, port: 5060 }
                        registration: "optional"
                      inbound_agent_id: "3f1c2b9e-7a4d-4e21-9c55-1b2d3e4f5a6b"
                      is_active: true
                      last_call_at: null
                      created_at: "2026-10-01T12:00:00Z"
                      updated_at: "2026-10-01T12:00:00Z"
                      sip_password: "Ex4mpleOnlyNotARealPassword12345"
                uri:
                  summary: SIP address endpoint
                  value:
                    data:
                      id: "1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"
                      name: "After-hours"
                      auth_mode: "uri"
                      slug: "after-hours-bz3r3mtypuwuw8tpdw3x392s"
                      inbound_agent_id: "3f1c2b9e-7a4d-4e21-9c55-1b2d3e4f5a6b"
                      is_active: true
                      last_call_at: null
                      allowed_source_ips: null
                      created_at: "2026-10-01T12:00:00Z"
                      updated_at: "2026-10-01T12:00:00Z"
                      sip_uri: "sip:after-hours-bz3r3mtypuwuw8tpdw3x392s@yappr-byoc.sip.telnyx.com"
                register:
                  summary: Extension endpoint
                  value:
                    data:
                      id: "5e9a7c21-3b4d-4f60-8a1c-2d3e4f5a6b7c"
                      name: "Hosted PBX extension"
                      auth_mode: "register"
                      slug: null
                      sip_uri: null
                      max_concurrent_calls: 2
                      inbound_agent_id: "3f1c2b9e-7a4d-4e21-9c55-1b2d3e4f5a6b"
                      is_active: true
                      last_call_at: null
                      created_at: "2026-10-04T12:00:00Z"
                      updated_at: "2026-10-04T12:00:00Z"
                      register:
                        server: "sip1.example.net"
                        username: "101"
                        auth_username: null
                        transport: "udp"
                        region: "middle_east"
                        status: "pending"
                        status_detail: null
                        status_checked_at: null
                        allow_list:
                          sip_ip: "192.76.120.75"
                          sip_ports: [5060, 5061]
                          rtp_ports: "16384-32768"
                          note: "allow these on your phone system"
        "400":
          description: |
            Nothing was created.
            - `SIP_ENDPOINT_REQUEST_INVALID` — `error` says why: `name` or
              `inbound_agent_id` missing, an agent that is not in this workspace, an
              `auth_mode` other than `credentials`, `uri` or `register`,
              `max_concurrent_calls` outside 1–8 or `null`, a `slug` outside its
              rules, an `allowed_source_ips` entry that is not an address, `register`
              missing or incomplete on an extension endpoint, a value for a field of
              the other kind of endpoint (`max_concurrent_calls` on a SIP address
              endpoint; `slug` or `allowed_source_ips` on a username-and-password
              trunk or an extension endpoint; `register` on any other kind), a field
              this call does not take, such as `sip_username`, `sip_password` or
              `transport`, or a body that is not a JSON object. `issues[]` names every
              fault at once, each at its pointer (`/name`, `/allowed_source_ips/1`)
              with `field_unknown`, `field_required` or `field_invalid`; an
              `Idempotency-Key` that can't be one is `header_invalid` at
              `Idempotency-Key`.
            - `SIP_REGISTER_HOST_INVALID` — extension endpoints: `register.server` is
              not a public host name or address (a scheme, a path, a private or
              loopback address, or a Yappr or Telnyx host).
            - `SIP_ENDPOINT_QUERY_INVALID` — the request has a query parameter; this
              call takes none.

            For `auth_mode: "register"`, `SIP_ENDPOINT_REQUEST_INVALID` also covers
            a missing `register`, `register.server`, `register.username` or
            `register.password`, a value that does not fit, and `sip_username`,
            `sip_password`, `slug` or `sip_uri` (an extension endpoint has none).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "403":
          description: |
            Nothing was created.
            - `SIP_REGISTER_NOT_ENABLED` — extension endpoints aren't switched on
              for this workspace. Ask Yappr support to switch them on; the other
              kinds are not affected.
            - `SIP_REGISTER_OUTBOUND_NOT_ENABLED` — `register.outbound.enabled: true`, and
              calling out through an extension isn't switched on for this workspace. Ask
              Yappr support; create it without `register.outbound` meanwhile.
            - `INSUFFICIENT_SCOPE` — the API key does not hold
              `sip_endpoints:manage`, and the message names it.
            - `FORBIDDEN_ROLE` — dashboard sessions only: just workspace owners and
              admins can create a username-and-password trunk. API keys with
              `sip_endpoints:manage` can.
            - `SIP_TRUNKS_NOT_ENABLED` — username-and-password trunks aren't
              switched on for this workspace. Ask Yappr support to switch them on.
              SIP address endpoints are not affected.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            Nothing was created, except for `SIP_REGISTER_SETUP_IN_PROGRESS`.
            - `VOICE_NOT_READY` — Yappr can't answer calls on username-and-password
              trunks or extension endpoints right now, for example during an update.
              Try again in a few minutes ([GET /sip-endpoints/status](/api-reference/sip-endpoints/status)
              says when). SIP address endpoints are not affected.
            - `SIP_REGISTER_LIMIT_REACHED` — extension endpoints: the workspace
              already holds its limit (5 unless Yappr support raised it), or Yappr has
              no room for another registration right now. Delete one you don't use,
              or ask Yappr support.
            - `PHONE_NUMBER_IN_USE` — `register.outbound.caller_number` is already a
              phone number in Yappr. Use another number, or remove it where it is.
            - `VOICE_NOT_READY` also answers `register.outbound.enabled: true` while the
              voice server can't place calls through an extension yet (`register_outbound_available`
              on [GET /sip-endpoints/status](/api-reference/sip-endpoints/status) says when).
            - `SIP_REGISTER_SETUP_IN_PROGRESS` — extension endpoints: a create with
              the same `Idempotency-Key` started an endpoint whose setup has not
              finished. Wait a minute and list your endpoints; if it is still
              switched off, delete it and create it again (if the new one then reads failed with 'extension username already in use', use a different extension name).
            - `SIP_REGISTER_EXTENSION_IN_USE` — extension endpoints: this extension
              username is already used by another live endpoint. Nothing was created.
              Use another extension name, or edit that endpoint. A name held by a
              deleted endpoint is not refused here: the create is accepted and the
              endpoint later shows the status `failed` with the reason "extension
              username already in use". To change an endpoint of yours, edit it
              instead of deleting and re-creating it.
              Usernames are unique across Yappr, first come first served, so with a
              short extension such as `101` a clash is likely: create a dedicated
              extension on your phone system with a distinctive name (letters,
              digits, `-` or `_`).
            - `CONFLICT` — a SIP address endpoint's generated address was already
              taken (rare). Send the request again for a new random address.
            - `IDEMPOTENCY_KEY_REUSED` — this `Idempotency-Key` already created an
              endpoint in the last 24 hours, from a different body. Send the
              original body to get that endpoint, or use a new key.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: |
            `RATE_LIMITED` (`RATE_LIMIT` on a SIP address endpoint) — this workspace
            already made 20 create attempts in the current 24 hours, which run from
            its first attempt. The limit counts attempts, not endpoints created, so
            an attempt that failed can count too. Nothing was created; try again
            once the 24 hours are up.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "500":
          description: "`INTERNAL_ERROR` — Yappr could not save the endpoint. Nothing was created; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "502":
          description: |
            `SIP_TRUNK_PROVISIONING_FAILED` — username-and-password trunks: the
            username and password could not be set up with Yappr's carrier.
            Nothing was created; try again in a minute.
            `SIP_REGISTER_PROVIDER_ERROR` — extension endpoints: the registration
            could not be set up with Yappr's carrier. Yappr undoes the attempt
            and nothing is created; try again in a minute. If it could not
            confirm the undo, the endpoint stays in the list, switched off:
            delete it, then create it again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /sip-endpoints/status:
    get:
      summary: Check username-and-password SIP trunks are available
      description: |
        Whether username-and-password SIP trunks are available to this
        workspace: whether it can create one right now. `credentials_available`
        is `true` when trunks are switched on for your workspace and Yappr's
        voice servers answer calls on them. It doesn't mean a particular agent can
        answer: an agent that is switched off, or whose workflow has never been
        published, can't take calls. While it is `false`, a create with
        `"auth_mode": "credentials"` is refused with `403 SIP_TRUNKS_NOT_ENABLED`
        (not switched on for your workspace: ask Yappr support) or
        `409 VOICE_NOT_READY` (for example during an update: try again in a few
        minutes), and the dashboard offers SIP address endpoints only. Existing
        endpoints can still be listed, changed and deleted, and a trunk can still
        get a new password with
        [rotate-password](/api-reference/sip-endpoints/rotate-password). Yappr
        checks its voice servers at most once a minute, so the answer can be up
        to a minute old. `register_available` says the same for extension endpoints
        (`auth_mode: "register"`): `false` means a create answers
        `403 SIP_REGISTER_NOT_ENABLED` or `409 VOICE_NOT_READY`. Requires
        `sip_endpoints:read`; it takes no query parameters.
      operationId: getSipEndpointsStatus
      tags: [SIP Endpoints]
      responses:
        "200":
          description: Whether username-and-password trunks can be created
          content:
            application/json:
              schema:
                type: object
                required: [credentials_available]
                properties:
                  credentials_available: { type: boolean, example: true }
                  register_available:
                    type: boolean
                    example: true
                    description: |
                      Extension endpoints can be created now: they are switched on for
                      your workspace and Yappr's voice servers answer calls on them.
                  register_outbound_available:
                    type: boolean
                    example: false
                    description: |
                      `register.outbound` can be switched on now: calling out through an
                      extension is switched on for your workspace and Yappr's voice servers
                      place these calls.
        "400":
          description: "`SIP_ENDPOINT_QUERY_INVALID` — the request has a query parameter; this call takes none."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "403":
          description: "`INSUFFICIENT_SCOPE` — the API key does not hold `sip_endpoints:read`, and the message names it."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /sip-endpoints/{id}:
    get:
      summary: Get SIP endpoint
      description: |
        One SIP endpoint. A trunk's password is never returned here; it is
        returned only by create and by
        [rotate-password](/api-reference/sip-endpoints/rotate-password). Requires
        `sip_endpoints:read`. A SIP address endpoint's `slug` and `sip_uri`, and a
        trunk's `sip_username`, are returned only to a key that also holds
        `sip_endpoints:manage`; with `sip_endpoints:read` alone (the Read-only
        preset) they are `null`. It takes no query parameters.
      operationId: getSipEndpoint
      tags: [SIP Endpoints]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: The SIP endpoint
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/SipEndpoint" }
        "400":
          description: "`SIP_ENDPOINT_QUERY_INVALID` — the request has a query parameter, such as `include=password`; this call takes none, and no read returns a password. `issues[]` names each."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "403":
          description: "`INSUFFICIENT_SCOPE` — the API key does not hold `sip_endpoints:read`, and the message names it."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "`SIP_ENDPOINT_NOT_FOUND` — no SIP endpoint with this id in this workspace. `RESOURCE_ID_INVALID` — the id in the path is not an id at all."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "500":
          description: "`INTERNAL_ERROR` — Yappr could not load this SIP endpoint. Try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    patch:
      summary: Update SIP endpoint
      description: |
        Change any endpoint's `name`, `inbound_agent_id` or `is_active`, a
        username-and-password trunk's `max_concurrent_calls`, or a SIP address
        endpoint's `allowed_source_ips`. Send at least one of them. Requires
        `sip_endpoints:manage`; in the dashboard, only workspace owners and
        admins can change a username-and-password trunk.

        On an extension endpoint, `register` changes the extension's settings: the
        carrier re-applies them, so `register.status` goes back to `pending` for a
        few minutes. Changing `register.username` or `register.auth_username`, or
        sending `register.password`, needs the password in the same request. Send
        `register.password` whenever the password changes on your phone system:
        Yappr does not keep it, but its carrier holds the last one it was given and
        uses it to register and to place transfers, so until you send the new one
        transfers fail, and `register.status` can keep reading `registered`.

        Not changed here: `auth_mode` (create a new endpoint instead), a trunk's
        username and password (for a new password, use
        [rotate-password](/api-reference/sip-endpoints/rotate-password)), and the
        SIP address: a body with `slug` is refused with
        `400 SIP_ENDPOINT_REQUEST_INVALID`. To move to a new address, create a new
        endpoint, point your phone system at it, then delete this one. Any other
        field the endpoint does not read is refused the same way, by name.
      operationId: updateSipEndpoint
      tags: [SIP Endpoints]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              minProperties: 1
              properties:
                name: { type: string, minLength: 1, maxLength: 200, description: "A new label." }
                inbound_agent_id: { type: string, format: uuid, description: "An agent in this workspace. It answers from the next call on. Any agent can answer, a workflow agent included; calls to an agent that is switched off, or whose workflow has never been published, are refused (on a trunk with SIP `603 Decline`)." }
                is_active:
                  type: boolean
                  description: |
                    `false` refuses the endpoint's new calls before they are answered
                    until you set it back to `true` (a trunk or SIP address endpoint
                    answers SIP `603 Decline`; an extension endpoint's calls are
                    refused). Calls in progress are not affected. On a trunk or SIP
                    address endpoint, re-route the calls in your phone system first:
                    it may not try its next route after a `603`. On an extension
                    endpoint, `register.status` reads `disabled` and your phone system
                    is **not** told. Re-route or remove the extension on your phone
                    system first. To change an extension endpoint's agent, call limit,
                    server or password, edit it: don't delete and re-create it.
                max_concurrent_calls:
                  type: integer
                  minimum: 1
                  maximum: 8
                  description: "Username-and-password trunks and extension endpoints only. 1 to 8 calls at once. `null` is refused: every endpoint has a limit."
                register: { $ref: "#/components/schemas/SipRegisterUpdate" }
                allowed_source_ips:
                  type: [array, "null"]
                  deprecated: true
                  maxItems: 50
                  description: "SIP address endpoints only. Recorded only — calls are not checked against it. `[]` or `null` clears it."
                  items: { type: string }
      responses:
        "200":
          description: The updated SIP endpoint
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/SipEndpoint" }
        "400":
          description: |
            Nothing was saved.
            - `SIP_ENDPOINT_REQUEST_INVALID` — `error` says why: nothing to update, a
              value that does not fit (for example `max_concurrent_calls` outside
              1–8, or `null`), an agent that is not in this workspace, a value for a
              field of the other kind of endpoint, a field that cannot change here
              (`slug`, `auth_mode`, a trunk's username and password) or that this call
              does not take, or a body that is not a JSON object. `issues[]` names
              every fault at once, each at its pointer.
            - `SIP_REGISTER_PASSWORD_REQUIRED` — `register.username` or
              `register.auth_username` is changed without `register.password`: Yappr
              doesn't keep the password, so send it again with the change.
            - `SIP_REGISTER_HOST_INVALID` — `register.server` is not a public host
              name or address.
            - `SIP_ENDPOINT_QUERY_INVALID` — the request has a query parameter; this
              call takes none.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "403":
          description: |
            Nothing was saved.
            - `INSUFFICIENT_SCOPE` — the API key does not hold
              `sip_endpoints:manage`, and the message names it.
            - `FORBIDDEN_ROLE` — dashboard sessions only: just workspace owners and
              admins can change a username-and-password trunk.
            - `SIP_REGISTER_OUTBOUND_NOT_ENABLED` — switching `register.outbound` on, where
              calling out through an extension isn't switched on for this workspace.
              Switching it off always works.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "`SIP_ENDPOINT_NOT_FOUND` — no SIP endpoint with this id in this workspace. `RESOURCE_ID_INVALID` — the id in the path is not an id at all."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            - `SIP_TRUNK_NOT_PROVISIONED` — this trunk's username and password were never finished, so it cannot be switched on. Delete it and create a new one.
            - `SIP_REGISTER_NOT_PROVISIONED` — this extension endpoint's registration was never finished, or is no longer set up at Yappr's carrier. Delete it and create a new one (if the new one then reads failed with 'extension username already in use', use a different extension name).
            - `SIP_REGISTER_EXTENSION_IN_USE` — `register.username` is already used by another live endpoint. Use another extension name.
            - `SIP_REGISTER_PROVIDER_ERROR` — the carrier is still applying the last change. Nothing was changed; wait a few minutes and try again.
            - `PHONE_NUMBER_IN_USE` — `register.outbound.caller_number` is already a phone number in Yappr. Nothing was saved. Use another number, or remove it where it is.
            - `VOICE_NOT_READY` — switching `register.outbound` on while the voice server can't place calls through an extension yet. Nothing was saved; try again in a few minutes.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: |
            `RATE_LIMITED` — extension endpoints: this workspace already made 30
            changes to extension endpoints in the last hour. A change that stays in
            Yappr (name, agent, call limit) doesn't count. Nothing was changed; try
            again later.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "500":
          description: "`INTERNAL_ERROR` — Yappr could not load the endpoint or save the change. Nothing was saved; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "502":
          description: "`SIP_REGISTER_PROVIDER_ERROR` — extension endpoints: the change could not be applied at Yappr's carrier. The endpoint keeps its old settings; try again in a minute."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      summary: Delete SIP endpoint
      description: |
        Deletes the endpoint. Requires `sip_endpoints:manage`. Re-route the calls
        in your phone system first: from then on, every call it sends here is
        refused.

        - **Username-and-password trunk:** Yappr first removes the trunk's
          username and password at its carrier, so they stop working within
          seconds: your phone system's next call is refused with SIP
          `403 Forbidden`. Only then is the endpoint deleted. In the dashboard,
          only workspace owners and admins can delete one. To replace a lost or
          leaked password instead, use
          [rotate-password](/api-reference/sip-endpoints/rotate-password).
        - **SIP address endpoint:** from then on, calls to its `sip_uri` are
          refused before they are answered (SIP `603 Decline`). Calls already in
          progress finish normally. To replace an address that may have leaked,
          create a new endpoint (it gets a fresh random address), point your phone
          system at it, then delete the old one.
        - **Extension endpoint:** Yappr deletes the extension's connection at its
          carrier first, then the endpoint. **Your phone system is not told:** the
          carrier can keep registering the extension on your phone system for hours
          (observed: more than 4 hours 40 minutes), so your phone system keeps
          routing its calls there and they are rejected. Meanwhile a new endpoint
          with the same extension name fails with "already in use", also when the
          deleted endpoint never registered (for example a wrong password). Re-route or
          remove the extension on your phone system **before** you delete. To
          change the agent, call limit, server or password, edit the endpoint
          (`PATCH`): don't delete and re-create it. If the extension called out
          through your phone system, its number (`provider: "phone_system"`) is
          removed with it, and `campaigns_without_number` says how many campaigns
          were calling from that number: they keep their history and have no
          number to call from until you pick one.
      operationId: deleteSipEndpoint
      tags: [SIP Endpoints]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                required: [ok]
                properties:
                  ok: { type: boolean, example: true }
                  campaigns_without_number:
                    type: integer
                    minimum: 0
                    example: 1
                    description: |
                      Only for an extension endpoint that called out through your
                      phone system (it had a `phone_system` number). How many
                      campaigns were calling from that number, which is removed with
                      the endpoint: they keep their history and lose their number
                      (`from_phone_number_id` becomes `null`, so they call from their
                      agent's own number, or cannot launch until you pick one with
                      `PATCH /campaigns/{id}`). `0` when none was.
        "400":
          description: "`SIP_ENDPOINT_QUERY_INVALID` — the request has a query parameter; this call takes none. Nothing was deleted."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "403":
          description: |
            Nothing was deleted.
            - `INSUFFICIENT_SCOPE` — the API key does not hold
              `sip_endpoints:manage`, and the message names it.
            - `FORBIDDEN_ROLE` — dashboard sessions only: just workspace owners and
              admins can delete a username-and-password trunk.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "`SIP_ENDPOINT_NOT_FOUND` — no SIP endpoint with this id in this workspace. `RESOURCE_ID_INVALID` — the id in the path is not an id at all."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "500":
          description: "`INTERNAL_ERROR` — Yappr could not load or delete the endpoint. On a username-and-password trunk, its username and password may already have stopped working; try again to finish the delete."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "502":
          description: |
            `SIP_TRUNK_PROVISIONING_FAILED` — username-and-password trunks: the
            username and password could not be removed at Yappr's carrier, so the
            trunk was not deleted. Try again in a minute.
            `SIP_REGISTER_PROVIDER_ERROR` — extension endpoints: the registration
            could not be removed at Yappr's carrier, so nothing was deleted. Try
            again in a minute.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /sip-endpoints/{id}/rotate-password:
    post:
      summary: Issue a new SIP password
      description: |
        Username-and-password trunks only. Issues the trunk a new SIP password and
        returns it **once**, in `sip_password`. The username stays the same. Send
        no body (or an empty JSON object): Yappr issues the password, so it can't
        be chosen.

        The old password stops working within seconds, and calls already in
        progress are not dropped. Enter the new password in your phone system
        right away. If it registers, it learns of the change only at its next
        registration refresh, which fails until the new password is in.

        Requires `sip_endpoints:manage`; in the dashboard, only workspace owners
        and admins. Limit: 10 attempts per trunk in an hour that runs from the
        first attempt. The limit counts attempts, not new passwords issued, and
        `rotations_left` says how many are left. The trunk's
        `password_rotated_at` (and `updated_at`) say when the password changed.
      operationId: rotateSipEndpointPassword
      tags: [SIP Endpoints]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: The trunk, with its new password in `sip_password`. Store it now; it is never shown again.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    allOf:
                      - { $ref: "#/components/schemas/SipEndpoint" }
                      - type: object
                        required: [sip_password]
                        properties:
                          sip_password:
                            type: string
                            description: |
                              The trunk's new SIP password, 32 letters and digits.
                              Store it now: neither the API nor the dashboard can
                              show it again. If it is lost, issue a new one.
                            example: "N3wExampleOnlyNotARealPassword99"
                  rotations_left:
                    type: [integer, "null"]
                    minimum: 0
                    maximum: 10
                    description: |
                      How many more attempts at a new password this trunk has in
                      the current hour, which runs from its first attempt. `null`
                      when it could not be read; the new password is valid either way.
                    example: 9
        "400":
          description: |
            The password did not change.
            - `SIP_ENDPOINT_REQUEST_INVALID` — the body has a field, or is JSON
              that is not an object: this call takes no body. A body that is not
              JSON at all is ignored, and the password is changed as if you had
              sent none.
            - `SIP_ENDPOINT_QUERY_INVALID` — the request has a query parameter;
              this call takes none.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "403":
          description: |
            The password did not change.
            - `INSUFFICIENT_SCOPE` — the API key does not hold
              `sip_endpoints:manage`, and the message names it.
            - `FORBIDDEN_ROLE` — dashboard sessions only: just workspace owners
              and admins can issue a new password.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "`SIP_ENDPOINT_NOT_FOUND` — no SIP endpoint with this id in this workspace. `RESOURCE_ID_INVALID` — the id in the path is not an id at all."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            The password did not change.
            - `SIP_ENDPOINT_NOT_CREDENTIALS` — this is a SIP address endpoint, which
              has no password. To move it to a new address, create a new endpoint,
              point your phone system at it, then delete this one.
            - `NOT_SUPPORTED_FOR_MODE` — this is an extension endpoint: its password
              is your phone system's. Send the new one with
              [`PATCH /sip-endpoints/{id}`](/api-reference/sip-endpoints/update) as
              `register.password`.
            - `SIP_TRUNK_NOT_PROVISIONED` — this trunk's username and password were
              never finished, or are no longer set up at Yappr's carrier. Delete it
              and create a new one.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: |
            `RATE_LIMITED` — this trunk already had 10 attempts at a new password
            in the current hour, which runs from its first attempt. The limit
            counts attempts, so an attempt that failed can count too. The password
            did not change; try again once the hour is up.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "500":
          description: "`INTERNAL_ERROR` — Yappr could not load the trunk. The password did not change; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "502":
          description: |
            `SIP_TRUNK_PROVISIONING_FAILED` — the new password could not be set
            or confirmed at Yappr's carrier. `error` says whether the current
            password still works. Try again in a minute: the password from the
            next successful answer is the one that works.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /carrier-accounts:
    get:
      summary: List carrier accounts
      description: |
        Your connected Telnyx accounts, each with the numbers added to it. Requires
        `carrier_accounts:read`.
      operationId: listCarrierAccounts
      tags: [Carrier Accounts]
      responses:
        "200":
          description: Your carrier accounts
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/CarrierAccount" }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
    post:
      summary: Connect a Telnyx account
      description: |
        Save a Telnyx API key made just for Yappr. The key is checked with Telnyx
        first; nothing is saved if Telnyx refuses it. Then
        [choose the Call Control App](/api-reference/carrier-accounts/connection) and
        [add your numbers](/api-reference/carrier-accounts/add-number). Requires
        `carrier_accounts:manage`. Limit: 10 per workspace per day.
      operationId: createCarrierAccount
      tags: [Carrier Accounts]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CarrierAccountCreate" }
      responses:
        "201":
          description: Connected (status `untested`, no app yet)
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/CarrierAccount" }
                  webhook_url: { type: string, format: uri, description: "The URL a Call Control App you made must use." }
                  telnyx:
                    type: object
                    description: The Call Control Apps and outbound voice profiles your key can see (same shape as the test result's `telnyx`).
        "400":
          description: "`INVALID_NAME`, `INVALID_API_KEY`, `INVALID_PUBLIC_KEY` or `INVALID_JSON`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "422":
          description: "`TELNYX_KEY_REJECTED` — Telnyx refused the key. `KEY_IS_YAPPR_ACCOUNT` — the key belongs to Yappr's own Telnyx account."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: "`RATE_LIMITED` — 10 accounts connected today."
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "`TELNYX_UNAVAILABLE` — Telnyx did not answer. Nothing changed; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /carrier-accounts/status:
    get:
      summary: Check carrier accounts are available
      description: |
        Whether this workspace may use carrier accounts (calls from numbers in your own
        Telnyx account). They are available in every workspace, so this answers
        `{"enabled": true, "sync": {...}}` unless Yappr has switched them off for this one; then every
        carrier-accounts route answers `403 CARRIER_ACCOUNTS_NOT_ENABLED`. Any valid API key
        reads it, whatever its scopes (a Read-only key included); a key limited to agents is
        refused `403 API_KEY_AGENT_SCOPED`, like every carrier-accounts route.

        `sync` says whether Yappr has switched number syncing on, read without running a
        sync and without asking Telnyx anything: `ready: false` (reason `sync_not_ready`)
        means no account's numbers are synced yet. Each account's `sync_status` says the
        same for that account, with when it last synced and why not.
      operationId: getCarrierAccountsStatus
      tags: [Carrier Accounts]
      responses:
        "200":
          description: Available
          content:
            application/json:
              schema:
                type: object
                properties:
                  enabled: { type: boolean, example: true }
                  sync:
                    type: object
                    description: |
                      Whether Yappr has switched number syncing on, read without running a
                      sync. Each account's `sync_status` says the same and more.
                    properties:
                      enabled: { type: boolean, description: "Number syncing is served to this workspace: `true` wherever carrier accounts are." }
                      ready:
                        type: boolean
                        nullable: true
                        description: "`false` while Yappr has not switched number syncing on: no account is synced, and POST /sync answers `503 SYNC_NOT_READY`. `null` when Yappr cannot say right now."
                      reason: { type: string, nullable: true, enum: [sync_not_ready, null] }
                    example: { enabled: true, ready: true, reason: null }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }

  /carrier-accounts/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get carrier account
      description: |
        Requires `carrier_accounts:read`. The account's `webhook_url` carries a secret,
        so it is left out unless you ask for it with `?include=webhook_url`, which needs
        `carrier_accounts:manage`.
      operationId: getCarrierAccount
      tags: [Carrier Accounts]
      parameters:
        - name: include
          in: query
          required: false
          schema: { type: string, enum: [webhook_url] }
          description: "`webhook_url` adds the account's webhook URL to `data`. Only a `carrier_accounts:manage` key may ask; any other value is `400 CARRIER_ACCOUNTS_QUERY_INVALID`."
      responses:
        "200":
          description: The account
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/CarrierAccount" }
        "400":
          description: "`CARRIER_ACCOUNTS_QUERY_INVALID` — `include` named something other than `webhook_url`; `issues[0].path` is `include`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: |
            `CARRIER_ACCOUNTS_NOT_ENABLED` — Yappr has switched carrier accounts off for this
            workspace. `INSUFFICIENT_SCOPE` — `?include=webhook_url` from a key without
            `carrier_accounts:manage`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` — not in this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    patch:
      summary: Update carrier account
      description: "Rename it, or replace its API key or public key. Requires `carrier_accounts:manage`. Limit: 20 per workspace per day. An update that sends a new `api_key` returns the account's `webhook_url` with it; any other update leaves it out."
      operationId: updateCarrierAccount
      tags: [Carrier Accounts]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CarrierAccountUpdate" }
      responses:
        "200":
          description: Updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/CarrierAccount" }
        "400":
          description: "`NOTHING_TO_UPDATE`, `INVALID_NAME`, `INVALID_API_KEY`, `INVALID_PUBLIC_KEY` or `INVALID_JSON`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` — not in this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: "`TELNYX_KEY_REJECTED`, `KEY_ACCOUNT_MISMATCH` (the new key is from another Telnyx account) or `KEY_IS_YAPPR_ACCOUNT`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: "`RATE_LIMITED`."
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "`TELNYX_UNAVAILABLE` — Telnyx did not answer. Nothing changed; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      summary: Disconnect carrier account
      description: |
        Deletes the saved key. If Yappr created the Call Control App, Yappr deletes it
        from your Telnyx account too (`telnyx_connection_deleted`). Yappr never deletes
        your API key: delete it in Telnyx yourself. A number still configured to
        answer here has to go back to its previous connection first: send
        `restore_routing=true`, or stop answering on each one. Requires
        `carrier_accounts:manage`.

        A number nothing points at is deleted. A number with history (a past call, a
        campaign, a charge) is kept so that history stays: switched off, its
        `carrier_state.state` is `removed` (Removed from this workspace, never "gone
        from Telnyx": it may still be in your Telnyx account) and its
        `carrier_account.status` is `disconnected`.
      operationId: deleteCarrierAccount
      tags: [Carrier Accounts]
      parameters:
        - name: restore_routing
          in: query
          required: false
          schema: { type: boolean, default: false }
          description: |
            `true` first moves every configured number back to the connection it
            was on in your Telnyx account, then disconnects.
      responses:
        "200":
          description: Disconnected
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  id: { type: string, format: uuid }
                  telnyx_connection_deleted: { type: boolean, nullable: true, description: "`null` when Yappr did not create the app; `false` when Telnyx did not confirm deleting it." }
                  restore: { $ref: "#/components/schemas/CarrierRestoreResult" }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` — not in this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "400":
          description: "`CARRIER_ACCOUNTS_QUERY_INVALID` — a query parameter other than `restore_routing`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            `CARRIER_ACCOUNT_HAS_CONFIGURED_NUMBERS` — a number still answers here;
            send `restore_routing=true`. With it, a number Telnyx would not put back, or
            more than 50 configured, answers this too, with `restore` (`ok: false`):
            nothing was disconnected; fix `restore.failed`, or send the same request
            again while `restore.remaining` is above 0. `CARRIER_NUMBERS_USED_BY_CAMPAIGNS`
            — a campaign calls from one of its numbers. `CARRIER_ACCOUNT_HAS_LIVE_CALLS`
            — a call on the account is still running. `CARRIER_ACCOUNT_HAS_NUMBERS`
            is retired.
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Error" }
                  - type: object
                    properties:
                      restore: { $ref: "#/components/schemas/CarrierRestoreResult" }

  /carrier-accounts/{id}/connection:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Choose the Call Control App
      description: |
        Choose the Call Control App Yappr places calls through: let Yappr create one
        in your account on an outbound voice profile you pick (`create`), or give one
        you made (`connection_id`). Yappr never creates or changes an outbound voice
        profile. Requires `carrier_accounts:manage`. Limit: 10 per workspace per day.
      operationId: connectCarrierAccountApp
      tags: [Carrier Accounts]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/CarrierConnectionSetup" }
      responses:
        "200":
          description: App connected
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/CarrierAccount" }
        "400":
          description: "`INVALID_CONNECTION_REQUEST` or `INVALID_JSON`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` — not in this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: "`CONNECTION_ALREADY_CONNECTED` — this account already has its app."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: "`TELNYX_KEY_REJECTED`, `OUTBOUND_PROFILE_NOT_FOUND`, `CONNECTION_CREATE_REJECTED`, `CONNECTION_NOT_FOUND`, `CONNECTION_WEBHOOK_MISMATCH` (the body carries `webhook_url`), `CONNECTION_HAS_NO_OUTBOUND_PROFILE` or `CONNECTION_INACTIVE`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: "`RATE_LIMITED`."
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "`TELNYX_UNAVAILABLE` — Telnyx did not answer. Nothing changed; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /carrier-accounts/{id}/test:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Test carrier account
      description: |
        Checks the key, the app and its outbound voice profile with Telnyx, and
        re-checks that every number is still in your account. **Places no call.**
        A number Telnyx no longer lists stops being callable until a later test finds
        it again. If Telnyx refuses the API key, the account pauses right away
        (`pause_reason: key_rejected`) and its numbers stop calling, as a refused call
        would pause it; reactivate it once the key works. Requires
        `carrier_accounts:manage`. Limit: 60 per workspace per day.
      operationId: testCarrierAccount
      tags: [Carrier Accounts]
      responses:
        "200":
          description: Test result
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CarrierAccountTestResult" }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` — not in this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: "`RATE_LIMITED`."
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "`TELNYX_UNAVAILABLE` — Telnyx did not answer. Nothing changed; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /carrier-accounts/{id}/reactivate:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Turn a paused account back on
      description: |
        Runs the [test](/api-reference/carrier-accounts/test) first. If it passes, the
        account returns to `untested` and its verified numbers are active again.
        Requires `carrier_accounts:manage`. Shares the test's limit.
      operationId: reactivateCarrierAccount
      tags: [Carrier Accounts]
      responses:
        "200":
          description: Turned back on
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/CarrierAccount" }
                  checks: { type: array, items: { type: object } }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` — not in this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: "`CARRIER_TEST_FAILED` — the body carries `checks`; fix what they show in Telnyx, then try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: "`RATE_LIMITED`."
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "`TELNYX_UNAVAILABLE` — Telnyx did not answer. Nothing changed; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /carrier-accounts/{id}/sync:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Sync numbers
      description: |
        Reads every number in your Telnyx account with your key and brings each one
        into this workspace as an `external` phone number. Calls out from them work
        right away; to have an agent answer calls to one,
        [configure it](/api-reference/carrier-accounts/configure-number). **Changes
        nothing in your Telnyx account and places no call.** Yappr also runs it when you
        choose the Call Control App, on every test and Turn back on, and once a day;
        call it after you buy, port or release numbers in Telnyx. Requires
        `carrier_accounts:manage`.
        Limit: 48 sync runs a day per workspace (continuing a run is free).

        - A new number starts able to call if Telnyx lists it as active and the account
          is not paused. On a number already here, a sync refreshes only what Telnyx
          says (`carrier_state`): its name and agents stay as you set them. It switches
          a number back on only when it switched it off itself (`off_until_active`, once
          Telnyx lists it as active again), never one someone in your workspace switched
          off (`off_by_owner`); see `is_active`.
        - Numbers Telnyx lists as deleted, ported out, or with a failed purchase or
          port are skipped. Any other status than `active` shows as `not_ready`.
        - A number Telnyx no longer lists is marked removed (`carrier_state.state` is
          `telnyx_gone`), never deleted: its call history stays. On a large account, read in parts, that happens only once two
          complete reads in a row miss it.
        - A number another Yappr workspace already uses is not added; it is counted in
          `held_elsewhere`.
        - A large account is read in parts: `complete: false` means sync again, or let
          Yappr read the next part within 5 minutes.
      operationId: syncCarrierAccountNumbers
      tags: [Carrier Accounts]
      responses:
        "200":
          description: Synced. For a large account, one more part read (see `complete`).
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    allOf:
                      - type: object
                        properties:
                          synced_at: { type: string, format: date-time, nullable: true, description: "When the whole account had been read. `null` while `complete` is `false`." }
                          complete:
                            type: boolean
                            description: |
                              `false` while a large account is still being read in parts: sync
                              again, or let Yappr read the next part within 5 minutes. The counts
                              are the run's so far.
                      - type: object
                        properties:
                          seen: { type: integer, description: "Numbers read from your Telnyx account." }
                          added: { type: integer, description: "Numbers new to this workspace." }
                          updated: { type: integer, description: "Numbers already here whose Telnyx details changed." }
                          removed:
                            type: integer
                            description: |
                              Numbers Telnyx no longer lists, now marked removed (`telnyx_gone`). Counted
                              only at the end of a whole read of the account. On an account read in parts, a number is marked
                              removed only when two complete reads in a row miss it, and a read during which
                              Telnyx's list changed removes nothing.
                          not_ready: { type: integer, description: "Numbers Telnyx lists with a status other than `active`." }
                          held_elsewhere:
                            type: integer
                            description: |
                              Numbers in your Telnyx account that another Yappr workspace already uses.
                              They are not added here. One is added by the next sync after that workspace
                              removes it (Remove from this workspace, which keeps its call history there).
                          held_elsewhere_numbers:
                            type: array
                            items: { type: string, example: "+972501234567" }
                            description: Those numbers, up to 100 of them (`held_elsewhere` is the exact count). It never says which workspace holds them.
                          held_elsewhere_details:
                            type: array
                            description: |
                              Why each number of your Telnyx account that the sync kept out is not here: the
                              numbers in `held_elsewhere_numbers` with their reason, then every number in
                              `excluded` as `own_removed`. It never says which workspace holds a number.
                              - `other_workspace` — another Yappr workspace uses it; **Your carrier** shows it as **In use by another workspace**. It comes here at the first sync after that workspace removes it (Remove from this workspace).
                              - `own_removed` — this workspace removed it; **Your carrier** shows it as **Removed from this workspace**, and **Add back** adds it again (the same numbers as `excluded`), unless another workspace has taken it since: then Add back answers `409 NUMBER_ALREADY_REGISTERED` until that workspace removes it.
                              - `pending_release` — another record holds it until it lets it go: a workspace that disconnected the account and keeps it for its call history, another connection of this workspace, or a number Yappr itself holds. It comes here at the first sync after that record lets it go; there is nothing to do here.
                            items:
                              type: object
                              properties:
                                phone_number: { type: string, example: "+972501110000" }
                                reason: { type: string, enum: [other_workspace, own_removed, pending_release] }
                          excluded:
                            type: array
                            description: |
                              Numbers in your Telnyx account that this workspace removed (Remove from this
                              workspace), up to 100. Every sync of this workspace skips them, so another
                              workspace can take them. **Your carrier** lists them as **Removed from this
                              workspace**, with **Add back**:
                              [POST /carrier-accounts/{id}/numbers](/api-reference/carrier-accounts/add-number)
                              with the number (`201`), unless another workspace has taken it since: then
                              `409 NUMBER_ALREADY_REGISTERED` until that workspace removes it. A number Telnyx
                              lists under a new id (it left your account and came back) is synced as usual.
                            items:
                              type: object
                              properties:
                                phone_number: { type: string, example: "+972501110001" }
                                telnyx_number_id: { type: string, nullable: true, example: "1293384261075731499", description: "The number's id in your Telnyx account, when the sync has read it." }
                          batch:
                            type: object
                            description: The counts of the last part read (the whole account, on one that fits in one part).
                            properties:
                              seen: { type: integer, description: "Numbers read from your Telnyx account." }
                              added: { type: integer, description: "Numbers new to this workspace." }
                              updated: { type: integer, description: "Numbers already here whose Telnyx details changed." }
                              unchanged: { type: integer, description: "Numbers already here with nothing new." }
                              restored: { type: integer, description: "Numbers that had left your account and came back." }
                              removed: { type: integer, description: "Numbers marked removed because Telnyx no longer lists them." }
                              not_ready: { type: integer, description: "Numbers Telnyx lists with a status other than `active`." }
                              skipped_stale: { type: integer, description: "Numbers you configured or stopped answering on while the sync was reading them: left as they are." }
                              invalid: { type: integer, description: "Entries Yappr could not read. While any remain, the run removes no number." }
                              dropped: { type: integer, description: "Numbers Telnyx lists as deleted, ported out, or with a failed purchase or port." }
                              missing: { type: integer, description: "Numbers a run read in parts did not find. They are kept, and removed only if the next complete run misses them too." }
                              held_elsewhere: { type: integer, description: "Numbers another record holds (see `held_elsewhere_details`)." }
                              excluded: { type: integer, description: "Numbers this workspace removed, skipped." }
                          run:
                            type: object
                            description: The counts of the whole run so far. `seen`, `added`, `updated`, `removed`, `not_ready` and `held_elsewhere` above are the same numbers.
                            properties:
                              seen: { type: integer, description: "Numbers read from your Telnyx account." }
                              added: { type: integer, description: "Numbers new to this workspace." }
                              updated: { type: integer, description: "Numbers already here whose Telnyx details changed." }
                              unchanged: { type: integer, description: "Numbers already here with nothing new." }
                              restored: { type: integer, description: "Numbers that had left your account and came back." }
                              removed: { type: integer, description: "Numbers marked removed because Telnyx no longer lists them." }
                              not_ready: { type: integer, description: "Numbers Telnyx lists with a status other than `active`." }
                              skipped_stale: { type: integer, description: "Numbers you configured or stopped answering on while the sync was reading them: left as they are." }
                              invalid: { type: integer, description: "Entries Yappr could not read. While any remain, the run removes no number." }
                              dropped: { type: integer, description: "Numbers Telnyx lists as deleted, ported out, or with a failed purchase or port." }
                              missing: { type: integer, description: "Numbers a run read in parts did not find. They are kept, and removed only if the next complete run misses them too." }
                              held_elsewhere: { type: integer, description: "Numbers another record holds (see `held_elsewhere_details`)." }
                              excluded: { type: integer, description: "Numbers this workspace removed, skipped." }
                      - type: object
                        properties:
                          numbers:
                            type: array
                            description: The account's numbers in this workspace after the sync.
                            items: { $ref: "#/components/schemas/PhoneNumber" }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` — not in this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: "`CONNECTION_REQUIRED` — choose the Call Control App first."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: |
            - `TELNYX_KEY_REJECTED` — Telnyx refused the saved key. The account pauses
              (`key_rejected`) and no number changes.
            - `TELNYX_REFUSED_REQUEST` — Telnyx accepted the key but refused to list the
              numbers. Check the key's permissions in Telnyx. The account does not pause.
            - `TOO_MANY_NUMBERS` — the account holds more than 10,000 numbers.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: "`RATE_LIMITED` — 48 sync runs in this workspace today (continuing a run is free)."
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: |
            - `TELNYX_UNAVAILABLE` — Telnyx did not answer. No number changed and
              `last_sync_error` says so; try again.
            - `SYNC_NOT_READY` — Yappr has not switched number syncing on yet
              (`sync_status.ready: false`, readable without syncing). Nothing changed; it
              starts by itself. Choosing the app, a test and Turn back on still do their
              job, and report it in `sync_error`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /carrier-accounts/{id}/numbers:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Add a number
      description: |
        Add a number you own in the connected Telnyx account. Yappr asks Telnyx, with
        your key, whether it is an active number in your account, and adds it only if
        it is. It becomes a phone number of your workspace with `provider: external`:
        use it as `from` on [POST /calls](/api-reference/calls/create), as a campaign's
        number, or as an agent's outbound number. Requires `carrier_accounts:manage`.
        Limit: 50 per workspace per day.

        **Add back.** A number this workspace removed is added back the same way. If
        the workspace still holds it as removed (a sync found it gone from Telnyx, or a
        disconnect kept it for its call history), it is taken back in place on this
        account and the answer is `200` with the same number: its history, name and
        agents stay, and a name or agent you send replaces its own. It comes back
        switched on, unless someone in your workspace had switched it off (it stays
        off) or this account is paused (Turn back on switches it on). A number you
        removed with [Remove a number](/api-reference/carrier-accounts/remove-number)
        has no row left here (only its record in `removed_numbers`), so it is added again (`201`), and the next sync that
        finds it in this workspace stops skipping it, unless another workspace has taken
        it since: then the answer is `409 NUMBER_ALREADY_REGISTERED` until that
        workspace removes it.
      operationId: addCarrierAccountNumber
      tags: [Carrier Accounts]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ExternalNumberCreate" }
      responses:
        "200":
          description: Added back. This workspace still held the number as removed (a sync found it gone from Telnyx, or a disconnect kept it), and it is taken back in place, with its history, name and agents.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/PhoneNumber" }
        "201":
          description: Number added
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/PhoneNumber" }
        "400":
          description: "`INVALID_NUMBER`, `INVALID_NAME`, `INVALID_AGENT` (`outbound_agent_id` is not an id) or `INVALID_JSON`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` — not in this workspace. `AGENT_NOT_FOUND` — `outbound_agent_id` is not an agent in this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: "`CONNECTION_REQUIRED` — choose the app first. `NUMBER_ALREADY_REGISTERED` — the number is already live in this workspace, or in use elsewhere in Yappr, or held by another workspace's lapsed claim that a campaign or past calls still use (that claim is switched off, not removed; support can move the number). A number this workspace removed with Remove a number gets this code only when another workspace has taken it since, until that workspace removes it."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: "`NUMBER_NOT_IN_YOUR_TELNYX_ACCOUNT` or `TELNYX_KEY_REJECTED`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: "`RATE_LIMITED`."
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "`TELNYX_UNAVAILABLE` or `OWNERSHIP_CHECK_UNAVAILABLE`. Nothing was added; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /carrier-accounts/{id}/numbers/{phone_number_id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
      - name: phone_number_id
        in: path
        required: true
        schema: { type: string, format: uuid }
    delete:
      summary: Remove a number from this workspace
      description: |
        Takes any number of the account out of this workspace: one Telnyx still lists,
        one a sync found gone from Telnyx, and one a disconnect kept for its history.
        Agents stop calling from it. Nothing changes in your Telnyx account. This
        workspace's syncs skip it from then on (it is listed in the sync's `excluded`),
        so another workspace connected to the same Telnyx account can take it at its
        next sync; [add it back](/api-reference/carrier-accounts/add-number) to have it
        here again. Its past calls keep their `carrier_account`, `from` and `to`, and its
        spend stays under its id in `GET /billing/consumption?group_by=phone_number`.
        The number has no row here afterwards; its record stays on the account's reads in
        `removed_numbers`, and the answer carries it (`removed`). Requires `carrier_accounts:manage`.
      operationId: removeCarrierAccountNumber
      tags: [Carrier Accounts]
      responses:
        "200":
          description: Removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  id: { type: string, format: uuid }
                  removed:
                    type: object
                    nullable: true
                    description: The number as it was. Keep it if you need to name the number later.
                    properties:
                      id: { type: string, format: uuid }
                      number: { type: string, example: "+972501234567" }
                      friendly_name: { type: string, nullable: true }
                      carrier_account_id: { type: string, format: uuid }
                      telnyx_number_id: { type: string, nullable: true, description: "The number's id in your Telnyx account, when a sync has read it." }
                      inbound_agent_id: { type: string, format: uuid, nullable: true }
                      outbound_agent_id: { type: string, format: uuid, nullable: true }
                      created_at: { type: string, format: date-time }
                      removed_at: { type: string, format: date-time }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` or `NUMBER_NOT_FOUND`. A number segment that is not an id at all is `RESOURCE_ID_INVALID`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            Nothing changed.
            - `NUMBER_STILL_CONFIGURED` — it still answers calls here. [Stop answering here](/api-reference/carrier-accounts/restore-number) first.
            - `NUMBER_IN_CAMPAIGN` — a campaign that has not ended (a draft, scheduled, running or paused one) calls from it. Give the campaign another number, stop it or delete it first.
            - `NUMBER_ON_LIVE_CALL` — a call on it is in progress. Try again when it ends.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /carrier-accounts/{id}/numbers/{phone_number_id}/configure:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
      - name: phone_number_id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Answer a number's calls in Yappr
      description: |
        Moves the number's calls to Yappr. In your Telnyx account, the number's
        connection changes from where its calls go today to the account's Call
        Control App, and its inbound agent answers them. That connection is the only
        setting Yappr changes. Yappr checks the number with Telnyx first, makes the
        change, then reads it back, and remembers the connection it replaced so
        [Stop answering here](/api-reference/carrier-accounts/restore-number) can put
        it back. On a number already configured it changes nothing. Requires
        `carrier_accounts:manage`. Limit: 200 per workspace per day.

        **Ask first.** Send the request once without `confirm` (an empty body): nothing
        changes, and the answer is `400 CONFIRM_REQUIRED` with `warnings`, read from
        your Telnyx account as it answers (voicemail included), and
        `current_connection_name`. What Telnyx does not answer just then comes from the
        last sync, which does not read voicemail. Show them, then send `{"confirm": true}`.

        **What changes:** calls to the number stop reaching the connection it was on,
        and the inbound agent you pick in Yappr answers them instead. Until the number
        has an inbound agent, its callers are turned away.

        **What stays the same:** messaging, the emergency address, caller name (CNAM),
        tags, number-level recording, forwarding on failure, call screening, voicemail,
        and calls out from your own phone system that show this number. Settings of
        these that are on come back in `warnings`.

        **Cost:** Telnyx bills your account for these calls; Yappr bills the agent
        minutes as usual.
      operationId: configureCarrierAccountNumber
      tags: [Carrier Accounts]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                confirm:
                  type: boolean
                  enum: [true]
                  description: |
                    `true` makes the change: it says you have read what changes and want this
                    number's calls to reach Yappr. Leave it out (an empty body, or `{}`) to ask
                    first: nothing changes, and the answer is `400 CONFIRM_REQUIRED` with the
                    `warnings` to show.
      responses:
        "200":
          description: |
            Configured: calls to the number reach Yappr. `carrier_state.state` is `ready`,
            or `paused` while the account is paused because Telnyx refused calls (that
            pause does not stop configuring).
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/PhoneNumber" }
                  changed: { type: boolean, description: "`false` when the number was already on the app: nothing was sent to Telnyx." }
                  warnings:
                    type: array
                    items: { type: string, enum: [forwarding_on_failure, number_recording, call_screening, voicemail, connection_change] }
                    description: |
                      The same list the ask-first answer gave, read again as the change
                      was made: `connection_change` when the number moved, and the
                      settings Yappr left on (`carrier_state.notes` shows those too,
                      except `voicemail`).
        "400":
          description: |
            `CONFIRM_REQUIRED` — the body is not `{"confirm": true}`, so nothing changed.
            This is also the ask-first answer: it carries `warnings`, read from your
            Telnyx account before anything moves (voicemail included; whatever Telnyx
            does not answer just then comes from the last sync, without voicemail), and
            `current_connection_name`, where the number's calls go today. Show them, then
            send `{"confirm": true}`.
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Error" }
                  - type: object
                    properties:
                      warnings:
                        type: array
                        description: |
                          What Configure changes for the number, and its settings in Telnyx that stay on,
                          read from your Telnyx account with your key (from the last sync, without
                          `voicemail`, for whatever Telnyx does not answer just then):
                          - `connection_change` — calls to the number stop reaching the connection they
                            reach today (`current_connection_name`) and come to Yappr. Not listed for a
                            number already on the app, or on no connection.
                          - `number_recording` — Telnyx records these calls too, so each call is recorded,
                            and billed, twice. You can turn it off in Telnyx.
                          - `forwarding_on_failure` — your "forward on failure" setting stays on.
                          - `call_screening` — Telnyx screens callers before Yappr gets the call.
                          - `voicemail` — Telnyx voicemail stays on for the number.
                        items: { type: string, enum: [forwarding_on_failure, number_recording, call_screening, voicemail, connection_change] }
                      current_connection_name: { type: string, nullable: true, example: Office PBX }
        "403": { $ref: "#/components/responses/CarrierAccountsNotEnabled" }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` or `NUMBER_NOT_FOUND` (not a number of this account)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            Nothing changed in Telnyx.
            - `CONNECTION_REQUIRED` — choose the Call Control App first.
            - `NUMBER_REMOVED_FROM_TELNYX` — Telnyx no longer lists the number in your account.
            - `NUMBER_NOT_READY` — its status in Telnyx is not `active` yet.
            - `CARRIER_ACCOUNT_PAUSED` — Telnyx refused the key, or the app is gone. Fix it
              and turn the account back on first. (A pause for refused calls does not stop this.)
            - `NUMBER_ON_YAPPR_PLATFORM` — the number is on a connection Yappr itself uses. Yappr does not move it.
            - `VOICE_NOT_READY` — Yappr cannot answer calls on your numbers right now,
              for example during an update. Try again in a few minutes.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: |
            - `NUMBER_FORWARDS_ALL_CALLS` — Telnyx forwards every call to this number
              elsewhere, so Yappr would never get them. Turn call forwarding off for it in
              Telnyx, then sync. Nothing changed.
            - `NUMBER_HAS_TRANSLATED_NUMBER` — Telnyx delivers its calls as another
              number. Remove the translated number in Telnyx, then sync. Nothing changed.
            - `NUMBER_HAS_TECH_PREFIX` — Telnyx adds a tech prefix to the dialled number
              before the call arrives, so Yappr could not match it. Turn off the tech
              prefix for this number in Telnyx, then sync. Nothing changed.
            - `TELNYX_REFUSED_CHANGE` — Telnyx refused the change. Nothing changed.
            - `TELNYX_REFUSED_REQUEST` — Telnyx accepted the key but refused to read or
              change the number (check the key's permissions). Nothing changed; the
              account does not pause.
            - `TELNYX_KEY_REJECTED` — Telnyx refused the saved key; the account pauses.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: "`RATE_LIMITED` — 200 numbers configured in this workspace today."
          headers:
            Retry-After: { $ref: "#/components/headers/RetryAfter" }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "502":
          description: "`CONFIGURE_NOT_APPLIED` — Telnyx took the change, but the number reads back on another connection. Check it in Telnyx (Numbers → My Numbers), then try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "`TELNYX_UNAVAILABLE` — Telnyx did not answer. Try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      summary: Stop answering a number's calls in Yappr
      description: |
        **Stop answering here.** Puts the number back on the connection it was on
        before it was configured (`carrier_state.previous_connection_name`), or on no
        connection if it had none, so its calls go where they went before. Its agents
        stay assigned and calls out from it keep working. If its connection was
        already changed away from the app in Telnyx, Yappr records that and changes
        nothing (`changed: false`). Yappr reads the number back before recording the
        change. Requires `carrier_accounts:manage`. It runs even while Yappr has
        switched carrier accounts off for the workspace (never `403
        CARRIER_ACCOUNTS_NOT_ENABLED`), so a line is never stranded on Yappr's app.
      operationId: restoreCarrierAccountNumber
      tags: [Carrier Accounts]
      responses:
        "200":
          description: Its calls go back to where they went before (`carrier_state.state` is `not_configured`)
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { $ref: "#/components/schemas/PhoneNumber" }
                  changed: { type: boolean, description: "`false` when the number was no longer on the app: nothing was sent to Telnyx." }
        "404":
          description: "`CARRIER_ACCOUNT_NOT_FOUND` or `NUMBER_NOT_FOUND`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            - `PREVIOUS_ROUTING_GONE` — Telnyx refused to put the number back, usually
              because that connection no longer exists. Its calls still reach Yappr.
              Pick a connection for it in Telnyx (Numbers → My Numbers), then sync.
            - `CONNECTION_REQUIRED` — the account has no Call Control App.
            - `NUMBER_REMOVED_FROM_TELNYX` — Telnyx no longer lists the number.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: |
            - `TELNYX_KEY_REJECTED` — Telnyx refused the saved key; the account pauses.
              Change the number's connection in Telnyx yourself, or fix the key and try again.
            - `TELNYX_REFUSED_CHANGE` — Telnyx refused the change. Nothing changed.
            - `TELNYX_REFUSED_REQUEST` — Telnyx accepted the key but refused the request
              (check the key's permissions). Nothing changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "502":
          description: "`RESTORE_NOT_APPLIED` — Telnyx accepted the change, but the number still reads back on the app, so its calls still reach Yappr. Nothing was recorded; try again in a minute."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "`TELNYX_UNAVAILABLE` — Telnyx did not answer. Nothing changed; try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /calls:
    get:
      summary: List calls
      operationId: listCalls
      tags: [Calls]
      description: |
        Requires `calls:read`, or `calls:metrics`: a `calls:metrics` key (without `calls:read`)
        reads each call as metrics - ids, agent, direction, status, moments, duration, cost,
        disposition, `ended_by`, `failure` and `analysis` - with `from`, `to`, `metadata`
        and `transfer_target` null, `lead` as `{id}`, `recording_url` left out
        and `personal_data_withheld: true`. It may not filter by `caller`, `callee`, `search` or
        `lead_id` (403 INSUFFICIENT_SCOPE).
      parameters:
        - in: query
          name: limit
          schema: { type: integer, default: 20, maximum: 100 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
          description: >
            Count from the top of the list. Send this or cursor, not both - both together is
            400 CALLS_QUERY_INVALID, because applying one of them silently is how a paging loop
            reads the same rows twice.
        - in: query
          name: cursor
          schema: { type: string }
          description: >
            Continue exactly where the last page stopped. Opaque; take it from
            pagination.next_cursor, which every page carries. This list grows while it is being
            read, so an offset silently repeats or skips rows and a cursor does not. A cursor
            this endpoint did not issue - one built by hand, edited, or taken from GET
            /deliveries - is 400 CALLS_CURSOR_INVALID rather than a silent first page: cursors
            are signed. While paging by cursor, pagination.total counts the calls still ahead.
        - in: query
          name: agent_id
          schema: { type: string, format: uuid }
          description: >
            Only calls this agent took or placed, by the id GET /agents returns. Anything that is
            not an id is 400 CALLS_QUERY_INVALID naming the parameter, rather than reaching the
            uuid column unchecked, and an id that is not an agent in this workspace is 404
            AGENT_NOT_FOUND (it was CALL_AGENT_UNKNOWN) rather than an empty page that reads as "no calls".
        - in: query
          name: status
          schema: { type: string, enum: [pending_connection, ringing, in_progress, completed, failed, no_answer, transferred, dnc_blocked] }
          description: >
            Filter by call status. pending_connection is a browser session minted with POST /calls
            {type: web} that nobody has connected to yet. Anything outside the list is 400 CALLS_QUERY_INVALID naming
            the statuses calls really have, rather than reaching the enum column unchecked.
        - in: query
          name: direction
          schema: { type: string, enum: [inbound, outbound, web_call] }
        - in: query
          name: callee
          schema: { type: string }
          description: "Filter by callee (destination) phone number, matched in E.164 when written with its country code (a bare + included); an Israeli number written +972…, 972… or 05… finds the same calls, and other digits (an extension, a number without its country code) are matched exactly as sent. Useful for counting prior attempts to a specific lead — e.g. retry-throttle logic: `?agent_id=X&callee=+972Y&from=TODAY` then read `data.length` directly."
          example: "+972501234567"
        - in: query
          name: caller
          schema: { type: string }
          description: "Filter by caller (source) phone number, read the same way as callee."
          example: "+972551234567"
        - in: query
          name: ab_variant
          schema: { type: string, enum: [a, b] }
          description: |
            Return only calls answered or placed by one side of a number's A/B
            test. `a` is the number's own agent, `b` the second agent. Calls on
            a number with no split carry no variant and are excluded by this
            filter.
        - in: query
          name: disposition
          schema: { type: string }
          description: >
            Only calls that ended with this outcome, by the disposition's label exactly as
            GET /dispositions returns it. A label no disposition in this workspace carries is
            404 CALL_DISPOSITION_UNKNOWN rather than an empty page.
          example: Interested
        - in: query
          name: disposition_id
          schema: { type: string, format: uuid }
          description: >
            The same outcome filter by id. Send this or disposition, not both. An id that is
            not a disposition in this workspace is 404 CALL_DISPOSITION_UNKNOWN rather than an
            empty page.
        - in: query
          name: source
          schema: { type: string, enum: [test, shared_link, api, phone_inbound, phone_outbound] }
          description: >
            Only calls that came from here. test is a rehearsal you started yourself (the agent's
            Test button, in the browser or by phone); shared_link is a call made through
            a shared link; api is a browser session this API minted; phone_inbound and
            phone_outbound are the two phone legs, real calls only - a test call dialled from the
            dashboard is returned by source=test and not by source=phone_outbound. Anything else is
            400 CALLS_QUERY_INVALID. A call recorded before its origin was written reads "unknown"
            and cannot be filtered for.
        - in: query
          name: carrier_account_id
          schema: { type: string, format: uuid }
          description: >
            Only calls on this carrier account - your own Telnyx account, as GET
            /carrier-accounts returns it: every call it signed for, placed from or answered
            on one of its numbers, outbound and inbound alike (a refused dial included). Needs carrier_accounts:read,
            like the carrier_account on each call - 403 INSUFFICIENT_SCOPE without it. Anything
            that is not an id is 400 CALLS_QUERY_INVALID; an account that is not in this
            workspace is 404 CARRIER_ACCOUNT_NOT_FOUND rather than an empty page.
        - in: query
          name: provider
          schema: { type: string, enum: [external, telnyx, none] }
          description: >
            Only calls on this carrier, as each call's `provider` says: external - your own Telnyx
            account (signed for a carrier account, or placed from one of its numbers); telnyx - a
            number bought from Yappr, or a SIP endpoint; none - a browser call, which has no phone
            side (`provider` null). Needs no scope beyond calls:read, like `provider` itself.
            Anything else is 400 CALLS_QUERY_INVALID.
        - in: query
          name: search
          schema: { type: string, minLength: 2, maxLength: 100 }
          description: >
            What the dashboard's Call Logs search box takes, in one parameter. The start of a call
            id - 8 or more of its hex characters, with dashes where an id has them, so the 8 the
            dashboard shows are enough - finds the calls whose id starts with it. A phone number
            finds the calls with it at either end, read the way callee and caller read it. Anything
            else is part of an agent's or a lead's name, case-insensitive; a lead deleted since does
            not count. A lead's name is searched only for a key with leads:read, the scope that
            reads it; for any other key a name matches agents alone. Digits that could be both
            (0501234567) are searched both ways. A name more than 300 agents and leads share
            (agents alone, without leads:read) is 400 CALLS_QUERY_INVALID, as is a search under 2
            or over 100 characters.
          example: 4d1d9ad0
        - in: query
          name: lead_id
          schema: { type: string, format: uuid }
          description: >
            Only calls with this lead, by the id GET /leads returns - the one way to find a browser
            call attached to a lead, which has no number at either end. Anything that is not an id
            is 400 CALLS_QUERY_INVALID; a lead that is not in this workspace, or was deleted, is
            404 NOT_FOUND rather than an empty page.
        - in: query
          name: from
          schema: { type: string, format: date-time }
          description: >
            Return calls created on or after this ISO 8601 timestamp - a date, or a date and time
            with Z or an offset. Any other shape (2026, Sep 1, 2026/09/01) and a day its month does
            not have - 2026-09-31, the month-end a report script guesses - is 400
            CALLS_QUERY_INVALID rather than a failed read or a window silently rolled forward to
            October 1. URL-encode a positive offset's + as %2B: a query string reads a bare + as
            a space, and the refusal says so when that is what happened.
        - in: query
          name: to
          schema: { type: string, format: date-time }
          description: >
            Return calls created on or before this timestamp. Validated the same way as from. A
            date-only value covers that whole day (UTC): to=2026-08-31 ends at
            2026-08-31T23:59:59.999999Z, so from=2026-08-01&to=2026-08-31 is all of August.
        - in: query
          name: updated_since
          schema: { type: string, format: date-time }
          description: >
            Every call that has CHANGED at or after this timestamp, whatever its created_at.
            This is the filter an incremental sync wants: status, ended_at, duration_seconds,
            cost_cents, the matched lead, the disposition and the whole analysis object all
            settle after the row is created - an analysis that never landed included, which is
            written onto the call as failed / analysis_unavailable within five minutes of the
            ten-minute mark (for a workflow agent's call, once no retry is still due) - so a
            sync windowed on created_at reads each call
            once, at its youngest and emptiest, and never learns that any of it landed. Record
            the time before a run starts, ask the next run from a few minutes before it, and
            upsert by id keeping the newer updated_at: a change is stamped when its write starts
            and readable only once it finishes, so windows that merely touch can skip one.
      responses:
        "200":
          description: List of calls
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string, format: uuid }
                        agent_id: { type: string, format: uuid }
                        agent:
                          type: object
                          nullable: true
                          description: "The agent behind agent_id, read with the call, so its name stays readable from a list after the agent is archived (GET /agents/{id} answers 404 for an archived agent). Always these three members, whatever the key's scopes; GET /calls/{id} embeds the whole agent for a key with agents:read. Null on a call with no agent."
                          required: [id, name, archived_at]
                          properties:
                            id: { type: string, format: uuid }
                            name: { type: string, nullable: true }
                            archived_at: { type: string, format: date-time, nullable: true, description: "When the agent was archived; null while it is not." }
                        from: { type: [string, "null"], description: "The caller, in E.164. On a call that arrived on a SIP endpoint it is whatever your phone system sent as the caller, which may not be a phone number, and `null` when the caller ID was only a username-and-password trunk's own username. An empty string on a browser call." }
                        to: { type: [string, "null"], description: "The number dialled, in E.164. `null` on every call that arrived on a SIP endpoint, and sip_endpoint_id names the endpoint: a SIP address endpoint's address is its credential, and what a username-and-password trunk's call dialled shows in the dashboard's call log. An empty string on a browser call." }
                        direction: { type: string }
                        status: { type: string }
                        started_at: { type: string, format: date-time, description: "When the call was placed - created_at on a browser session that never recorded a start of its own. Never null." }
                        ended_at: { type: string, format: date-time, nullable: true, description: "When the call ended. Never before started_at." }
                        recording_started_at: { type: string, format: date-time, nullable: true, description: "When the call's recording began, as Get call reads it: a transcript's start and end are milliseconds from here. Null on a browser call, on a call with no recording yet, and on older calls recorded before the field was added." }
                        duration_seconds: { type: integer, nullable: true, description: "Connected time in whole seconds, as Get call reads it: null while the call runs and on every call that was never answered (nobody picked up, or no browser connected, and no answer recorded); a whole number, 0 included, on every call that was - a call with an answered_at was answered, whatever stage its failure names." }
                        cost_cents:
                          type: integer
                          nullable: true
                          description: >
                            What this one call consumed from the workspace's credits, in credits (one
                            credit is one cent) - the same number Get call returns. 0 for a call that
                            ended without a charge (failed, not answered, blocked, or completed with no
                            connected time); null only while the call is still settling - never 0 for
                            an unsettled call. cost_status says which. Summing this list is how a spend
                            report is built; workspace aggregates by day, product or agent live in
                            GET /billing/consumption.
                        cost_status:
                          type: string
                          enum: [charged, not_charged, pending]
                          description: >
                            Whether cost_cents is final. charged - the recorded charge. not_charged -
                            the call ended without billable time, or ended more than 24 hours ago with
                            no charge recorded, and cost_cents is 0. pending - the call is live or
                            ended less than 24 hours ago and its charge has not been recorded yet, so
                            cost_cents is null; come back. Only pending is worth polling, and it never
                            lasts more than a day after a call ends.
                        created_at: { type: string, format: date-time }
                        updated_at:
                          type: string
                          format: date-time
                          description: >
                            When this row last changed - what ?updated_since= bounds. Revoking the
                            call's recording links and deleting its lead move it too. Calls
                            recorded before this field existed carry the last moment they can be
                            proved to have changed, so it is never null.
                        source:
                          type: string
                          enum: [test, shared_link, api, phone_inbound, phone_outbound, unknown]
                          description: >
                            Where the call came from. A rehearsal and a shared-link call used to be the same row -
                            both web_call, both with empty from and to - so testing spend could not be told apart
                            from the link that was handed out. "unknown" is a call recorded before its origin was
                            written down, and is the one value ?source= refuses.
                        provider:
                          type: string
                          enum: [external, telnyx]
                          nullable: true
                          description: >
                            Whose carrier the phone side ran on, in the words GET /phone-numbers uses for the
                            call's number. external - your own Telnyx account (a number with provider external):
                            Telnyx billed you for the phone minutes, and cost_cents is Yappr's charge beside them.
                            telnyx - Yappr's own carrier: a number bought from Yappr, or a SIP endpoint. null - a
                            browser call, which has no phone side.
                        carrier_account:
                          type: object
                          nullable: true
                          description: >
                            The carrier account an external call ran on - the account Telnyx signed the call
                            for, or its from-number's account when no signed event arrived. null on every other
                            call, and for a key without carrier_accounts:read (provider still says external). An
                            account removed since keeps its id, with name, provider and status null. The same
                            four fields as a number's carrier_account on GET /phone-numbers.
                          properties:
                            id: { type: string, format: uuid }
                            name: { type: string, nullable: true }
                            provider: { type: string, enum: [telnyx], nullable: true }
                            status: { type: string, enum: [untested, active, paused], nullable: true }
                        carrier_call_id:
                          type: string
                          nullable: true
                          description: >
                            On an external call only (absent on every other call): the call_control_id Telnyx
                            gave the call on your own Telnyx account - the id to find it by in your Telnyx
                            records and its call debugging. null when the dial never got one (refused before
                            Telnyx answered), and null for a key without carrier_accounts:read.
                          example: "v3:u5OA0mKfWkqg2Gfyv1c0g8ukRZ3n1R6f2sKnH4Qj1i1aX8Pz9g"
                        shared_link_id:
                          type: string
                          format: uuid
                          description: >
                            The shared link this call came through. Absent, not null, on every other kind of call.
                        sip_endpoint_id:
                          type: string
                          format: uuid
                          description: >
                            The SIP endpoint this call arrived on - a phone_inbound call from your own phone
                            system. Such a call's `to` is null (see `to`). Absent, not null, on every other
                            kind of call.
                        ended_by:
                          type: string
                          enum: [caller, agent, system, operator, unknown]
                          nullable: true
                          description: "Who ended the call. caller - the far end hung up first, or the browser closed the connection (the End button on a browser test call included); a browser call whose failure code is caller_left always reads caller. agent - the agent chose to end it, through its end-call tool, its flow End step or its closing line. system - Yappr ended it, on the silence timeout, the maximum-duration cap, an answering machine, a fault, the watchdog closing a stuck call, or a browser session that expired before anyone connected. operator - someone ended the call from outside it on purpose: the End button on a dashboard phone test call, POST /calls/{id}/end or the session's cancel_url on a browser session nobody opened, or Yappr stopping a stuck call. A call ended this way has no failure member. unknown - the carrier reported the ending without saying which side dropped the call. null - nothing recorded one. A transfer records nothing at the handoff itself, because the leg stays up and whoever hangs up afterwards is the answer; the value is already resolved for the call direction. First-write-wins, so a specific value is never overwritten by a later generic one."
                        disconnect_reason:
                          type: string
                          nullable: true
                          description: "Short human-readable label for why the call ended, meant for display rather than branching - for example Completed, No answer, Busy, Call rejected, Cancelled, Caller inactive, Max duration reached, Voicemail detected, Answering machine detected, Ended by operator, Ended by the platform: stuck call, Failed, or one of the Transfer ... labels when a handoff never connected, or \"Your Telnyx account refused the call…\" when your own Telnyx account refused a call from one of its numbers. Wording may change and labels are added, so treat it as text. First-write-wins. Null when nothing was recorded, and when what was recorded is not one of these labels - an internal note never reaches this field."
                        transferred_at:
                          type: string
                          format: date-time
                          nullable: true
                          description: "When the call was handed off to another party. A phone number, and an extension endpoint's new call through your extension, leave the call with status 'transferred'. A SIP REFER hand-off over a username-and-password trunk ends 'completed' with this time set."
                        transfer_target:
                          type: string
                          nullable: true
                          description: "The number the call was transferred to (E.164), or, for a hand-back to your own phone system, the SIP address with any password and any header part (the part after a ?) removed. The extension before the @ stays."
                        metadata:
                          type: object
                          description: >
                            The metadata you attached at POST /calls (phone or web), exactly as Get call
                            returns it, so a sync can match its own ids from the list; {} when none was
                            attached. Internal bookkeeping (retry counters, carrier ids, error text and when
                            it was recorded, the browser session) is removed. Some keys the platform adds do
                            stay, and this is not an exhaustive list: ab_variant and ab_variant_fallback when
                            a split picked the agent, share_link_id on a call from a share link, agent_id on a
                            test call started from the dashboard, queued, queue_id and queue_wait_seconds on a
                            call that waited for a free line, workflow_request_id on a call started from a
                            call request, and, on a call that spoke, timezone, timezone_source and
                            timezone_unconfirmed (the zone the agent's clock ran in; a timezone key you attach
                            yourself is never replaced). Name your own keys so they cannot collide with these.
                        recording_url:
                          type: string
                          description: "Signed URL for the call recording on the API host. Opens directly in a browser or audio player — answers 200 with the audio itself (HEAD and Range supported). No additional authentication required. It lasts 7 to 8 days (`exp`) and stops opening when the call's links are revoked (POST /calls/{id}/recording/revoke); read the call again for a current one. Absent when the call has no recording the link can serve."
                        tool_calls_count:
                          type: integer
                          description: "Number of LLM-decided tool invocations during the call. Always 0 for flow-agent calls — see flow_tool_fires_count instead."
                        flow_steps_count:
                          type: integer
                          description: "Number of nodes visited during the call. 0 for prompt-agent calls. Same node visited twice counts twice."
                        ab_variant:
                          type: string
                          enum: [a, b]
                          description: "Which side of the number's A/B test took this call - `a` the number's own agent, `b` the second one. Absent on calls placed or answered by a number with no split."
                        flow_tool_fires_count:
                          type: integer
                          description: "Number of tool_call nodes that fired during the call. 0 for prompt-agent calls."
                        disposition:
                          nullable: true
                          description: "Full Disposition object. Present only when a disposition has been assigned to the call."
                          allOf:
                            - $ref: "#/components/schemas/Disposition"
                        lead:
                          nullable: true
                          description: "Full Lead object. Present only when a matched lead exists for this call. A key without `leads:read` reads `{id}` only."
                          allOf:
                            - $ref: "#/components/schemas/Lead"
                        failure:
                          description: >
                            Why the call did not complete, classified exactly as Get call classifies it.
                            Absent on a call that completed, so check for the member rather than a value
                            inside it. disconnect_reason only repeats the status on a failure; failure.code
                            is the cause.
                          allOf:
                            - $ref: "#/components/schemas/CallFailure"
                        analysis:
                          description: >
                            Where the call's post-call analysis stands, classified exactly as Get call
                            classifies it. Always present, so a sync can page this list and act on each
                            row without a second request per call.
                          allOf:
                            - $ref: "#/components/schemas/CallAnalysis"
                        personal_data_withheld:
                          type: boolean
                          description: >
                            Present, and true, only on a call read by a `calls:metrics` key that does
                            not hold `calls:read`: the people on the call and what they said were held
                            back. Absent on every other read.
                  pagination:
                    type: object
                    properties:
                      total:
                        type: integer
                        description: >
                          Calls matching the filters. While paging by cursor this counts the calls
                          still ahead of the cursor, not the size of the whole list.
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean }
                      next_cursor:
                        type: [string, 'null']
                        description: >
                          The last row of this page, as the opaque string that continues it. On
                          every page, including one asked for with no paging parameter at all, so
                          moving a job from offset paging to cursor paging costs no extra request.
                          Null on the last page.
        "400":
          description: >
            `CALLS_QUERY_INVALID` — the request carried a query parameter this list does not
            apply, sent a known one with no value at all (`?agent_id=`, which would have
            returned every call), sent both `disposition` and `disposition_id`, sent both
            `cursor` and `offset`, sent an `agent_id`, `disposition_id`, `lead_id` or
            `carrier_account_id` that is not an id, sent a `search` under 2 or over 100 characters
            or one more than 300 agents and leads share by name (leads count only for a key with
            leads:read), or
            sent a `from`, `to` or `updated_since` that is not a real timestamp, sent a `limit` or
            `offset` that is not a whole number, or sent an `offset` past the last matching call
            (it used to be a 500). The body names
            the offending parameters and the accepted set. Also `CALLS_CURSOR_INVALID` when the
            `cursor` was not issued by this endpoint, and `INVALID_AB_VARIANT` when `ab_variant`
            is anything but `a` or `b`.
            A parameter sent twice is refused too (CALLS_QUERY_INVALID): only one of the values would have been used.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "403":
          description: >
            `INSUFFICIENT_SCOPE` — the key holds neither `calls:read` nor `calls:metrics`, sent
            `carrier_account_id` without `carrier_accounts:read`, or holds only `calls:metrics` and
            filtered by `caller`, `callee`, `search` or `lead_id`.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: >
            `CALL_DISPOSITION_UNKNOWN` — the `disposition` label or `disposition_id` is not a
            disposition in this workspace. `AGENT_NOT_FOUND` — the `agent_id` is not an agent
            in this workspace (it was `CALL_AGENT_UNKNOWN`; every route answers a missing agent this way).
            `CARRIER_ACCOUNT_NOT_FOUND` — the `carrier_account_id` is not a carrier account in this
            workspace. `NOT_FOUND` — the `lead_id` is not a lead in this
            workspace. A filter that would match nothing is refused rather than answered with an
            empty page.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "503":
          description: >
            `CALLS_LIST_TIMEOUT` — the list could not be read inside its own time budget (about 15
            seconds), so it stopped rather than leave the request hanging until the platform cut
            it off. Nothing was changed. Send the same request again after the `Retry-After`
            seconds, or narrow it with `from` and `to` or a smaller `limit`. Every answer from
            this list also carries a `Server-Timing` header with the time each step took.
          headers:
            Retry-After:
              description: Seconds to wait before sending the same request again.
              schema: { type: integer, example: 5 }
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

    post:
      summary: Create outbound call, or mint a web-call session
      description: >
        Place an outbound phone call using a Yappr agent (default), or — with `type: "web"` — mint a
        short-lived browser session token for an in-browser voice call via the `@goyappr/client` SDK.
        A phone call needs a balance above the billing floor and an active Yappr phone number; if server
        capacity is fully utilized it is queued automatically and returns HTTP 202. A web session does not
        place a call and is not queued — it returns a token the visitor's browser uses to connect.
        Minting always succeeds for a reachable active agent, and the response's `protocol` says which
        exchange the browser must speak: `offer` for the one-shot connection most agents use, or
        `call_request` when the agent's published workflow runs before-call steps or has follow-ups
        (After steps) - a one-shot connection has no workflow run for either, so a follow-up on it would
        never start - which the browser creates, polls and then starts. Follow `protocol` rather than
        inferring it from the workflow. A web channel alongside before-call steps publishes and works;
        only an older client that ignores `protocol` and sends a one-shot offer anyway is refused, with
        `409 workflow_preparation_required`, and its token is not spent.
      operationId: createCall
      tags: [Calls]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                type:
                  type: string
                  enum: [phone, web]
                  default: phone
                  description: |
                    Call channel. Omit or `"phone"` places a normal outbound phone call (requires `to` and `from`).
                    `"web"` mints a short-lived, single-use browser session token instead of dialing — no call is
                    placed until the visitor's browser connects via the `@goyappr/client` SDK. For `"web"`, only
                    `agent_id` is used (`to`/`from` are ignored) and the 201 response is a session object.
                agent_id:
                  type: string
                  format: uuid
                  description: |
                    Optional for a phone call, required for `type: "web"`.

                    Omit it and the `from` number decides: its outbound agent
                    places the call, or its `outbound_split` picks between two
                    agents. An explicit `agent_id` always wins over a split. If
                    the number has no agent attached, the call is refused with
                    `422 AGENT_NOT_RESOLVED` — "Attach an agent to this phone
                    number or send agent_id" — and nothing is queued or dialed.

                    When a split resolves the agent, the call record carries
                    `metadata.ab_variant` (`"a"` or `"b"`); retrying with the
                    same `Idempotency-Key` resolves to the same agent.
                to:
                  type: string
                  example: "+972501234567"
                  description: |
                    Destination phone number in strict E.164 format.

                    **Validation rules** (enforced at API and DB layers):
                    - Must match `^\+[1-9][0-9]{7,14}$` — leading `+`, 8–15 digits, no spaces or dashes.
                    - Israeli numbers (`+972…`) must be exactly 12 or 13 characters total (`+972` followed by an 8-digit landline or 9-digit mobile).
                    - Calls can only be placed to Israeli numbers (`+972`); any other country is refused.
                    - Must differ from `from`.

                    Malformed numbers are rejected with `400 invalid_destination` — no row is written to the database, no carrier dial is attempted, and no capacity is consumed.
                from:
                  type: string
                  example: "+972551234567"
                  description: |
                    An active number in your workspace, in strict E.164 format: bought from Yappr, or registered from your own Telnyx account on a [carrier account](/api-reference/carrier-accounts/add-number) — then the call runs on your Telnyx account, which bills you for its phone minutes — or the `phone_system` number of an extension endpoint with [outbound calls](/concepts/sip-trunks#outbound-calls-through-the-extension) on, when the call goes out through your own phone system on your phone plan. Same validation rules as `to`. Malformed numbers are rejected with `400 INVALID_FROM_NUMBER`.
                variables:
                  type: object
                  additionalProperties:
                    type: string
                  description: "Key-value pairs injected as template variables into the agent's system prompt (e.g. {{LeadName}})."
                  example: { "LeadName": "David Cohen", "OrderNumber": "ORD-1234" }
                metadata:
                  type: object
                  description: |
                    Arbitrary key-value data attached to the call log record. Forwarded in real-time to every tool webhook as `call_metadata` so tool receivers (Make.com scenarios, n8n workflows, custom edge functions) can route updates back to the right CRM record without a secondary GET /calls/{id} fetch. Ideal for carrying IDs like appointment_id, contact_id, calendar_id. Not injected into the agent's system prompt.

                    **Flow agents — contract callout.** Flow agents can reference `{{metadata.<key>}}` tokens inside `args_template` values. Missing keys render to an empty string at runtime with no save-time or dispatch-time warning, so always check the agent's `flow_config.metadata.custom_metadata_keys` before placing the call and ensure every key in that array is supplied here.

                    **Reserved keys.** The five platform-supplied tokens (`id`, `direction`, `agent_number`, `user_number`, `agent_name`) are emitted by the platform at call start and cannot be overridden — using any of them as a key here is a `400 INVALID_METADATA_RESERVED_KEY`. Pick a different name for your custom field. `recording_started_at` and `recording_ended_at` are written by Yappr from the call's recording; a value sent under either name is dropped.
                  example: { "appointment_id": "ghl-apt-abc123", "calendar_id": "ghl-cal-xyz789", "contact_id": "ghl-contact-def456" }
                allowed_origins:
                  type: array
                  items: { type: string }
                  description: "Web sessions only (`type: web`). Optional list of browser origins permitted to use the minted session (e.g. `https://app.example.com`)."
                  example: ["https://app.example.com"]
                lead_id:
                  type: string
                  format: uuid
                  description: |
                    Web sessions only (`type: web`). Attaches the call to one of this workspace's leads:
                    the call carries that `lead`, and what the post-call pass learns is written to it.
                    Not an id is `400`; not a lead in this workspace, or a deleted one, is `404`. An
                    agent whose workflow runs before-call steps (`protocol: "call_request"`) cannot
                    take one: its call is created by the call request, which has no lead, so the mint
                    is `422 WEB_LEAD_UNSUPPORTED` and no token is issued.
                workflow_revision_id:
                  type: string
                  format: uuid
                  nullable: true
                  description: |
                    Workflow agents only. Places this call on one exact published version of the
                    agent instead of whichever version is current when the call goes out. Use it
                    when a batch must stay on the version you tested.

                    Omit it (or send `null`) to use the agent's current published version.

                    Sending a value for an agent that is not a workflow agent is a
                    `422 WORKFLOW_PIN_INVALID`. A version id that this agent does not own is
                    rejected later, as `404 WORKFLOW_AGENT_UNAVAILABLE` — the same answer as an
                    agent that is not reachable — so take the id from the `data[].id` of
                    `GET /agents/{id}/workflow/versions` instead of guessing it.
      responses:
        "201":
          description: |
            Phone call initiated (`type: phone`), or web-call session minted (`type: web`).
          content:
            application/json:
              schema:
                oneOf:
                  - title: Phone call initiated
                    type: object
                    properties:
                      id: { type: string, format: uuid, description: "call_log ID" }
                      status: { type: string }
                      agent_id: { type: string, format: uuid }
                      to: { type: string }
                      from: { type: string }
                      created_at: { type: string, format: date-time }
                  - title: Web-call session minted
                    description: >
                      No call is placed yet — the browser connects with the token. Once the
                      call ends it runs the same post-call pipeline as a phone call: transcript,
                      summary, recording, and disposition are written to the call record (fetch
                      via `GET /calls/{id}` using the returned `getId()`/call id), and the agent's
                      configured post-call webhook fires with the same payload.
                    type: object
                    properties:
                      type: { type: string, example: "web"  }
                      call_id:
                        type: string
                        format: uuid
                        nullable: true
                        description: |
                          The call this session will be. GET /calls/{id} answers for it at once, with
                          `status: "pending_connection"` until a browser connects; the same id then runs
                          the call. Unused, it settles `no_answer` / `failure.code: "session_expired"`
                          as soon as it is read after `expires_at` (GET /calls/{id}, GET /calls, the
                          export), otherwise at the next five-minute sweep. `null` when `protocol` is
                          `call_request`: that call is created when the request starts, and the request
                          reports its id.
                      token:
                        type: string
                        description: "Single-use session credential (prefix `wcs_`). Hand to the browser; the SDK presents it as the `x-yappr-web-token` header. Never exposes your API key."
                        example: "wcs_9g6-_LauzTgtv8nU31p8un0xk6H-cyUmqD1NEov_0Pk"
                      expires_at: { type: string, format: date-time, description: "Token expiry: 5 minutes after mint for an `offer` session, 15 minutes for a `call_request` session, which has to outlast the steps it waits for." }
                      cancel_url:
                        type: string
                        description: |
                          Where to discard this session when nobody will use it, for either `protocol`.
                          `POST` with the token as `x-yappr-web-token` and no body (or `{}`): the token is spent so no
                          browser can use it, and an `offer` session's call settles at once exactly as
                          POST /calls/{id}/end settles it: `ended_by: operator`, `disconnect_reason: "Ended by
                          operator"`, cost 0 and no `failure` member. Answers `200 {"status": "cancelled" | "expired", "call_id"}`
                          (`call_id` null for a `call_request` session), `409 WEB_SESSION_ALREADY_USED` once a
                          browser has used the token, `400 WEB_SESSION_CANCEL_INVALID` for a body with any field
                          in it or one that is not JSON, `401` for an unknown token. Takes the token, never the
                          secret key. A browser that still presents a cancelled token is refused
                          `403 WEB_SESSION_CANCELLED`, on the offer and on the call request alike.
                        example: "https://api.goyappr.com/web-call/cancel"
                      agent_id: { type: string, format: uuid }
                      agent_name: { type: string }
                      connection:
                        type: object
                        description: |
                          Everything the browser SDK needs — pass straight to
                          `startSession({ token, connection })`. These are the browser
                          data-plane URLs plus one **publishable** key, the same class of
                          key as a Stripe publishable key: it identifies the data plane,
                          it grants nothing on its own, and the browser is where it is
                          meant to live. The per-call credential is `token` above.
                          A secret-class key is never returned here: the mint refuses the
                          whole request with `503 WEB_CALL_UNAVAILABLE` rather than substitute
                          one. A deployment with no data-plane key at all still mints the
                          session, with `api_key` as `null`.
                        properties:
                          host:
                            type: string
                            description: >
                              The origin the four URLs below live on - named rather than left to be
                              parsed out of them, so a frontend can pin it, proxy it or allow it
                              through a content policy deliberately. It is the API host: these are
                              browser routes on api.goyappr.com that take the session token (or a call
                              request's capability), never the secret key.
                            example: "https://api.goyappr.com"
                          base_url: { type: string, description: "Browser data-plane base the three URLs below are built on." }
                          web_call_url: { type: string, description: "Where the browser posts its SDP offer." }
                          call_requests_url: { type: string, description: "Where the browser creates and polls a call request, when `protocol` is `call_request`." }
                          turn_credentials_url: { type: string, description: "Where the browser fetches short-lived ICE/TURN credentials." }
                          api_key:
                            type: [string, 'null']
                            description: "Publishable data-plane key, safe in a browser. Never a secret or service-role key; `null` when the deployment has none."

        "200":
          description: |
            Call blocked because the destination is on the company's Do-Not-Call list.
            A `call_logs` row is recorded with `status: "dnc_blocked"` (so analytics +
            webhooks pick it up), but no carrier leg is established and no minutes
            are charged. To allow this number again, remove its DNC entry via
            `DELETE /do-not-call/{id}`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  call_id: { type: string, format: uuid, nullable: true }
                  status: { type: string, example: "dnc_blocked"  }
                  agent_id: { type: string, format: uuid }
                  to: { type: string }
                  from: { type: string }
                  message: { type: string }
                  dnc_reason: { type: string, nullable: true }
                  started_at: { type: string, format: date-time }
                  ended_at: { type: string, format: date-time }
        "202":
          description: |
            Accepted, but no call has been placed yet. Four shapes share this status, and they
            are told apart by the fields they carry:

            - **Queued at capacity.** All lines are busy; the call is placed automatically when
              one frees up. Carries `queue_position`.
            - **Accepted for a workflow agent.** Every outbound call on a workflow agent is
              accepted first and placed afterwards, so this is the normal success response for
              those agents — not an overflow. Carries `request_id`: poll it with
              `GET /call-requests/{id}`, and stop the call before it goes out with
              `POST /call-requests/{id}/cancel`. `status` is `scheduled` when the workspace's
              calling window is not open yet, `queued` otherwise. An identical retry sent with
              the same `Idempotency-Key` returns this same body again instead of accepting a
              second call.
            - **Deferred to the next calling window.** The workspace is outside its outbound
              calling hours, so the call is held and placed when the window next opens.
              `status` is `scheduled` and `scheduled_for` is that opening. This is the
              non-workflow counterpart of the `scheduled` acceptance above.
            - **Returned to the queue.** The call was prepared but handed back before dialling,
              so it has not been placed and will be retried automatically. This is the one
              shape with no `id`: it carries `status`, `message` and a short `reason` label
              only. Do not treat it as a live call, and do not resend it — a retry of your own
              would be a second call.

            Send an `Idempotency-Key` header to make a retry safe: an identical retry returns the
            original acceptance rather than a second call. Reusing the key with different call
            details is a `409 WORKFLOW_IDEMPOTENCY_CONFLICT`.
          content:
            application/json:
              schema:
                oneOf:
                  - title: Queued at capacity
                    type: object
                    properties:
                      id: { type: string, format: uuid, description: "queue entry ID" }
                      status: { type: string, example: "queued"  }
                      agent_id: { type: string, format: uuid }
                      to: { type: string }
                      from: { type: string }
                      queue_position: { type: integer }
                      queued_at: { type: string, format: date-time }
                      expires_at: { type: string, format: date-time }
                      message: { type: string }
                  - title: Accepted for a workflow agent
                    type: object
                    properties:
                      id: { type: string, format: uuid, description: "Queue entry ID." }
                      request_id: { type: string, format: uuid, description: "Pass this to the call-request endpoints to follow or cancel the call." }
                      run_id: { type: string, format: uuid }
                      call_id: { type: [string, 'null'], format: uuid, description: "Always null here; a call record does not exist yet." }
                      status: { type: string, enum: [queued, scheduled] }
                      preparation_status: { type: string, example: "pending" }
                      agent_id: { type: string, format: uuid }
                      to: { type: string }
                      from: { type: string }
                      queued_at: { type: string, format: date-time }
                      scheduled_for: { type: string, format: date-time, description: "Present only when the call waits for the next calling window." }
                      expires_at: { type: string, format: date-time }
                  - title: Deferred to the next calling window
                    type: object
                    properties:
                      id: { type: string, format: uuid, description: "Queue entry ID." }
                      status: { type: string, example: "scheduled"  }
                      agent_id: { type: string, format: uuid }
                      to: { type: string }
                      from: { type: string }
                      scheduled_for: { type: string, format: date-time, description: "When the outbound calling window next opens." }
                      queued_at: { type: string, format: date-time }
                      expires_at: { type: string, format: date-time }
                      message: { type: string }
                  - title: Returned to the queue
                    type: object
                    properties:
                      status: { type: string, example: "queued"  }
                      message: { type: string, description: "Plain-language explanation of why the call was handed back." }
                      reason: { type: string, description: "Short label for the cause. Diagnostic only — branch on the status and the presence of request_id, never on this string." }
        "400":
          description: |
            Bad request. The `code` field identifies the specific failure:
            - `invalid_destination` — `to` cannot be dialled, and this is the only code that
              says so. It covers a malformed number (not E.164, or an Israeli number written with a
              leading `0` after the country code or with the wrong digit count) and a well-formed
              number that cannot be reached (a mobile prefix no longer in service, or a service
              number such as 1-800), and a number outside Israel: calls can only be placed to
              Israeli numbers (+972). The `error` text says which. No call was placed and nothing was
              charged; correct the number, because the same one fails the same way every time.
            - `INVALID_FROM_NUMBER` — `from` is malformed, or is not an active number on your workspace (a number on a `paused` carrier account is switched off, so it answers this too).
            - `SELF_CALL_NOT_ALLOWED` — `to` and `from` are the same number.
            - `WEB_CALL_REQUEST_INVALID` — `type: "web"` only: the body carried a field a browser
              session does not read. It takes `type`, `agent_id`, `metadata`, `variables`,
              `allowed_origins` and `lead_id`; nothing was minted.
            - Inactive agent. A missing `to` or `from` is not here: it is
              `422 WORKFLOW_REQUEST_INVALID`, naming the field.
            WEB_CALL_REQUEST_INVALID also refuses a field of the wrong type on a browser session: metadata and variables are objects, allowed_origins an array of origins.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "402":
          description: |
            `BILLING_ERROR` — the call cannot be paid for now. A call needs at
            least **$1.00** of credit to start.

            If auto top-up is enabled, we charge the card on file and re-check
            the balance before refusing, so a 402 means the top-up could not
            cover it: auto top-up is off, the workspace is suspended, there is no
            billing account, the card was declined, automatic payment attempts
            are cooling down or have stopped, or the workspace's own low-balance
            threshold is set below the minimum needed to start. The `error`
            message says which. Do not retry the same request immediately; add
            credits or update the payment method when payment action is required.

            `SPEND_BUDGET_REACHED` shares this status and is a different thing: the
            workspace set itself a monthly spending limit and this month's charges have
            reached it, so outbound phone calls asked for through the API or by a campaign
            are paused until the limit is raised, turned off, or the next calendar month
            begins. This covers every outbound PHONE call, including a workflow agent's call
            request and one already accepted and waiting for its call window. Nothing is
            wrong with the account, and calls coming in, browser rehearsals and shared-link
            calls are unaffected. Read where the month stands with `GET /billing`;
            change the limit with `PATCH /billing`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: |
            A key [limited to some agents](/api-reference/introduction#limiting-a-key-to-some-agents):
            - `AGENT_OUTSIDE_KEY_SCOPE` — `agent_id` is left out or is not one of the key's agents.
            - `API_KEY_AGENT_SCOPED` — `from` is not a number one of the key's agents answers or
              calls from: another client's number, or one no agent uses. The same answer whether
              the number exists or not.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: |
            `AGENT_NOT_FOUND` — the `agent_id` names no agent in this workspace, the same
            answer every route gives a missing agent.
            `WORKFLOW_AGENT_UNAVAILABLE` — the agent is here but cannot take the call: it is
            archived or switched off. Switch it on, or call a different agent.

            The same code and status answer a `workflow_revision_id` that is not one of this
            agent's own published versions. If the agent itself is fine, re-read
            `GET /agents/{id}/workflow/versions` and pin an id from that list.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: |
            The `code` field identifies the failure:
            - `WORKFLOW_UNPUBLISHED` — the agent has never been published. Publish it, then call.
              A `type:"web"` mint answers this too: it used to hand back a token that could only
              fail once a browser spent it.
            - `WORKFLOW_AGENT_INACTIVE` — the agent is switched off. A `type:"web"` mint answers
              this instead of the bare 400 it used to. Set `is_active` to true and ask again.
            - `WORKFLOW_IDEMPOTENCY_CONFLICT` — this `Idempotency-Key` was already used with
              different call details. Send the original details, or use a new key for a new call.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: |
            The `code` field identifies the failure. These are not all workflow-only — each
            bullet says which agents can answer with it:
            - `WORKFLOW_REQUEST_INVALID` — `to` or `from` is missing; the response names which.
              The same code answers an `Idempotency-Key` header that is not 1–200 visible
              ASCII characters (`!` through `~`, so a space is rejected). Both checks run for
              every agent, before the agent is read. For a workflow agent the same code also
              answers a body that carries a property this endpoint does not accept,
              `variables`/`metadata` that is not an object, or `type` present with a value other
              than `"phone"`. Send only `agent_id`, `to`, `from`, `variables`, `metadata`,
              `workflow_revision_id` and — if you send it at all — `type: "phone"`.
            - `WORKFLOW_PIN_INVALID` — `workflow_revision_id` was sent for an agent that is *not*
              a workflow agent. Omit it: only workflow agents have versions to pin. A version that
              belongs to some other agent, or to no agent at all, is the `404` above instead.
            - `WORKFLOW_DEADLINE_INVALID` — workflow agents only: the workspace's next calling
              window is further out than scheduling allows. Widen the calling window.
            - `OUTSIDE_CALL_WINDOW` — no future calling window is configured for outbound calls.
              Answered for either kind of agent. Configure one, then call.
            - `PHONE_SYSTEM_OUTBOUND_OFF`, `PHONE_SYSTEM_OUTBOUND_PAUSED`, `PHONE_SYSTEM_NOT_CONNECTED`,
              `DESTINATION_OUTSIDE_PHONE_SYSTEM_COUNTRY` — `from` is a `phone_system` number (an
              extension that calls out through your own phone system,
              [register.outbound](/concepts/sip-trunks#outbound-calls-through-the-extension)) and the call
              can't go out: outbound is switched off on its endpoint, paused after your phone system
              refused the last calls (turn it back on with `enabled: true`), the endpoint is switched
              off or not registered, or `to` is outside Israel while the endpoint dials in `national`
              format (today a number outside Israel is refused first with `400 invalid_destination`,
              in either dial format). Answered for either kind of agent, before anything is reserved
              or dialled.
            - `WEB_LEAD_UNSUPPORTED` — `type:"web"` only: `lead_id` was sent for a workflow agent
              whose browser call is created by a call request. Its call is created by the call request, which
              takes no lead. Mint again without `lead_id`.
            - `carrier_account_paused`, `carrier_account_unavailable` — workflow agents, at
              acceptance, and only while `from` (a number from your own Telnyx account, a
              [carrier account](/concepts/bring-your-own-carrier)) is still switched on although
              its account is paused or no longer connected. Pausing an account switches its
              numbers off, so a request from one of them normally answers
              `400 INVALID_FROM_NUMBER`. Nothing was accepted or dialled. A request already
              accepted with `202` waits while its number's account is paused and ends `expired`
              (`request_expired`) unless the account is
              [turned back on](/api-reference/carrier-accounts/reactivate) first; one your Telnyx
              account refuses when it is placed ends `failed` (`request_failed`), once.

            A call that was refused before it rang is also a `422`, and is not retried. It is
            recorded as `failed`, and no webhook is sent for it: this answer is
            the only notice. (A call answered `202` and refused later, from the
            queue, sends `call.failed` with the reason in `data.error_reason`.)
            The `error` message says why, for example:
            - `from` is a number from your own Telnyx account (a
              [carrier account](/concepts/bring-your-own-carrier)) and Telnyx
              turned the dial down: "Your Telnyx account refused this call…".
              If Telnyx refused the account's API key, or its Call Control App
              is gone, the account is also paused: "Calls from this number are
              paused…".
            - The number you called is not in service. It is added to your
              do-not-call list so it is not dialled again.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "429":
          description: Concurrent call limit reached for your plan
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: |
            `WORKFLOW_ADMISSION_UNAVAILABLE` — workflow agents only. Call acceptance is
            temporarily unavailable and **no call was placed**. Retry the same request with the
            same `Idempotency-Key`.

            One cause does not clear on retry: a `workflow_revision_id` that belongs to the agent
            but has no usable build behind it answers here too. If the same pinned version fails
            every time while an unpinned call succeeds, pin a different version or drop the pin.

            `BILLING_UNAVAILABLE` — the balance could not be settled *yet*, but
            the request is worth retrying. Returned when an auto top-up is still
            being processed, when a payment outcome is still being resolved,
            when a charge has been made but the credit has not appeared, or when
            the balance check itself failed. Retry after a few seconds; this is
            explicitly **not** a 402, so integrations should not treat it as
            "the customer is out of money".

            `WEB_CALL_UNAVAILABLE` — web sessions only (`type: web`). This deployment's
            data-plane key is a secret-class key rather than a publishable one, so the mint
            refused rather than hand a key of that class to a browser. No session was minted
            and no token was spent. Retrying will not clear it on its own; contact support.
            A deployment with no data-plane key at all is not this: the session is minted and
            `connection.api_key` comes back `null`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /calls/export:
    get:
      summary: Export calls as CSV
      description: |
        The call log as a file, filtered exactly as `GET /calls` is filtered. Required
        scope `calls:read`, or `calls:metrics`, whose file leaves From, To, Lead name, Summary
        and Carrier call ID empty, carries no Extracted columns, and refuses the `caller`,
        `callee`, `search` and `lead_id` filters. `Lead name` is filled only for a key that also holds
        `leads:read`; without it the column is empty on every row, as `GET /calls` reads
        such a key's lead as `{id}`, and a `lead_id` filter does not bring the name back.

        It carries the same fields as the dashboard's Export CSV, in the same order, so the
        two line up column for column. Every line under the headings is one call: the total
        is the `X-Total-Cost-USD` header, not a line among the rows. They are not
        byte for byte alike: this file has fixed English headings and the API's own values;
        the dashboard's is written in the reader's language, heads its start
        `Started (ISO 8601)` (with the workspace's offset) and adds `Started (<zone>)`
        second, heads its duration `Duration (seconds)`, writes the screen's words for
        direction, status, source and no agent, and `Yes`/`No` for `true`/`false`.

        Answers `text/csv; charset=utf-8` with a UTF-8 byte-order mark, which is what makes
        a spreadsheet read Hebrew agent and disposition names as Hebrew. Rows stream as they
        are read, so a large window starts arriving immediately.

        **One moment.** The file holds the calls that existed when the request arrived; a
        call that starts while it streams belongs to the next export, never half to this
        one. `X-Total-Rows` is therefore exactly the number of call rows in the file.

        **Columns.** `Started` (ISO 8601 with its offset, always `+00:00` — the file is not
        localised, so it carries no workspace timezone), `Agent` (the agent's name, empty
        when the call has none), `A/B` (`A`, `B`, or empty), `Direction` and `Status` (the
        API's own values, e.g. `web_call`, `no_answer`), `Disposition` (the outcome's
        label), `From`, `To`, `Duration` (whole seconds), `Cost (USD)` (dollars and cents;
        `0.00` on a call that ended without a charge, empty only while the charge is pending),
        `Source`, `Shared link ID`,
        `Call ID` (the key to `GET /calls/{id}` — join on this), `Lead name` (empty when the
        call has no lead or it was deleted, and for a key without `leads:read`), `Summary`, `Cost status` (`charged`,
        `not_charged` or `pending`, exactly as `cost_status` on `GET /calls`), `Ended by`
        (`caller`, `agent`, `system`, `operator`, `unknown`, or empty when nothing recorded
        it, exactly as `ended_by` on `GET /calls`), `Agent ID` (the agent's id beside its
        name, so two agents with one name stay two in a pivot), `Provider` (`external`,
        `telnyx`, or empty on a browser call, exactly as `provider` on `GET /calls`), `Carrier
        account` (the carrier account's name on an `external` call, for a key with
        `carrier_accounts:read`; empty otherwise), `Carrier call ID` (on an `external` call, the
        id Telnyx gave it on your account, as `carrier_call_id`), then one `Extracted: <field>` column
        per field any call in the file collected, named for its key in `extracted_data`
        (a string as written, a number or `true`/`false` as the API returns it, anything
        nested as JSON, empty when the call did not collect it). In `Lead name`, `Summary`
        and the `Extracted:` columns a value opening with `=`, `+`, `-`, `@` or a tab is
        written with a leading apostrophe so a spreadsheet does not run it as a formula; a
        phone number or a plain number is written as it is. The first twenty-one columns
        never move; the `Extracted:` set depends on the window, so read those by heading.
        There is no `Total` line: what the rows cost together is the `X-Total-Cost-USD`
        header.

        **Row limit.** At most 10000 calls per export. A window holding more is refused
        with `400 CALLS_EXPORT_TOO_LARGE` naming the count — never truncated, because a
        file cut short carries totals that are wrong and says nothing about it. Page a
        larger export by splitting the window with `from` and `to`: a call's start time
        never changes, so consecutive windows skip nothing. `to` is inclusive, so a call
        that started at exactly a boundary is in both neighbouring files — de-duplicate on
        `Started` before adding their `X-Total-Cost-USD` values up.

        `limit`, `offset`, `cursor` and `updated_since` are refused here with
        `400 CALLS_QUERY_INVALID`. An export is one whole window of call starts, not a page
        of it and not what changed since it last ran: to read pages, or the calls that have
        changed, use `GET /calls`.
      operationId: exportCalls
      tags: [Calls]
      parameters:
        - in: query
          name: agent_id
          schema: { type: string, format: uuid }
          description: Only this agent's calls. An id that is not an agent in this workspace is 404 AGENT_NOT_FOUND, as on GET /calls.
        - in: query
          name: status
          schema: { type: string, enum: [pending_connection, ringing, in_progress, completed, failed, no_answer, transferred, dnc_blocked] }
          description: pending_connection is a browser session minted with POST /calls that no browser has connected to yet. Anything outside the list is 400 CALLS_QUERY_INVALID.
        - in: query
          name: direction
          schema: { type: string, enum: [inbound, outbound, web_call] }
        - in: query
          name: callee
          schema: { type: string }
          description: "Destination number in E.164."
          example: "+972501234567"
        - in: query
          name: caller
          schema: { type: string }
          description: "Source number in E.164."
          example: "+972551234567"
        - in: query
          name: ab_variant
          schema: { type: string, enum: [a, b] }
          description: >
            Which side of a number's A/B split took the call. Anything but a or b is
            400 INVALID_AB_VARIANT, exactly as on GET /calls — never an empty file that
            reads as "no call ran that variant".
        - in: query
          name: disposition
          schema: { type: string }
          description: >
            Only calls that ended with this outcome, by its label exactly as GET /dispositions
            returns it. A label this workspace does not have is 404 CALL_DISPOSITION_UNKNOWN
            rather than an empty file.
          example: Interested
        - in: query
          name: disposition_id
          schema: { type: string, format: uuid }
          description: The same outcome filter by id. Send this or `disposition`, not both.
        - in: query
          name: source
          schema: { type: string, enum: [test, shared_link, api, phone_inbound, phone_outbound] }
        - in: query
          name: carrier_account_id
          schema: { type: string, format: uuid }
          description: >
            Only calls on this carrier account (signed for, placed from or answered on one
            of its numbers), exactly as on GET /calls: needs
            carrier_accounts:read (403 INSUFFICIENT_SCOPE), and an account that is not in this
            workspace is 404 CARRIER_ACCOUNT_NOT_FOUND rather than an empty file. The file's name
            carries it: `calls-carrier-7c1e4a2b-….csv`, the first eight characters of the id.
        - in: query
          name: provider
          schema: { type: string, enum: [external, telnyx, none] }
          description: >
            Only calls on this carrier, exactly as on GET /calls: external, telnyx or none (a
            browser call). The file's name carries it: `calls-provider-external-….csv`.
        - in: query
          name: search
          schema: { type: string, minLength: 2, maxLength: 100 }
          description: >
            The same search as GET /calls - the start of a call id (8 or more characters), a phone
            number at either end, or part of an agent's or a lead's name. A lead's name is searched
            only for a key with leads:read; for any other key a name matches agents alone.
          example: Tamar
        - in: query
          name: lead_id
          schema: { type: string, format: uuid }
          description: >
            Only calls with this lead. A lead that is not in this workspace is 404 NOT_FOUND rather
            than an empty file.
        - in: query
          name: from
          schema: { type: string, format: date-time }
          description: >
            Calls created on or after this timestamp. A value that is not a real date —
            including a month-end its month does not have, like 2026-09-31 — is
            400 CALLS_QUERY_INVALID.
        - in: query
          name: to
          schema: { type: string, format: date-time }
          description: >
            Calls created on or before this timestamp, inclusive. Refused the same way from is. A
            date-only value covers that whole day (UTC), up to 23:59:59.999999.
      responses:
        "200":
          description: |
            The file. `Content-Disposition` names it for its filters and its window
            (`calls-agent-9b29b0c9-no_answer-2026-09-01_2026-09-30.csv`; the agent and an
            outcome filter by the first eight characters of their id), `X-Total-Rows` carries
            the number of calls in it and `X-Total-Cost-USD` what they cost together. Every
            line under the headings is a call.
          headers:
            Content-Disposition:
              schema: { type: string }
              description: 'attachment; filename="calls-agent-9b29b0c9-2026-09-01_2026-09-30.csv"'
            X-Total-Rows:
              schema: { type: integer }
              description: >
                Calls in the file. This, X-Total-Cost-USD and Content-Disposition are listed
                in Access-Control-Expose-Headers, so a browser client can read them too.
            X-Total-Cost-USD:
              schema: { type: string }
              description: >
                What the calls in the file cost together, in dollars and cents as a bare
                decimal (`36.57`) — the sum of the Cost (USD) column. It replaces the Total
                line the file used to end with.
          content:
            text/csv:
              schema: { type: string }
              example: |
                "Started","Agent","A/B","Direction","Status","Disposition","From","To","Duration","Cost (USD)","Source","Shared link ID","Call ID","Lead name","Summary","Cost status","Ended by","Agent ID","Provider","Carrier account","Carrier call ID","Extracted: preferred_day"
                "2026-09-14T08:03:11.123456+00:00","Dental intake","","outbound","completed","Booked","+972551234567","+972501234567","94","0.41","phone_outbound","","7ccf2af4-a6e2-40db-9f60-de21933d83c4","Dana Levi","Booked a cleaning for Tuesday morning.","charged","caller","3f9b1c2d-5e6a-4b7c-8d9e-0f1a2b3c4d5e","telnyx","","","Tuesday"
        "400":
          description: >
            `CALLS_QUERY_INVALID` — a filter this export does not have, a filter sent with no
            value, a `status` / `direction` / `source` outside its set, a `from` or `to` that is
            not a real timestamp, or `limit` / `offset`. `INVALID_AB_VARIANT` — `ab_variant` was
            not `a` or `b`. `CALLS_EXPORT_TOO_LARGE` — the window holds more than 10000 calls;
            nothing was written.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            `INSUFFICIENT_SCOPE` — the key holds neither `calls:read` nor `calls:metrics`, or holds
            only `calls:metrics` and filtered by `caller`, `callee`, `search` or `lead_id`.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: >
            `CALL_DISPOSITION_UNKNOWN` — the `disposition` label or `disposition_id` you filtered
            by is not a disposition in this workspace. `AGENT_NOT_FOUND` — the `agent_id` you
            filtered by is not an agent in this workspace. `CARRIER_ACCOUNT_NOT_FOUND` — the
            `carrier_account_id` is not a carrier account in this workspace. `NOT_FOUND` — the
            `lead_id` is not a lead in this workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /calls/{id}:
    get:
      summary: Get call
      operationId: getCall
      tags: [Calls]
      description: |
        One call, whole: who it was with, what was said, what the agent picked out of it, what it
        cost, and where its post-call analysis stands.

        Requires `calls:read`, or `calls:metrics`, which reads the call as metrics: the members
        that describe the call itself (ids, `agent`, direction, status, moments, duration, cost,
        `usage`, disposition, `ended_by`, `failure`, `analysis`), `from`, `to`, `metadata`
        and `transfer_target` null, `lead` as `{id}`, and
        `personal_data_withheld: true`. The transcript, summary, recording, `extracted_data`,
        events, timeline, tool calls and execution history are left out, and the execution-history
        parameters answer 403 INSUFFICIENT_SCOPE.

        **Rehearsals and leads.** A rehearsal in the browser (**Test**, **In the browser**, or a session minted
        with `POST /calls {"type":"web"}`) has no caller's number, so lead processing skips it:
        no lead is created or updated, no `lead.created` or `lead.updated` is sent, and a
        follow-up on `lead.ready` does not run. On a rehearsal that ran through a call request the
        `lead` artifact in `execution.summary.artifacts` reads `skipped` with
        `reason_code: "web_call_no_phone"`; one that connected straight away (`protocol: "offer"`)
        has no `lead` artifact at all. The analysis still runs:
        `summary`, `disposition` and `extracted_data` are written as on any call. A dashboard browser test
        given a phone number to simulate, and a session minted with `lead_id`, are processed for
        a lead after all.
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
        - { $ref: "#/components/parameters/ExecutionLimit" }
        - { $ref: "#/components/parameters/ExecutionCursor" }
        - { $ref: "#/components/parameters/ExecutionPhase" }
        - { $ref: "#/components/parameters/ExecutionKind" }
        - { $ref: "#/components/parameters/ExecutionStatus" }
        - in: query
          name: omit
          required: false
          description: >
            `execution` reads the call without its execution history: the history is not read at all,
            so the answer comes back sooner and is a fraction of the size. `execution` then carries only
            `summary.settlement`, `summary.is_settled` and `refresh_after_ms`, worked out from the call
            itself, on every call (`execution_status: omitted`) - the members a poller stops on. Cannot
            be sent with an `execution_` parameter, and takes no other value (400 `CALLS_QUERY_INVALID`).
          schema: { type: string, enum: [execution] }
      responses:
        "200":
          description: Full call details
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  agent_id: { type: string, format: uuid }
                  from: { type: [string, "null"], description: "The caller, in E.164. On a call that arrived on a SIP endpoint it is whatever your phone system sent as the caller, which may not be a phone number, and `null` when the caller ID was only a username-and-password trunk's own username. An empty string on a browser call." }
                  to: { type: [string, "null"], description: "The number dialled, in E.164. `null` on every call that arrived on a SIP endpoint, and sip_endpoint_id names the endpoint: a SIP address endpoint's address is its credential, and what a username-and-password trunk's call dialled shows in the dashboard's call log. An empty string on a browser call." }
                  personal_data_withheld:
                    type: boolean
                    description: >
                      Present, and true, only when a `calls:metrics` key that does not hold
                      `calls:read` read the call: the people on it and what they said were held
                      back. Absent on every other read.
                  direction: { type: string }
                  status: { type: string }
                  started_at: { type: string, format: date-time, description: "When the call was placed - dialled, arrived at your number, or its browser session opened. The same moment as created_at, and created_at itself on a browser session that never recorded a start of its own: never null. It is not when anyone answered; that is answered_at." }
                  answered_at: { type: string, format: date-time, nullable: true, description: "When the call's audio came up - the person you dialled picked up, your number answered the caller, or the browser connected. Where the voice server recorded no such moment on a call that did connect, the earliest evidence that it connected: the first moment anybody was heard, or, for a browser or incoming call holding a recording or a transcript, its started_at (a recording alone does not count on a failed call). duration_seconds counts from about here, and each timeline message is dated answered_at + offset_ms. Null on a call that never got that far." }
                  recording_started_at: { type: string, format: date-time, nullable: true, description: "When the call's recording began, as the carrier stamped it: every transcript turn's start and end are milliseconds from here, so recording_started_at + start is when the line was said. It is not started_at - an outbound call rings before it is answered and recorded - and it is within about 2 seconds of answered_at, either side. Present once the recording is saved, usually a few seconds after the call ends; null on a browser call (its recording begins once the browser has connected, shortly after answered_at), on a call with no recording, and on older calls recorded before the field was added." }
                  ended_at: { type: string, format: date-time, nullable: true, description: "When the call ended - the caller or the agent leaving, or Yappr closing it. Never before started_at." }
                  duration_seconds: { type: integer, nullable: true, description: "Connected time in whole seconds, counted from about answered_at to the end - the time the call is billed for. Ringing, and the wait between placing a call and its answer, are not in it. Null while the call runs and on every call that was never answered (nobody picked up, the number was blocked, or no browser connected, and no answered_at); a whole number, 0 included, on every call that was - a call with an answered_at was answered, whatever stage its failure names." }
                  cost_cents:
                    type: integer
                    nullable: true
                    description: >
                      What this call consumed from the workspace's credits, in credits (one credit is
                      one cent). 0 for a call that ended without a charge (failed, not answered,
                      blocked, or completed with no connected time); null only while the call is still
                      settling - never 0 for an unsettled call. cost_status says which. This is what
                      you were charged, and the only cost a call states. For totals across calls, by
                      day, product or agent, use GET /billing/consumption.
                  cost_status:
                    type: string
                    enum: [charged, not_charged, pending]
                    description: >
                      Whether cost_cents is final: charged (the recorded charge), not_charged (ended
                      without billable time, or ended more than 24 hours ago with no charge recorded;
                      cost_cents is 0) or pending (live, or ended less than 24 hours ago with the
                      charge not recorded yet; cost_cents is null - come back).
                  metadata:
                    type: object
                    nullable: true
                    description: |
                      The metadata object you attached at `POST /calls`. Empty object `{}` if no metadata
                      was provided at call creation. Internal bookkeeping the call picked up on the way is
                      not part of it — including the text recorded when a call failed, which is the
                      carrier's own cause code or an exception's tail, and when it was recorded. Read
                      `failure` for why a call did not complete. Some keys the platform adds do stay, and
                      this is not an exhaustive list: `ab_variant` and `ab_variant_fallback` when a split
                      picked the agent, `share_link_id` on a call from a share link, `agent_id` on a test
                      call started from the dashboard, `queued`, `queue_id` and `queue_wait_seconds` on a
                      call that waited for a free line, `workflow_request_id` on a call started from a
                      call request, and, on a call that spoke, `timezone`, `timezone_source` (`call_variable`,
                      `workspace` or `fallback`) and `timezone_unconfirmed` (`true` when the zone is UTC taken
                      from a workspace that may never have chosen one): the zone the agent's clock ran in,
                      which a calendar tool books on only when it shares that zone. A `timezone` key you
                      attach yourself is never replaced. Name your own keys so they cannot collide with these.
                  created_at: { type: string, format: date-time }
                  updated_at:
                    type: string
                    format: date-time
                    description: >
                      When this row last changed - the same field GET /calls projects and
                      ?updated_since= bounds, so a sync that pages the list and then reads a call by
                      id keeps the timestamp its loop windows on. Calls recorded before this field
                      existed carry the last moment they can be proved to have changed, so it is
                      never null.
                  source:
                    type: string
                    enum: [test, shared_link, api, phone_inbound, phone_outbound, unknown]
                    description: >
                      Where the call came from. A rehearsal and a shared-link call used to be the same row -
                      both web_call, both with empty from and to - so testing spend could not be told apart
                      from the link that was handed out. "unknown" is a call recorded before its origin was
                      written down, and is the one value ?source= refuses.
                  provider:
                    type: string
                    enum: [external, telnyx]
                    nullable: true
                    description: >
                      Whose carrier the phone side ran on, in the words GET /phone-numbers uses for the
                      call's number. external - your own Telnyx account (a number with provider external):
                      Telnyx billed you for the phone minutes, and cost_cents is Yappr's charge beside them.
                      telnyx - Yappr's own carrier: a number bought from Yappr, or a SIP endpoint. null - a
                      browser call, which has no phone side.
                  carrier_account:
                    type: object
                    nullable: true
                    description: >
                      The carrier account an external call ran on - the account Telnyx signed the call
                      for, or its from-number's account when no signed event arrived. null on every other
                      call, and for a key without carrier_accounts:read (provider still says external). An
                      account removed since keeps its id, with name, provider and status null. The same
                      four fields as a number's carrier_account on GET /phone-numbers.
                    properties:
                      id: { type: string, format: uuid }
                      name: { type: string, nullable: true }
                      provider: { type: string, enum: [telnyx], nullable: true }
                      status: { type: string, enum: [untested, active, paused], nullable: true }
                  carrier_call_id:
                    type: string
                    nullable: true
                    description: >
                      On an external call only (absent on every other call): the call_control_id Telnyx
                      gave the call on your own Telnyx account - the id to find it by in your Telnyx
                      records and its call debugging. null when the dial never got one (refused before
                      Telnyx answered), and null for a key without carrier_accounts:read.
                    example: "v3:u5OA0mKfWkqg2Gfyv1c0g8ukRZ3n1R6f2sKnH4Qj1i1aX8Pz9g"
                  shared_link_id:
                    type: string
                    format: uuid
                    description: >
                      The shared link this call came through. Absent, not null, on every other kind of call.
                  sip_endpoint_id:
                    type: string
                    format: uuid
                    description: >
                      The SIP endpoint this call arrived on - a phone_inbound call from your own phone
                      system. Such a call's `to` is null (see `to`). Absent, not null, on every other
                      kind of call.
                  ended_by:
                    type: string
                    enum: [caller, agent, system, operator, unknown]
                    nullable: true
                    description: "Who ended the call. caller - the far end hung up first, or the browser closed the connection (the End button on a browser test call included); a browser call whose failure code is caller_left always reads caller. agent - the agent chose to end it, through its end-call tool, its flow End step or its closing line. system - Yappr ended it, on the silence timeout, the maximum-duration cap, an answering machine, a fault, the watchdog closing a stuck call, or a browser session that expired before anyone connected. operator - someone ended the call from outside it on purpose: the End button on a dashboard phone test call, POST /calls/{id}/end or the session's cancel_url on a browser session nobody opened, or Yappr stopping a stuck call. A call ended this way has no failure member. unknown - the carrier reported the ending without saying which side dropped the call. null - nothing recorded one. A transfer records nothing at the handoff itself, because the leg stays up and whoever hangs up afterwards is the answer; the value is already resolved for the call direction. First-write-wins, so a specific value is never overwritten by a later generic one."
                  disconnect_reason:
                    type: string
                    nullable: true
                    description: "Short human-readable label for why the call ended, meant for display rather than branching - for example Completed, No answer, Busy, Call rejected, Cancelled, Caller inactive, Max duration reached, Voicemail detected, Answering machine detected, Ended by operator, Ended by the platform: stuck call, Failed, or one of the Transfer ... labels when a handoff never connected, or \"Your Telnyx account refused the call…\" when your own Telnyx account refused a call from one of its numbers. Wording may change and labels are added, so treat it as text. First-write-wins. Null when nothing was recorded, and when what was recorded is not one of these labels - an internal note never reaches this field."
                  transferred_at:
                    type: string
                    format: date-time
                    nullable: true
                    description: "When the call was handed off to another party. A phone number, and an extension endpoint's new call through your extension, leave the call with status 'transferred'. A SIP REFER hand-off over a username-and-password trunk ends 'completed' with this time set."
                  transfer_target:
                    type: string
                    nullable: true
                    description: "The number the call was transferred to (E.164), or, for a hand-back to your own phone system, the SIP address with any password and any header part (the part after a ?) removed. The extension before the @ stays."
                  recording_url:
                    type: string
                    description: "Signed URL for the call recording on the API host. Opens directly in a browser or audio player — answers 200 with the audio itself (HEAD and Range supported). No additional authentication required. It lasts 7 to 8 days (`exp`) and stops opening when the call's links are revoked (POST /calls/{id}/recording/revoke); read the call again for a current one. Absent when the call has no recording the link can serve."
                  agent:
                    type: object
                    nullable: true
                    description: >
                      The agent behind `agent_id`, read with the call, so its name stays readable after the
                      agent is archived (GET /agents/{id} answers 404 for an archived agent). For a key
                      holding `agents:read` it is the object a campaign embeds for its agent; for a key
                      without it, `{ id, name }`. Both carry `archived_at`. Null when the call has no agent.
                    allOf:
                      - $ref: "#/components/schemas/Agent"
                    properties:
                      archived_at:
                        type: string
                        format: date-time
                        nullable: true
                        description: When the agent was archived; null while it is not.
                  disposition:
                    nullable: true
                    description: "Full Disposition object. Present only when a disposition has been assigned."
                    allOf:
                      - $ref: "#/components/schemas/Disposition"
                  lead:
                    nullable: true
                    description: "Full Lead object including long_term_context and tags. Present only when a matched lead exists. A key without `leads:read` reads `{id}` only."
                    allOf:
                      - $ref: "#/components/schemas/Lead"
                  summary: { type: string, description: "AI-generated call summary, written in the language the call was held in - read off the conversation when its script makes the language clear, else the agent's language; a multilingual agent's summary is in the language the caller spoke. Present only when available.", nullable: true }
                  transcript:
                    type: array
                    description: |
                      Full call transcript, ordered by time. Present only when available. Written once, after
                      the call recording is saved, by transcribing that recording: on every call, whichever
                      voice model ran it and whatever language it was in. Where the recording holds the caller
                      and the agent on separate channels, who said a line is read from its channel. A call with
                      no recording has none.
                    items: { $ref: "#/components/schemas/TranscriptEntry" }
                  usage:
                    type: object
                    description: |
                      **What the call consumed on the voice model that ran it**, reported by the provider
                      itself: token counts, or seconds of live audio. It carries no price; what the call
                      cost you is `cost_cents`. Present only when a reading exists — a call that never
                      reached the model has no `usage` member at all, which is a different statement
                      from a call that consumed nothing.

                      One entry in `legs` per engine the call ran on, summed across every provider
                      session the call spanned: a call whose socket dropped and was rebuilt mid-call is
                      still one entry with the whole call's usage on it.

                      The two engines report in different units and the response says which: a Gemini
                      voice runs on tokens split by modality, a GPT voice on seconds of live audio.
                    properties:
                      legs:
                        type: array
                        items: { $ref: "#/components/schemas/CallUsageLeg" }
                  extracted_data:
                    type: object
                    description: >
                      Structured fields extracted post-call by the agent's extraction_parameters.
                      The member is absent — not null — on a call where extraction did not run or
                      produced nothing at all, so read it with a presence check. When it is there
                      it carries one key per configured parameter, and a parameter the conversation
                      never supplied is null inside it. A present object of all-null values means
                      extraction ran and captured nothing, which is not the same as no extraction.
                      A number parameter holds one number - "about 12" is 12, a half is kept ("two
                      and a half" is 2.5), a range is its middle ("3-4" is 3.5). A date parameter
                      holds a YYYY-MM-DD day or null; a month with no day is null (see
                      extracted_data_precision).
                  extracted_data_precision:
                    type: object
                    description: >
                      Beside extracted_data, for an agent that collects dates: one entry per date
                      parameter saying how precisely the caller gave it - day, month (with the month,
                      as YYYY-MM, and approximate true when it was worked out from a length of time
                      ago) or unknown - with role (event or message) when the reader judged whose day
                      it is, and ambiguity when the caller's words disagreed. Absent on calls analysed
                      before it was recorded, and on agents with no date parameters.
                    additionalProperties: { $ref: "#/components/schemas/ExtractedDatePrecision" }
                    example: { interview_date: { precision: month, month: "2026-11" }, start_date: { precision: day, month: "2026-12" } }
                  extracted_data_ranges:
                    type: object
                    description: >
                      Beside extracted_data: one entry per number parameter whose stored value is the
                      middle of a range the caller gave ("בין שש לשבע" is 6.5), with the range's two ends.
                      Absent when no number was a range, and on calls analysed before it was recorded.
                    additionalProperties: { $ref: "#/components/schemas/ExtractedNumberRange" }
                    example: { pain_level: { low: 6, high: 7 } }
                  tool_calls:
                    type: array
                    description: |
                      Paired request/response objects for each tool invocation during the call. Easier to
                      consume than raw events. Auth-related headers (Authorization, tokens, keys) are
                      redacted as `[REDACTED]`.

                      **Superseded by `timeline` (below)**, which is what the dashboard shows and what new
                      integrations should read. This member is kept for existing ones, and it is the raw
                      view: apart from those headers it returns the tool's URL, its arguments and the
                      response body as they were. The summaries-only rule below is a rule about `timeline`,
                      not about this member.

                      **A call the workflow platform ran** records its tool runs in `timeline`, not as raw
                      events, so for those calls this member lists the same `tool` rows as pairs: `tool_name`,
                      `timestamp`, `kind` (always `tool_call`; a connected app also carries `provider` and
                      `action`), `node` and `response.success` / `response.error` /
                      `response.duration_ms` (`success` is `null` while the tool is still running). They are
                      summaries: `request.body` is `null`, there is no URL or headers, and
                      `response.response_preview` is `null`. Read `timeline` for the full account.
                    items: { $ref: "#/components/schemas/ToolCallPair" }
                  events:
                    type: array
                    description: |
                      Full ordered event stream for the call. Low-level — for flow agents prefer
                      `flow_trace` (below). Auth headers in `tool_called` events are redacted.

                      **Superseded by `timeline` (below)**, and the rawest of these members: everything a
                      tool sent and received, and the engine's own error text, is here as it was recorded.
                      Kept for existing integrations.
                    items: { $ref: "#/components/schemas/CallEvent" }
                  timeline:
                    type: array
                    description: |
                      **What happened on the call, as one time-ordered list.** The same rows the call log
                      shows in the dashboard, read from the same place, so an agent building on this API
                      and a person reading the screen never see two different accounts of one call.

                      Every row carries `kind` and `at`; the rest of its fields depend on the kind:

                      - `call` — the call's own moments, as `event`: `placed` (dialled, arrived, or its browser
                        session opened - `started_at`), `answered` (its audio came up - `answered_at`;
                        absent on a call that never got that far) and `ended` (`ended_at`; absent while the
                        call is going on). Each row's `at` is its field's value. The gap between the first
                        two is ringing.
                      - `message` — a transcript turn: `role`, `text`, `offset_ms` (ms from when the call was
                        answered). `at` is `answered_at` + `offset_ms`.
                      - `phase` — a stage of the call: `lane` (`before` / `during`), `scope`, `status`, and, when it
                        did not work out, `error` (a sentence) and `code` (`cancelled`, `expired`, `declined`,
                        `inputs_invalid` or `did_not_finish`; null otherwise). A call that completed, or was
                        handed to a person (`transferred`), reads its `during` stage `succeeded`, whoever ended
                        it: a failed `during` stage goes with a failure. A `before` stage can stay `failed` on a
                        call that still connected, when the agent is set to carry on without what it could not
                        get. A call that failed gets one row for the failure itself — `scope: "call"`,
                        `status: "failed"`, carrying the same sentence as `failure.reason` and `failure.code`
                        as its `code` — unless the call's own stages already report the failure, in which
                        case those rows are the account of it and none is added.
                      - `transition` — the conversation moving: `from_node` / `from_label`, `to_node` / `to_label`,
                        the `edge_id` and `edge_condition` of the route that fired, `edge_scope`
                        (`direct`, or `global` for a route reachable from anywhere), and `strict` —
                        `true` when the row comes from the authoritative stage cursor the agent's
                        conversation holds, `false` when it is the agent's own record of the stage it
                        entered. An agent whose conversation has no stages produces no `transition` rows;
                        `edge_condition` is only ever set on a `strict` row.
                      - `tool` — one tool invocation, typed by `tool_type`. Every agent's tools are here,
                        however the agent is built — a staged conversation's invocations and a
                        single-prompt agent's own webhook, transfer and end-of-call records read back in
                        the same shape:
                        `http` adds `method`, `url_host` (the host only), `request_bytes`, `response_status`;
                        `app` adds `app`, `action` and `connection_label`;
                        `transfer` adds `destination`;
                        `end` adds `reason` and `ended_by`.
                        All of them carry `name`, `step_id`, `lane` (the stage the step ran in: `before`,
                        `during`, or `after` for a follow-up once the call ended), `status`, `duration_ms`,
                        `attempt_count` and, when something went wrong, `error` — one sentence — plus `failure`, the
                        stable code behind that sentence: `failure.code` is one of `tool_timeout`,
                        `tool_unreachable`, `tool_rejected`, `transfer_failed` or `tool_failed`, and a
                        `tool_timeout` also carries `failure.limit_seconds`, the limit the tool ran past.
                        A tool that timed out keeps `status: "pending"` on purpose — nothing answered, so
                        whether the action happened is unknown and may need reconciling — and `failure`
                        is how you tell that apart from a step still running. A row nothing went wrong
                        with has no `failure` member at all.
                        A follow-up step whose inputs are read from the call by description also carries
                        `reads`: one entry per such input - `input`, `instruction` (the author's own
                        description) and `outcome` (`read`, `fallback` when the call did not say it and the
                        author's fixed value was sent, or `missing`). The value is not in the timeline; what
                        the step sent is in `tool_calls[]`.
                      - `skipped` — a follow-up step that did not run because the call did not give it a value
                        it reads by description: `lane` (`after`), `scope`, `step_id`, `name`, `reason`
                        (`extraction_missing`, or `dependency_skipped` when a step it depends on was skipped)
                        and `reads`. Nothing was sent, and a skipped step is not a failure.
                      - `trigger` — an after-call follow-up the workspace authored: the `event` that opened it,
                        its `steps`, its `status`.
                      - `delivery` — one row of the webhook delivery ledger: `id` (the same id
                        `GET /deliveries` lists), `tool_id`, `agent_id`, `event`, `status`,
                        `response_status`, `attempt_count`, `error_message`, `delivered_at` (null unless it
                        was delivered), `tool_name`, and `retry_of` / `retried_by` linking a retry and the
                        delivery it re-sent.

                      **`status` is one of three words** on every row that has one — `succeeded`,
                      `failed`, or `pending` (it has not settled yet) — except a `delivery`, which
                      carries the ledger's own `delivered`, `failed`, `pending` or `unknown` (no answer
                      came in time, so your endpoint may have acted; check there). A row may have no
                      `status` at all when the agent's own record of the step never came back. Branch
                      on those values and, on a `tool` row, on `failure.code`; `error` is a sentence for
                      a person to read, not to match on.

                      **Summaries only.** A URL's path and query, request headers, credentials, the account
                      behind a connected app, and raw request or response bodies are never returned in
                      these rows. (The older `tool_calls` and `events` members above still return them, with
                      auth headers redacted; that is what they are for, and why they are superseded.)
                      Full request/response: `tool_calls[]`, joined by a `tool` row's `exchange_id`.
                      Omitted if the call's timeline is momentarily unavailable.
                    items:
                      type: object
                      additionalProperties: true
                      properties:
                        kind:
                          type: string
                          enum: [call, message, phase, transition, tool, trigger, delivery, skipped]
                        at: { type: string, format: date-time, description: "ISO 8601 in UTC, written with +00:00, like every timestamp on the call." }
                        event: { type: string, description: "On a call row: placed, answered or ended - requested in place of placed on a call that ended without being answered. On a trigger or delivery row: the event it ran on." }
                        code: { type: [string, 'null'], description: "On a phase row: why it did not work out (cancelled, expired, declined, inputs_invalid, did_not_finish; the failure's code on the call's own failure row), null when it did." }
                        error_code: { type: string, description: "On a tool or delivery row that did not work out: the code GET /deliveries gives the same failure, from its error_code list (for example downstream_http_error, http_timeout or http_network_error). A code added to that list reaches this field too; read one you do not know as delivery_failed. Absent on a row that worked or has not settled." }
                        exchange_id: { type: string, description: "On a tool row with a full record: its id, the matching `tool_calls[].id` (what was sent and got back). Absent otherwise." }
                      required: [kind, at]
                  ab_variant:
                    type: string
                    enum: [a, b]
                    nullable: true
                    description: "Which side of the number's A/B split ran this call. Present only on a number that is actually running a split."
                  ab_variant_fallback:
                    type: boolean
                    description: "True when the split picked B but the call went to A anyway, because B could not take it. Present only alongside `ab_variant`."
                  failure:
                    description: >
                      Why the call did not complete. Present only on a call whose status is failed or
                      no_answer; a call that completed has no failure member at all, so check for the
                      member rather than for a value inside it. A call ended on purpose from outside it
                      (ended_by operator) has none either.
                    allOf:
                      - $ref: "#/components/schemas/CallFailure"
                  analysis:
                    description: >
                      Where the post-call analysis stands. Always present — this is how you tell a
                      summary that is still coming from one that is never coming.
                    allOf:
                      - $ref: "#/components/schemas/CallAnalysis"
                  follow_ups:
                    description: >
                      Which of the agent's follow-ups did not run on this call, and why. Absent
                      when there is nothing to explain, so check for the member rather than for a
                      value inside it.
                    allOf:
                      - $ref: "#/components/schemas/CallFollowUps"
                  flow_trace:
                    nullable: true
                    description: |
                      **Present only on flow-agent calls** (`agent.type='flow'`). For prompt agents this field is omitted.
                      Structured view of the call's path through the flow graph, built from the underlying `flow_*` events.
                      Flow tool and integration results are also included in `tool_calls[]`, with `kind` set to
                      `tool_call` or `integration_call`. The same results appear inline on each
                      `flow_trace.steps[].tool_call` for graph-oriented investigation.
                    allOf:
                      - $ref: "#/components/schemas/FlowTrace"
                  execution_status:
                    type: string
                    enum: [included, omitted, pending, none]
                    description: >
                      What `execution` is on this read - not the `execution_status` query parameter, which
                      filters the history's rows by their own status. `included`: the whole block. `omitted`: you sent
                      `omit=execution`, and `execution` is an ExecutionSettlement. `pending`: the history did not
                      answer in time - `execution` is an ExecutionSettlement, and a read again brings the block
                      (send `execution_limit` to be told 503 instead). `none`: the call has no execution history,
                      and there is no `execution` member.
                  execution:
                    oneOf:
                      - $ref: '#/components/schemas/CallExecution'
                      - $ref: '#/components/schemas/ExecutionSettlement'
        "400":
          description: CALLS_QUERY_INVALID — a query parameter other than the five execution-history ones, or one of them sent twice or with no value; the message names it.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: INSUFFICIENT_SCOPE — the key holds neither `calls:read` nor `calls:metrics`, or holds only `calls:metrics` and asked for the execution history.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "410":
          description: EXECUTION_RETENTION_EXPIRED — the `execution_cursor` points at history that is no longer retained. Read again without it.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "422":
          description: EXECUTION_CURSOR_INVALID — an `execution_cursor` this read did not issue or that was sent with other filters, or an `execution_limit` or filter value the history does not have. Follow `execution.history.next_url` rather than building one.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "503":
          description: EXECUTION_READ_UNAVAILABLE — execution history was asked for and could not be read. Temporary; retry the same request.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /calls/{id}/end:
    post:
      summary: End a browser session nobody has opened
      operationId: endPendingWebCall
      tags: [Calls]
      description: >
        Requires calls:create. Ends a browser session minted with POST /calls {"type":"web"} that
        no browser has opened yet (status pending_connection): the call settles at once as
        status no_answer, ended_by operator, disconnect_reason "Ended by operator", cost 0 and no
        failure member (you ended it; it did not fail), and a browser that
        later tries the session's token is turned away. It takes no body. It is not a hang-up: a
        call a browser has already opened, or one that has settled, is refused with 409
        CALL_NOT_PENDING and left as it is.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: The session was ended.
          content:
            application/json:
              schema:
                type: object
                required: [id, status, ended_at, ended_by]
                properties:
                  id: { type: string, format: uuid }
                  status: { type: string, enum: [no_answer] }
                  ended_at: { type: string, format: date-time }
                  ended_by: { type: string, enum: [operator] }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '400':
          description: CALL_END_INVALID - the body had something in it. Ending takes no body (send none, or {}); the message names what to remove. Nothing was changed.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404':
          description: NOT_FOUND - no such call in this workspace (or one a key limited to other agents cannot see). An id that is not an id at all is RESOURCE_ID_INVALID.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '409':
          description: CALL_NOT_PENDING - the call is not a browser session waiting to be opened (a browser opened it, it is a phone call, or it has settled). `status` in the body names the state it is in. Nothing was changed.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '503':
          description: CALL_END_UNAVAILABLE - the call could not be read or written just then. Nothing was changed; send the same request again.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /calls/{id}/recording:
    get:
      summary: Get call recording
      description: >
        Answers 200 with the audio file of the call's recording itself, not a
        redirect, typed as the file is stored: `audio/ogg` when Yappr recorded
        the call (every browser call), `audio/mpeg` when the phone carrier did.
        No Authorization header required — the `exp` and `sig` query parameters
        (included in the `recording_url` from GET /calls responses)
        serve as authentication. Open directly in a browser, use as
        an `<audio>` src, or fetch it as is. HEAD answers the GET's headers with
        no body. A HEAD without a Range answers from Yappr's record of the file
        without reading the audio - the stored file's record, or the record kept
        of a phone carrier's recording (written when it is saved; an older one is
        looked up at the carrier on its first read, which keeps one) - so it
        answers 200 where a GET answers 404 (the carrier has since deleted its
        file) or 503 (the audio's store is not answering). A HEAD with a Range
        reads the audio and answers as a GET would; send `Range: bytes=0-0` to
        check that the audio can still be fetched. A `Range` header is honoured: 206 with those bytes
        and a `Content-Range`, or 416 when it starts past the end. Every answer,
        refusals too, is `Cache-Control: private, no-store`. A link lasts
        7 to 8 days (`exp` is 00:00 UTC on the eighth day after the day it was
        issued) and stops opening when the call's links are revoked; read the
        call again for a current one. Python's built-in urllib (`User-Agent:
        Python-urllib/3.x`) is refused at the edge with 403 `error code: 1010`
        until an edge rule is lifted; send any other User-Agent. A link issued before links started expiring
        has no `exp` and opens until the call's links are revoked. A refusal
        is JSON, except to a browser (a GET whose Accept includes text/html),
        which gets the same status with a short page saying why.
      operationId: getCallRecording
      tags: [Calls]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
        - in: query
          name: exp
          required: false
          schema: { type: integer }
          description: "When the link stops opening, in Unix seconds: 00:00 UTC on the eighth day after the day it was issued. Part of the signed link; do not change it."
        - in: query
          name: sig
          required: true
          schema: { type: string }
          description: "Signature included in the `recording_url` from call responses. Do not construct this manually."
        - in: header
          name: Range
          required: false
          schema: { type: string }
          example: "bytes=0-99"
          description: "One byte range. Answers 206 with those bytes; without it the whole file is 200."
      responses:
        "200":
          description: The whole audio file. HEAD answers these headers with no body.
          headers:
            Content-Length:
              schema: { type: integer }
              description: The file's size in bytes.
            Accept-Ranges:
              schema: { type: string }
              description: "`bytes`"
            Content-Disposition:
              schema: { type: string }
              description: "`attachment; filename=\"recording-<call id>-<YYYY-MM-DD>.ogg\"` (or `.mp3`): the call and the day it started, in UTC."
            ETag:
              schema: { type: string }
              description: The stored file's entity tag; it changes only if the file does. Listed in Access-Control-Expose-Headers.
            Last-Modified:
              schema: { type: string }
              description: When the stored file was written. Listed in Access-Control-Expose-Headers.
            Access-Control-Expose-Headers:
              schema: { type: string }
              description: "`Content-Length, Content-Range, Accept-Ranges, Content-Disposition, ETag, Last-Modified`"
            Cache-Control:
              schema: { type: string }
              description: "`private, no-store`, on every answer including refusals."
          content:
            audio/ogg:
              schema: { type: string, format: binary }
            audio/mpeg:
              schema: { type: string, format: binary }
        "206":
          description: The bytes the Range header asked for.
          headers:
            Content-Range:
              schema: { type: string }
              description: "`bytes <first>-<last>/<size>`"
            Content-Length:
              schema: { type: integer }
          content:
            audio/ogg:
              schema: { type: string, format: binary }
            audio/mpeg:
              schema: { type: string, format: binary }
        "403":
          description: "RECORDING_LINK_EXPIRED (past its exp), RECORDING_LINK_REVOKED (the call's links were revoked since), or RECORDING_LINK_INVALID (not issued by Yappr, or changed; or sent without its sig, which an API key does not replace). Read the call again for a current link. A browser gets a short page instead of JSON."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
            text/html:
              schema: { type: string }
        "404":
          description: "NOT_FOUND: call not found, or no recording can be served (not stored yet, or no longer fetchable) - for any link to such a call, signed or not. GET /calls and GET /calls/{id} leave recording_url out for such a call. A HEAD without a Range answers 200 instead when it answers from the record kept of a phone carrier's recording the carrier has since deleted. A browser gets a short page instead of JSON."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
            text/html:
              schema: { type: string }
        "416":
          description: "The Range starts past the end of the file; no body."
          headers:
            Content-Range:
              schema: { type: string }
              description: "`bytes */<size>`, on a 416 whenever the file's size can be read."
            ETag:
              schema: { type: string }
              description: The stored file's entity tag, whenever it can be read.
            Last-Modified:
              schema: { type: string }
              description: When the stored file was written, whenever it can be read.
        "503":
          description: "RECORDING_LINK_UNAVAILABLE: the link could not be checked, or the audio fetched, just now (including an audio store that does not start answering within a few seconds). Try again. A HEAD without a Range that answers from the file's record does not wait on the audio's store, so it answers 200 there. A browser gets a short page instead of JSON."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
            text/html:
              schema: { type: string }

  /calls/{id}/recording/revoke:
    post:
      summary: Revoke recording links
      description: >
        Requires calls:create. Takes back every recording link issued for this call so far,
        including links from before links started expiring, which have no exp: from then on they
        answer 403 RECORDING_LINK_REVOKED. Answers with a new working link, and later reads of the
        call return new links too. The recording itself is not deleted. It takes no body and no query
        parameters; anything sent is refused by name with 400 RECORDING_REVOKE_INVALID.
        The call's updated_at moves to revoked_at, so a sync on updated_since (even
        updated_since=revoked_at) reads the new link.
      operationId: revokeCallRecordingLinks
      tags: [Calls]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Every earlier link for the call is revoked.
          content:
            application/json:
              schema:
                type: object
                required: [call_id, revoked_at]
                properties:
                  call_id: { type: string, format: uuid }
                  revoked_at: { type: string, format: date-time }
                  recording_url:
                    type: string
                    description: A new link that works. Absent (never null) when the call has no recording yet, or none the link can serve, as GET /calls and GET /calls/{id} leave it out.
        "400":
          description: "RECORDING_REVOKE_INVALID: a body field or query parameter was sent. Nothing was revoked. issues[] names each one: a body field as field_unknown at /<field>, a query parameter at its name."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "RESOURCE_ID_INVALID: the id in the path is not a call id. NOT_FOUND: no call with this id in this workspace, or a call of an agent the key is not limited to."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: "RECORDING_LINK_UNAVAILABLE: nothing was revoked. Try again."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /call-requests:
    post:
      summary: Create web call request
      operationId: createWebCallRequest
      tags: [Calls]
      description: >
        Requires calls:create. Creates a browser call on a workflow agent (with or without steps before it answers or
        follow-ups after the call), and returns the capability the
        browser needs to follow and start it. Nothing is dialled, no call record is created and no line is held: the caller's
        browser starts the call itself once the steps are done.


        Use this when an agent's mint answers `protocol: "call_request"`. An agent the mint answers
        `offer` for does not need it - POST /calls with `type: "web"` mints a session token and the
        browser sends one offer, exactly as before.


        The `start_capability` is returned once and stored only as a hash. It authorises this one
        request's read, cancel and start and nothing else, it dies with the request, and it is
        safe to hand to a browser: it cannot read another request, a phone request, or anything
        about the workspace.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [type, agent_id]
              additionalProperties: false
              properties:
                type: { type: string, enum: [web], description: "A phone call is created with POST /calls." }
                agent_id: { type: string, format: uuid }
                variables: { type: object, description: "Values the workflow's request schema declares. Rendered into the prompt and readable by before-call steps." }
                metadata: { type: object, description: Stored on the call record and echoed to tools. Reserved platform key names are refused. }
                workflow_revision_id: { type: string, format: uuid, description: Pin a published version of this agent's workflow instead of following the current one. }
      parameters:
        - in: header
          name: Idempotency-Key
          required: false
          schema: { type: string, maxLength: 200 }
          description: >
            Visible ASCII, space excluded. The same key with the same body answers 200 with the
            request as it is now and no start_capability (see the 200 response); with a
            different body it is a conflict.
      responses:
        '200':
          description: >
            This Idempotency-Key already created a request (with the same body). The request as
            it is now - the CallRequest fields, `request_id`, `type`, `agent_id`, `accepted_at`,
            the three URLs and `replayed: true` - and no `start_capability`: the one that works
            was returned once, by the first create, and is stored only as a hash. A request that
            already failed reads `failed` with its `error_code` here, not `preparing`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CallRequest'
                  - type: object
                    required: [request_id, replayed, status_url, cancel_url, start_url]
                    properties:
                      request_id: { type: string, format: uuid }
                      type: { type: string, enum: [web] }
                      agent_id: { type: [string, 'null'], format: uuid }
                      accepted_at: { type: [string, 'null'], format: date-time }
                      replayed: { type: boolean, enum: [true] }
                      status_url: { type: string, format: uri }
                      cancel_url: { type: string, format: uri }
                      start_url: { type: string, format: uri }
        '202':
          description: Accepted. The steps have not run yet.
          content:
            application/json:
              schema:
                type: object
                required: [request_id, run_id, channel, status, preparation_status, expires_at, start_capability, status_url, cancel_url, start_url]
                properties:
                  id: { type: string, format: uuid, description: Same value as request_id on this channel. }
                  request_id: { type: string, format: uuid }
                  run_id: { type: string, format: uuid }
                  call_id: { type: [string, 'null'], description: Always null here. A browser call has no call record until it is started. }
                  type: { type: string, enum: [web] }
                  channel: { type: string, enum: [web] }
                  status: { type: string, enum: [preparing, scheduled] }
                  preparation_status: { type: string, enum: [pending] }
                  agent_id: { type: string, format: uuid }
                  accepted_at: { type: string, format: date-time }
                  expires_at: { type: string, format: date-time, description: After this the request is abandoned and the capability stops working. }
                  start_capability: { type: string, description: "Returned once. Send it as the x-yappr-call-request-key header on read, cancel and start." }
                  status_url: { type: string, format: uri }
                  cancel_url: { type: string, format: uri }
                  start_url: { type: string, format: uri }
        '400':
          description: INVALID_AGENT_ID, or a variables/metadata value that is not an object, or a body whose type is not "web".
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: AGENT_NOT_FOUND - this workspace has no agent with that id., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409':
          description: >
            WORKFLOW_AGENT_INACTIVE - the agent exists but is switched off; PATCH it with
            is_active true and ask again. A copy made with POST /agents/{id}/duplicate starts
            switched off, so this is the usual answer on a freshly duplicated agent.
            WORKFLOW_UNPUBLISHED - this agent's workflow has never been published.
            WORKFLOW_NOT_ENABLED - this agent does not run a workflow, so it has nothing to
            prepare; mint a browser session with POST /calls {"type":"web"} instead.
            WORKFLOW_IDEMPOTENCY_CONFLICT - this key was used with a different body.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '422':
          description: WORKFLOW_REQUEST_INVALID or WORKFLOW_PIN_INVALID — the body or the pinned revision is not usable.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '503':
          description: WORKFLOW_ADMISSION_UNAVAILABLE — temporary; retry the same request.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /call-requests/{id}/start:
    post:
      summary: Start web call request
      operationId: startWebCallRequest
      tags: [Calls]
      description: >
        Requires calls:create, plus the request's own `start_capability` in the
        x-yappr-call-request-key header. Sends a fresh SDP offer for a request that has reached
        `ready`, takes a line, and returns the answer the browser completes the connection with.


        A start is one offer. Sending the same offer again returns the same peer, so a lost
        response is recovered rather than turned into a second call; sending a different one is
        refused, because the request has already spent its start. A `503` here is refused before
        anything is claimed, so the preparation is still worth starting - poll and try again.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
        - in: header
          name: x-yappr-call-request-key
          required: true
          schema: { type: string }
          description: The `start_capability` this request was created with.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sdp, type]
              properties:
                sdp: { type: string, description: "A fresh SDP offer from a peer connection created now, not before the steps ran." }
                type: { type: string, enum: [offer] }
      responses:
        '201':
          description: The call is live. Complete the WebRTC connection with this answer.
          content:
            application/json:
              schema:
                type: object
                required: [sdp, type, pc_id, call_id, request_id]
                properties:
                  sdp: { type: string }
                  type: { type: string, enum: [answer] }
                  pc_id: { type: string, description: Peer id. Trickle ICE candidates and hang up against ice_candidate_url with it. }
                  ice_candidate_url: { type: string, format: uri }
                  call_id: { type: string, format: uuid, description: "Read it with GET /calls/{id} once the call ends." }
                  request_id: { type: string, format: uuid }
                  run_id: { type: string, format: uuid }
                  replayed: { type: boolean, description: True when this is the receipt of a start that already happened. }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope. CALL_REQUEST_KEY_REQUIRED - no x-yappr-call-request-key header (and no start_capability in the body) was sent.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '402':
          description: WORKFLOW_BILLING_UNAVAILABLE — this workspace is out of credit.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '403':
          description: WORKFLOW_START_DENIED — the capability does not belong to that request. The same answer covers a wrong capability, a missing request and a phone request.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '404':
          description: WORKFLOW_REQUEST_NOT_FOUND — no such request in this workspace.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '409':
          description: >
            WORKFLOW_START_NOT_READY - the before-call steps have not finished; poll until the
            request reports ready. WORKFLOW_START_ALREADY_CLAIMED - this request has already been
            started with a different offer. WORKFLOW_REQUEST_CANCELLED - it was cancelled.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '410':
          description: WORKFLOW_START_EXPIRED — the request outlived its expiry. Create a new one.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '502':
          description: WEB_START_REFUSED — the voice runtime refused the offer. The line was given back and the request is finished; create a new one.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '503':
          description: >
            AT_CAPACITY - every line is busy and nothing was claimed, so poll and start again.
            WEB_START_UNAVAILABLE - the voice runtime never answered; the line was given back and
            the request is finished.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /call-requests/{id}:
    get:
      summary: Get call request
      operationId: getCallRequest
      tags: [Calls]
      description: >
        Requires calls:read. Reads one accepted call request for a workflow agent: an outbound
        one (the `request_id` POST /calls returned) or a browser one (`channel: "web"`, the
        `request_id` POST /call-requests or the browser's own POST /web-call/call-requests
        returned). A `call_request` Web SDK session is read back this way: the page hands your
        server the `request_id` its call request answered with. The request is the record of
        everything that happens before a call exists; once `call_id` is set, the call itself is
        read with GET /calls/{id}.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
        - { $ref: "#/components/parameters/ExecutionLimit" }
        - { $ref: "#/components/parameters/ExecutionCursor" }
        - { $ref: "#/components/parameters/ExecutionPhase" }
        - { $ref: "#/components/parameters/ExecutionKind" }
        - { $ref: "#/components/parameters/ExecutionStatus" }
      responses:
        '200':
          description: Current state of the request.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CallRequest' }
        '400':
          description: CALLS_QUERY_INVALID — a query parameter other than the five execution-history ones, or one of them sent twice or with no value; the message names it.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404':
          description: WORKFLOW_REQUEST_NOT_FOUND — no such request in this workspace. An id that is not an id at all is RESOURCE_ID_INVALID.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '405': { description: Use GET here; cancellation has its own path., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '410':
          description: EXECUTION_RETENTION_EXPIRED — the `execution_cursor` points at history that is no longer retained. Read again without it.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '422':
          description: EXECUTION_CURSOR_INVALID — an `execution_cursor` this read did not issue or that was sent with other filters, or an `execution_limit` or filter value the history does not have. Follow `execution.history.next_url` rather than building one.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '503':
          description: WORKFLOW_ADMISSION_UNAVAILABLE — temporary; retry the same request. EXECUTION_READ_UNAVAILABLE — execution history was asked for and could not be read; retry the same request.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /call-requests/{id}/cancel:
    post:
      summary: Cancel call request
      operationId: cancelCallRequest
      tags: [Calls]
      description: >
        Requires calls:create — the same permission that created the request. A key that can
        only read calls must not be able to stop one, and a key that can start a call may stop
        the one it started. Cancelling is safe to repeat: an already-cancelled request answers
        200 with the same state. It prevents a call that has not been placed yet; it is not a
        hang-up. A request that already failed, expired or became a call is refused 409
        CALL_REQUEST_FINAL and keeps its status and error_code.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: State of the request after cancellation.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CallRequest' }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted. A valid key without the scope this operation needs is 403 INSUFFICIENT_SCOPE, naming the scope.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404':
          description: WORKFLOW_REQUEST_NOT_FOUND — no such request in this workspace. An id that is not an id at all is RESOURCE_ID_INVALID.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '405': { description: Use POST here., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409':
          description: >
            CALL_REQUEST_FINAL — the request already failed, expired or became a call, so there is
            nothing left to cancel; nothing was written. The body carries its `status`,
            `error_code` and `call_id` beside `error` and `code`. WORKFLOW_DISPATCH_ALREADY_CLAIMED
            — placement has started, so the request can no longer be cancelled. Cancelling is not
            a hang-up; read the call instead.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '503':
          description: WORKFLOW_ADMISSION_UNAVAILABLE — temporary; retry the same request.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /web-call/cancel:
    x-yappr-plane: browser
    servers:
      - url: https://api.goyappr.com
        description: Browser data plane, on the API host (the web mint's connection.host). Takes a session token, a call request's capability or a shared link - never the secret key.
    post:
      summary: Cancel a browser session (data plane)
      operationId: cancelWebSession
      tags: [Calls]
      security: []
      description: >
        The browser data plane, not the secret-key API: the session's `cancel_url` from
        POST /calls {"type":"web"}. Authorized by the session token itself, sent as
        `x-yappr-web-token`, so your server or the page you handed the token to can take back a
        session nobody will use. Send no body, or `{}`. The token is spent so no browser can use
        it; an `offer` session's call settles at once as POST /calls/{id}/end settles it. Safe
        to repeat. Once cancelled, a browser that still presents the token is refused
        `403 WEB_SESSION_CANCELLED` by the offer and by the call request alike. Once a page has
        created a call request with the token, this cancels that request as
        POST /call-requests/{id}/cancel does, and the answer names it (`request_id`).
      parameters:
        - in: header
          name: x-yappr-web-token
          required: true
          schema: { type: string }
          description: The session token (`wcs_…`).
      responses:
        '200':
          description: Cancelled (or already expired). `call_id` is null for a `call_request` session. A token that created a call request answers with that request cancelled and its `request_id`.
          content:
            application/json:
              schema:
                type: object
                required: [status, call_id]
                properties:
                  status: { type: string, enum: [cancelled, expired] }
                  call_id: { type: [string, 'null'], format: uuid }
                  request_id: { type: string, format: uuid, description: Only when the token created a call request - the request this cancelled. }
        '400':
          description: WEB_SESSION_CANCEL_INVALID — a body with a field in it, or one that is not JSON. Send none, or `{}`.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '401': { description: 'No token, or one that is not a session token.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '405': { description: Use POST here., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409':
          description: WEB_SESSION_ALREADY_USED — a browser spent this token on a one-shot offer; end the call it started. CALL_REQUEST_FINAL — the call request this token created already failed, expired or became a call; the body carries its status, error_code, call_id and request_id, and nothing was written.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /web-call/call-requests:
    x-yappr-plane: browser
    servers:
      - url: https://api.goyappr.com
        description: Browser data plane, on the API host (the web mint's connection.host). Takes a session token, a call request's capability or a shared link - never the secret key.
    post:
      summary: Create a browser call request (data plane)
      operationId: createBrowserCallRequest
      tags: [Calls]
      security: []
      description: >
        The browser data plane: what `@goyappr/client` calls when a mint answers
        `protocol: "call_request"`, with the session token as `x-yappr-web-token` (a shared
        link's page sends `x-share-token` instead). Accepts the call request exactly as
        POST /call-requests does and answers the same `202`, including the
        `start_capability` that authorizes the read, cancel and start below. The same token
        asking again gets the same request: a `200` with the request as it is now and no new
        capability, exactly as POST /call-requests answers a repeated Idempotency-Key. Hand the
        `request_id` to your server to read the request with GET /call-requests/{id}.
      parameters:
        - in: header
          name: x-yappr-web-token
          required: false
          schema: { type: string }
          description: The session token from POST /calls {"type":"web"}.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: The session names the agent, its variables and its metadata; a token-authorized request sends `{}`.
      responses:
        '200':
          description: This token already created a request - the request as it is now, `replayed` true and no `start_capability`, as POST /call-requests answers a repeated key.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/CallRequest'
                  - type: object
                    required: [request_id, replayed, status_url, cancel_url, start_url]
                    properties:
                      request_id: { type: string, format: uuid }
                      type: { type: string, enum: [web] }
                      agent_id: { type: [string, 'null'], format: uuid }
                      accepted_at: { type: [string, 'null'], format: date-time }
                      replayed: { type: boolean, enum: [true] }
                      status_url: { type: string, format: uri }
                      cancel_url: { type: string, format: uri }
                      start_url: { type: string, format: uri }
        '202':
          description: Accepted, as POST /call-requests answers it - the request, its `start_capability` and the three URLs, on this host.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CallRequestAccepted' }
        '400':
          description: >
            CALL_REQUEST_FIELD_NOT_ALLOWED — `metadata` or `variables` in the body of a token- or
            link-authorized request. A Web SDK session carries the values it was minted with: set
            them on POST /calls {"type":"web"} and send `{}` here.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '401': { description: 'UNAUTHORIZED - a token or share link that is not one of ours, or no token, link or sign-in at all.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403':
          description: >
            WEB_SESSION_CANCELLED — the token was taken back with its cancel_url; mint a new
            session. FORBIDDEN "This session token has expired" — it ran out. A revoked or
            expired shared link is refused the same way.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '409':
          description: >
            WEB_SESSION_PROTOCOL_OFFER — the token was minted for protocol "offer": send the
            browser's SDP offer to POST /web-call with it instead.
            SESSION_TOKEN_EXPIRES_TOO_SOON / SHARE_LINK_EXPIRES_TOO_SOON — less than the
            five-minute preparation window is left; mint a new session. Only a new request is
            refused: a token that already created one gets that request back (the `200`),
            however little time it has left. The lifecycle refusals of POST /call-requests apply
            too.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '503':
          description: >
            WORKFLOW_ADMISSION_UNAVAILABLE — temporary; retry. AUTH_UNAVAILABLE — a dashboard
            sign-in could not be checked just now (not a refused sign-in); retry after the
            Retry-After header's seconds, with the same Idempotency-Key to get the same request.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /web-call/call-requests/{id}:
    x-yappr-plane: browser
    servers:
      - url: https://api.goyappr.com
        description: Browser data plane, on the API host (the web mint's connection.host). Takes a session token, a call request's capability or a shared link - never the secret key.
    get:
      summary: Poll a browser call request (data plane)
      operationId: pollBrowserCallRequest
      tags: [Calls]
      security: []
      description: >
        The browser's own poll, authorized by the request's `start_capability` alone. Answers
        the CallRequest plus `company_id`, `agent_id` and `preparation_steps`: each before-call
        step's label and status, and for one that did not succeed, what its tool answered
        (`error_code`, `http_status`) - never its result.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
        - in: header
          name: x-yappr-call-request-key
          required: true
          schema: { type: string }
          description: The `start_capability` this request was created with.
      responses:
        '200':
          description: Current state of the request.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CallRequest' }
        '401':
          description: CALL_REQUEST_KEY_REQUIRED — no x-yappr-call-request-key header was sent. A capability that is sent and is not this request's is the 403.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '403':
          description: WORKFLOW_START_DENIED — the capability does not belong to that request. The same answer covers a missing request and a phone request.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '405': { description: Use GET here., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /web-call/call-requests/{id}/cancel:
    x-yappr-plane: browser
    servers:
      - url: https://api.goyappr.com
        description: Browser data plane, on the API host (the web mint's connection.host). Takes a session token, a call request's capability or a shared link - never the secret key.
    post:
      summary: Cancel a browser call request (data plane)
      operationId: cancelBrowserCallRequest
      tags: [Calls]
      security: []
      description: >
        Authorized by the request's `start_capability`. Stops a request that has not started,
        as POST /call-requests/{id}/cancel does, with the same answers: a request that already
        failed, expired or became a call is 409 CALL_REQUEST_FINAL and keeps its `status` and
        `error_code`; an already-cancelled one answers 200 again. One difference: a request
        that was started (`dispatched`) but whose call has not connected yet (the call still
        reads `ringing`) is not refused. That call ends at once as `no_answer`, ended by the
        caller, and the answer is 200 with the request plus `call_status`, `ended_by` and
        `ended_at`. A call that connected is ended by hanging up, and keeps the 409.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
        - in: header
          name: x-yappr-call-request-key
          required: true
          schema: { type: string }
      responses:
        '200':
          description: >
            State of the request after the cancel. When the cancel ended a started call that
            had not connected, the request (still `dispatched`, with its `call_id`) also
            carries `call_status`, `ended_by` and `ended_at`.
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: '#/components/schemas/CallRequest' }
                  - type: object
                    properties:
                      call_status:
                        type: string
                        enum: [no_answer]
                        description: Only when this cancel ended the request's call while it was still connecting.
                      ended_by:
                        type: string
                        enum: [caller]
                        description: Only when this cancel ended the call.
                      ended_at:
                        type: string
                        format: date-time
                        description: When this cancel ended the call. Only when it did.
        '401':
          description: CALL_REQUEST_KEY_REQUIRED — no x-yappr-call-request-key header was sent. A capability that is sent and is not this request's is the 403.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '403':
          description: WORKFLOW_START_DENIED — the capability does not belong to that request.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '405': { description: Use POST here., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409':
          description: >
            CALL_REQUEST_FINAL — the request already failed, expired or became a call that
            connected (or had already ended); its `status`, `error_code` and `call_id` ride in
            the body and nothing was written. WORKFLOW_DISPATCH_ALREADY_CLAIMED — the call has
            started; end it instead.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /web-call/call-requests/{id}/start:
    x-yappr-plane: browser
    servers:
      - url: https://api.goyappr.com
        description: Browser data plane, on the API host (the web mint's connection.host). Takes a session token, a call request's capability or a shared link - never the secret key.
    post:
      summary: Start a browser call request (data plane)
      operationId: startBrowserCallRequest
      tags: [Calls]
      security: []
      description: >
        Authorized by the request's `start_capability`. The same start as
        POST /call-requests/{id}/start - a fresh SDP offer for a request that reports `ready`,
        answered `201` with the SDP answer, `pc_id`, `ice_candidate_url` and `call_id` - with the
        same refusals.
      parameters:
        - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
        - in: header
          name: x-yappr-call-request-key
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sdp, type]
              properties:
                sdp: { type: string }
                type: { type: string, enum: [offer] }
                wait_for_ready_ms:
                  type: integer
                  minimum: 0
                  description: >
                    Optional. Send the offer while the request is still preparing and let the start
                    wait up to this many milliseconds (at most 15000) for it to read `ready`, instead of
                    polling first. Absent or 0, a request that is not ready is refused at once with
                    WORKFLOW_START_NOT_READY. A request whose steps failed is refused the same way once
                    the wait runs out; poll it to read why.
      responses:
        '201':
          description: The call is live. Complete the WebRTC connection with this answer.
          content:
            application/json:
              schema:
                type: object
                required: [sdp, type, pc_id, call_id, request_id]
                properties:
                  sdp: { type: string }
                  type: { type: string, enum: [answer] }
                  pc_id: { type: string }
                  ice_candidate_url: { type: string, format: uri }
                  call_id: { type: string, format: uuid }
                  request_id: { type: string, format: uuid }
                  run_id: { type: string, format: uuid }
                  replayed: { type: boolean }
        '400':
          description: INVALID_START_WAIT — wait_for_ready_ms is not a non-negative number of milliseconds.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '401':
          description: CALL_REQUEST_KEY_REQUIRED — no x-yappr-call-request-key header was sent. A capability that is sent and is not this request's is the 403.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '403':
          description: WORKFLOW_START_DENIED — the capability does not belong to that request.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '409':
          description: WORKFLOW_START_NOT_READY, WORKFLOW_START_ALREADY_CLAIMED or WORKFLOW_REQUEST_CANCELLED, as on POST /call-requests/{id}/start.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '410':
          description: WORKFLOW_START_EXPIRED — the request outlived its expiry. Create a new one.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '502':
          description: WEB_START_REFUSED — the voice server refused the offer; the request is finished.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '503':
          description: AT_CAPACITY (nothing claimed; poll and start again), WEB_START_UNAVAILABLE (the voice server never answered; the request is finished) or AUTH_UNAVAILABLE (a start aimed at the testing server could not check its sign-in just now; nothing was claimed; retry).
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /web-call:
    x-yappr-plane: browser
    servers:
      - url: https://api.goyappr.com
        description: Browser data plane, on the API host (the web mint's connection.host). Takes a session token, a call request's capability or a shared link - never the secret key.
    post:
      summary: Connect a browser call (data plane)
      operationId: offerBrowserCall
      tags: [Calls]
      security: []
      description: >
        The browser data plane: the mint's `connection.web_call_url`, where `@goyappr/client` posts
        the browser's SDP offer for a session minted with `protocol: "offer"`. Authorized by the
        session token as `x-yappr-web-token` (a shared link's page sends `x-share-token`, the
        dashboard its own sign-in), never the secret key. The token is single-use: the first offer
        spends it, and the call it starts is the session's `call_id`. An agent whose mint answers
        `protocol: "call_request"` is a workflow agent (steps or not) the workflow engine runs, and is
        refused here before the token is spent; use the call request below.
      parameters:
        - in: header
          name: x-yappr-web-token
          required: false
          schema: { type: string }
          description: The session token (`wcs_…`) from POST /calls {"type":"web"}.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sdp, type]
              properties:
                sdp: { type: string, description: The browser's SDP offer. }
                type: { type: string, enum: [offer] }
      responses:
        '201':
          description: The call is live. Complete the WebRTC connection with this answer, and send ICE candidates to `ice_candidate_url`.
          content:
            application/json:
              schema:
                type: object
                required: [call_id, sdp, type, pc_id]
                properties:
                  call_id: { type: string, format: uuid }
                  agent_name: { type: string }
                  sdp: { type: string }
                  type: { type: string, enum: [answer] }
                  pc_id: { type: string }
                  ice_candidate_url: { type: string, format: uri }
        '400':
          description: BAD_REQUEST — the body is not JSON, or has no `sdp` and `type`.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '401':
          description: UNAUTHORIZED — no session token, share link or sign-in, or one that is not one of ours.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '403':
          description: >
            WEB_SESSION_CANCELLED — the token was taken back with its cancel_url. FORBIDDEN — the token
            was already used or has expired, or the shared link was revoked or has expired. Mint a new
            session.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '409':
          description: workflow_preparation_required — this agent runs on the workflow engine, which a one-shot offer cannot start; create a browser call request with the same token instead. Nothing was spent.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '502':
          description: VOICE_CONNECTION_REFUSED — the voice server refused the offer. The call is recorded failed and the token is spent; mint a new session rather than resending the offer.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '503':
          description: VOICE_UNAVAILABLE — the voice server did not take the offer, or every line was busy. The call is recorded failed and the token is spent; mint a new session and try again in a moment.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /turn-credentials:
    x-yappr-plane: browser
    servers:
      - url: https://api.goyappr.com
        description: Browser data plane, on the API host (the web mint's connection.host). Takes a session token, a call request's capability or a shared link - never the secret key.
    post:
      summary: Fetch ICE servers for a browser call (data plane)
      operationId: browserTurnCredentials
      tags: [Calls]
      security: []
      description: >
        The mint's `connection.turn_credentials_url`: short-lived STUN and TURN servers for the
        browser's peer connection, fetched before the offer. Authorized like the offer - the
        session token as `x-yappr-web-token`, a shared link or a sign-in - and it does not spend the
        token. `GET` answers the same.
      parameters:
        - in: header
          name: x-yappr-web-token
          required: false
          schema: { type: string }
          description: The session token (`wcs_…`).
      responses:
        '200':
          description: ICE servers, in the shape RTCPeerConnection takes.
          content:
            application/json:
              schema:
                type: object
                required: [iceServers]
                properties:
                  iceServers:
                    type: array
                    items:
                      type: object
                      properties:
                        urls: { oneOf: [{ type: string }, { type: array, items: { type: string } }] }
                        username: { type: string }
                        credential: { type: string }
        '401':
          description: UNAUTHORIZED — no token, link or sign-in; a token or link that is not ours; or a session token that was already used or has expired. Mint a new session.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '403':
          description: WEB_SESSION_CANCELLED — the session token was taken back with its cancel_url. Mint a new session.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '405':
          description: METHOD_NOT_ALLOWED — use POST or GET.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    get:
      summary: Fetch ICE servers for a browser call, by GET (data plane)
      operationId: browserTurnCredentialsGet
      tags: [Calls]
      security: []
      description: >
        The same as POST /turn-credentials, for a browser that fetches with GET: the same
        authorization, the same ICE servers, the same refusals, and the token is not spent.
      parameters:
        - in: header
          name: x-yappr-web-token
          required: false
          schema: { type: string }
          description: The session token (`wcs_…`).
      responses:
        '200':
          description: ICE servers, in the shape RTCPeerConnection takes.
          content:
            application/json:
              schema:
                type: object
                required: [iceServers]
                properties:
                  iceServers:
                    type: array
                    items:
                      type: object
                      properties:
                        urls: { oneOf: [{ type: string }, { type: array, items: { type: string } }] }
                        username: { type: string }
                        credential: { type: string }
        '401':
          description: UNAUTHORIZED — no token, link or sign-in; a token or link that is not ours; or a session token that was already used or has expired. Mint a new session.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        '403':
          description: WEB_SESSION_CANCELLED — the session token was taken back with its cancel_url. Mint a new session.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /do-not-call:
    get:
      summary: List DNC entries (or look up by phone)
      description: |
        Returns every Do-Not-Call entry for your company, ordered by most-recently
        added. Pass `?phone=+972501234567` (any common format works — it's normalized)
        to look up a single entry instead of listing all.

        Entries whose `expires_at` has passed are returned too, in the list and by a
        lookup, until they are deleted. `active` says whether an entry blocks calls now.
      operationId: listDoNotCall
      tags: [Do Not Call]
      parameters:
        - in: query
          name: phone
          schema: { type: string }
          description: "Single-number lookup. Returns 404 if the number is not on the list. A number whose block has lapsed is still on the list - it comes back with `active: false`."
      responses:
        "200":
          description: List of DNC entries (or one entry when `phone` is supplied)
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: "#/components/schemas/DncEntry" }
                  - $ref: "#/components/schemas/DncEntry"
        "400":
          description: DO_NOT_CALL_REQUEST_INVALID — a query parameter other than `phone`, `phone` sent twice or empty, or a `phone` that is not a phone number.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: When `?phone=...` is supplied and the number isn't on the list
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    post:
      summary: Add a phone number to the DNC list
      description: |
        Adds a phone number to your company's Do-Not-Call list. The number is
        normalized to E.164 before storage, so any common input format works
        (`+972501234567`, `0501234567`, `972501234567`).

        **Scope** — by default, an entry is **global**: every outbound agent
        is blocked from calling this number. To block only specific agents
        (and let others through), pass `agent_ids` with an array of agent UUIDs.

        **Idempotent** — re-adding a number that's already on the list returns
        the existing entry, unchanged, with HTTP 200 instead of an error. That
        includes a lapsed entry (`active: false`): a re-add does not renew it
        and the number stays callable. To block it again, PATCH a new
        `expires_at` (or `null` for never), or delete the entry and add it
        again. To replace metadata on an existing entry, use
        `PATCH /do-not-call/{id}`.
      operationId: addDoNotCall
      tags: [Do Not Call]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [phone_number]
              properties:
                phone_number:
                  type: string
                  description: Phone number in any common format. Normalized to E.164 before storage.
                  example: "+972501234567"
                reason:
                  type: string
                  nullable: true
                  description: Optional free-form note ("Customer requested removal", "Regulator complaint", etc.).
                expires_at:
                  type: string
                  format: date-time
                  nullable: true
                  description: When the block lapses. Omit or set to `null` for a permanent block.
                agent_ids:
                  type: array
                  items: { type: string, format: uuid }
                  description: |
                    Optional. Omit or pass `[]` for a global block (every agent
                    in your company is blocked from calling this number). Pass
                    an array of agent UUIDs to scope the block to those agents
                    — agents NOT in the list can still place outbound calls
                    to this number. All UUIDs must reference active agents in
                    the same company; otherwise the request is rejected with
                    HTTP 400.
                  example: ["7e8a91c1-0000-4c11-9a00-000000000001"]
      responses:
        "200":
          description: Existing entry returned (idempotent re-add)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DncEntry" }
        "201":
          description: Number added to DNC list
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DncEntry" }
        "400":
          description: DO_NOT_CALL_REQUEST_INVALID for every refusal - phone_number missing or not a phone number, reason not a string, agent_ids naming an agent outside this company, expires_at malformed or in the past, a field other than phone_number, reason, expires_at and agent_ids, or a body that is not a JSON object.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /do-not-call/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get a DNC entry by id
      operationId: getDoNotCall
      tags: [Do Not Call]
      responses:
        "200":
          description: DNC entry
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DncEntry" }
        "400":
          description: DO_NOT_CALL_REQUEST_INVALID — a query parameter was sent; reading one entry takes none, and the message names it.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    patch:
      summary: Update a DNC entry
      description: |
        Update `reason`, `expires_at`, and/or `agent_ids`. The `phone_number`
        is immutable — delete the entry and add a new one if you need to
        change the number.

        **Switching scope:** pass `agent_ids: []` to convert a scoped entry to
        a global block, or pass a non-empty array to narrow a global block to
        specific agents.
      operationId: updateDoNotCall
      tags: [Do Not Call]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                reason: { type: string, nullable: true }
                expires_at: { type: string, format: date-time, nullable: true }
                agent_ids:
                  type: array
                  items: { type: string, format: uuid }
                  description: Empty array = global; non-empty = scoped to listed agents.
      responses:
        "200":
          description: Updated entry
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DncEntry" }
        "400":
          description: DO_NOT_CALL_REQUEST_INVALID for every refusal - an attempted phone_number edit, no editable field, unknown agent_ids, a body that is not a JSON object. Also when expires_at is malformed or in the past - a past expiry would lift the block at once, so it is refused; DELETE the entry instead. DO_NOT_CALL_REQUEST_INVALID when the body carries a field other than reason, expires_at and agent_ids - a misspelt expire_at is refused, and nothing beside it is saved.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      summary: Remove a phone number from the DNC list
      description: |
        Removes the entry. Outbound calls to this number will be allowed again
        immediately. The same number can be re-added later.
      operationId: deleteDoNotCall
      tags: [Do Not Call]
      responses:
        "200":
          description: Removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
  /call-windows:
    get:
      summary: Get call time windows
      description: |
        Returns the company's call time window configuration: which directions
        the window is enforced on, the workspace timezone, the optional
        after-hours message, and every allowed window grouped by day of week.

        Windows gate phone calls only. Browser sessions minted with
        `POST /calls {"type":"web"}` are never gated.
      operationId: getCallWindows
      tags: [Call Windows]
      responses:
        "200":
          description: Current configuration
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CallWindowConfig" }
        "400":
          description: "CALL_WINDOWS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    put:
      summary: Replace call time windows
      description: |
        Atomically replaces the call window configuration. Send any combination
        of `inbound_enabled`, `outbound_enabled`, `closed_message`, `timezone` and
        `windows`. Omitting `windows` leaves the existing schedule unchanged;
        including it (even as an empty array) overwrites the whole schedule.
        `timezone` sets the workspace's clock, which the hours, extraction dates,
        campaign suggestions and consumption days are all read on.

        Window rules:
        - `day_of_week` is 0–6 (0=Sunday … 6=Saturday).
        - `start_time` and `end_time` are `HH:MM` (24h, workspace timezone).
        - `start_time` must be earlier than `end_time` (no overnight wrap-around — use two rows on consecutive days instead).
        - Multiple windows per day are allowed but must not overlap.

        Requires the `call_windows:manage` scope. This one setting takes every agent in
        the workspace on or off the phone, so a key minted for one agent's management
        cannot change it. Reading the hours needs no scope. Keys issued before this
        scope existed do not hold it: Settings → API keys lists the scopes added since
        a key was created and adds them to that key in one press, so the key an
        integration already uses keeps working.
      operationId: updateCallWindows
      tags: [Call Windows]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                inbound_enabled: { type: boolean, description: "When true, inbound phone calls outside the window are ended before an agent answers." }
                outbound_enabled: { type: boolean, description: "When true, outbound phone calls outside the window are scheduled for the next opening." }
                closed_message:
                  type: string
                  nullable: true
                  maxLength: 500
                  description: What an inbound caller will hear when the window is closed, spoken before the call ends. Stored and returned today; not spoken yet, so out-of-hours calls are still ended in silence for now. Send `null` or a blank string to clear it. Omit the field to leave it unchanged.
                timezone:
                  type: string
                  description: >
                    The workspace's clock, as an IANA timezone name. The calling hours are read on
                    it, and so are relative dates agents collect, GET /campaigns/defaults and the days
                    of GET /billing/consumption. An offset (`+03:00`) or an abbreviation (`IDT`) is
                    refused with 400. A name in another case (`asia/jerusalem`) is stored as the zone
                    database spells it (`Asia/Jerusalem`). Omit it to leave the clock unchanged.
                  example: Asia/Jerusalem
                windows:
                  type: array
                  description: Full replacement set of windows. Empty array = no allowed windows on any day.
                  items: { $ref: "#/components/schemas/CallWindow" }
                expected_updated_at:
                  type: string
                  format: date-time
                  description: |
                    Optional. The `updated_at` you read from `GET /call-windows`.
                    When it no longer matches, the request is refused with
                    `409 CALL_WINDOWS_CONFLICT` and nothing is written, so you
                    never replace a change you have not seen. Omit it to write
                    unconditionally, which is what every client did before this
                    field existed.
                  example: "2026-09-22T11:30:00.000Z"
      responses:
        "200":
          description: Updated configuration
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CallWindowConfig" }
        "400":
          description: "Invalid call windows (overlap or start>=end) CALL_WINDOWS_REQUEST_INVALID: a body field this route does not read. It takes inbound_enabled, outbound_enabled, closed_message, timezone, windows and expected_updated_at; anything else is refused by name rather than dropped. A timezone that is not an IANA name is refused the same way."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: INSUFFICIENT_SCOPE - the key is valid for this workspace but does not hold call_windows:manage. Nothing was written. A key older than the scope can be given it in Settings -> API keys without being reissued.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: CALL_WINDOWS_CONFLICT - the expected_updated_at you sent is not the current version, so someone changed the hours after you read them. Nothing was written. Re-read GET /call-windows and decide against what is there.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  /dispositions:
    get:
      summary: List dispositions
      description: Returns all call dispositions for your company, ordered by position.
      operationId: listDispositions
      tags: [Dispositions]
      responses:
        "200":
          description: List of dispositions
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Disposition" }

        "400":
          description: "DISPOSITIONS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Create disposition
      operationId: createDisposition
      tags: [Dispositions]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [label]
              properties:
                label: { type: string, example: "Interested", description: "The text the post-call model matches on. It is the whole of the matching rule." }
                color: { type: string, example: "#22c55e", description: "Defaults to grey (`#6b7280`) when omitted, null or blank." }
                position: { type: integer, description: "Display order. Auto-increments if omitted." }
      responses:
        "201":
          description: Disposition created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Disposition" }
        "400":
          description: "DISPOSITION_REQUEST_INVALID: a body field this route does not read. It takes label, color and position; anything else is refused by name rather than dropped."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: A disposition with this label already exists
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /dispositions/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get disposition
      operationId: getDisposition
      tags: [Dispositions]
      responses:
        "200":
          description: Disposition
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Disposition" }
        "400":
          description: "DISPOSITIONS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    patch:
      summary: Update disposition
      operationId: updateDisposition
      tags: [Dispositions]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                label: { type: string }
                color: { type: string, description: "Sending null or a blank string restores the grey default rather than clearing the colour." }
                position: { type: integer }
      responses:
        "200":
          description: Updated disposition
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Disposition" }
        "400":
          description: "No updatable fields were provided, or label was empty DISPOSITION_REQUEST_INVALID: a body field this route does not read. It takes label, color and position; anything else is refused by name rather than dropped."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "409":
          description: A disposition with this label already exists
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      summary: Delete disposition
      description: >
        Permanently deletes a disposition. Protected (system) dispositions cannot be deleted.
        The outcome leaves every campaign's `stop_disposition_ids` (drafts, launched and archived);
        only a launched campaign it is the sole way to stop refuses the delete, with `409 DISPOSITION_IN_USE`.
      operationId: deleteDisposition
      tags: [Dispositions]
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
        "400":
          description: "DISPOSITIONS_QUERY_INVALID: a query parameter. A delete reads only its path, so any parameter is refused by name rather than ignored, and nothing is deleted."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: Disposition is protected and cannot be deleted
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "NOT_FOUND: no disposition with that id belongs to this workspace."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: >
            DISPOSITION_IN_USE: a launched campaign (scheduled, running, paused, stopped or completed)
            stops on this outcome and on nothing else. The message names it. Add another stop outcome with
            PATCH /campaigns/{id}, or archive a finished one, then repeat. Drafts never block a delete. Nothing was deleted.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /leads:
    get:
      summary: List leads
      operationId: listLeads
      tags: [Leads]
      description: >
        Any query parameter other than the five below is a `400 LEADS_QUERY_INVALID`,
        and so is one sent twice or with no value, and a `limit` or `offset` that is not
        a whole number (a `limit` above 100 is clamped to 100). A filter that is silently
        ignored cannot be told apart from one that matched everything.
      parameters:
        - in: query
          name: search
          schema: { type: string }
          description: >
            Case-insensitive search across name, phone_number, and email. Part of a
            number finds the contact however it is written: `0527140`, `052-714`,
            `+972 52 714` and `52 714 0311` all find `+972527140311`.
        - in: query
          name: tag
          schema: { type: string }
          description: >
            Only leads carrying this tag, by the tag's name as GET /lead-tags returns it.
            A name no tag in the workspace has is `404 LEAD_TAG_UNKNOWN`, never an empty page.
            Send `tag` or `tag_id`, not both.
        - in: query
          name: tag_id
          schema: { type: string, format: uuid }
          description: The same filter by tag id. Send `tag` or `tag_id`, not both.
        - in: query
          name: limit
          schema: { type: integer, default: 20, maximum: 100 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: List of leads
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Lead" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean }
        "404":
          description: >
            `LEAD_TAG_UNKNOWN` — the `tag` name or `tag_id` is not a lead tag in this workspace.
            A filter that would match nothing is refused rather than answered with an empty
            page.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

    post:
      summary: Create lead
      operationId: createLead
      tags: [Leads]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [phone_number]
              properties:
                phone_number:
                  type: string
                  example: "+972501234567"
                  description: >
                    E.164, or the local form (0501234567) which is normalised to E.164 before it
                    is stored. A number that could never be dialled — too short, non-numeric, an
                    impossible Israeli prefix or length — is `400 INVALID_PHONE_NUMBER` rather
                    than a lead that looks real and can never be called.
                name: { type: string, nullable: true }
                email: { type: string, format: email, nullable: true }
                source:
                  type: string
                  enum: [api, manual, csv_import]
                  default: api
                  description: >
                    Where the lead came from. Omitted means `api`. Any other value is
                    `400 INVALID_LEAD_SOURCE` — it used to be accepted and then stored as `api`.
                    Leads Yappr creates from a call are stored as `call`, which a request
                    cannot claim.
                long_term_context: { type: string, nullable: true, description: "Free text the agent reads before it speaks, when the agent has lead memory switched on." }
                tags:
                  type: array
                  items: { type: string }
                  description: >
                    Tag names to attach, exactly as GET /lead-tags returns them. Resolved to IDs
                    server-side; matching is exact. A name no tag in this workspace carries is
                    `400 INVALID_TAG_NAMES` — the names that did resolve used to be kept and the
                    rest dropped, which returned 201 with fewer tags than were asked for.
                    Use `tag_ids` to pass UUIDs directly.
                tag_ids:
                  type: array
                  items: { type: string, format: uuid }
                  description: "Tag IDs to attach. Use `tags` (names) or `tag_ids` (UUIDs), not both."
                metadata:
                  type: object
                  description: Stored as sent, except the reserved key extracted, which only a call writes and is dropped from a create.
      responses:
        "201":
          description: Lead created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Lead" }
        "400":
          description: >
            `INVALID_PHONE_NUMBER`, `INVALID_LEAD_SOURCE`, `INVALID_TAG_NAMES` or `INVALID_TAG_IDS` —
            nothing was created. `LEAD_REQUEST_INVALID` — the body carried a field a create does
            not read, a value for the reserved `metadata.extracted`, or an `email` that is not
            an email address; the message names it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: A lead with this phone number already exists
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /leads/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get lead
      operationId: getLead
      tags: [Leads]
      responses:
        "200":
          description: Lead
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Lead" }
        "400":
          description: "LEADS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    patch:
      summary: Update lead
      description: >
        Send only the fields you want to change. `tags` or `tag_ids` replaces all existing tags,
        and every name or id in it has to be a tag in this workspace. This is also how a lead is
        tagged after a call: your service reads the call's `extracted_data` and PATCHes the lead.
      operationId: updateLead
      tags: [Leads]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string, nullable: true }
                email: { type: string, format: email, nullable: true }
                long_term_context: { type: string, nullable: true, description: "AI memory for this lead. Injected into the agent's system prompt at call time." }
                metadata: { type: object }
                tags:
                  type: array
                  items: { type: string }
                  description: >
                    Replace all tags, by name. Names match exactly and all of them must be tags
                    in this workspace — one that is not is `400 INVALID_TAG_NAMES`, so a typo
                    cannot silently drop a tag. An empty array clears the lead's tags.
                tag_ids:
                  type: array
                  items: { type: string, format: uuid }
                  description: "Replace all tags by UUID"
      responses:
        "200":
          description: >
            The updated lead, for a key that also holds `leads:read`. A key with `leads:manage`
            alone reads back only what it wrote: `id`, each field it sent as the lead now holds it
            (`tag_ids` reads back as `tags`; `metadata` without the values the calls collected)
            and `updated_at`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Lead" }
        "400":
          description: "`INVALID_TAG_NAMES` or `INVALID_TAG_IDS` — the lead is unchanged. `LEAD_REQUEST_INVALID` — the body carried a field an edit does not read (`phone_number` and `source` are fixed at creation), changed the reserved `metadata.extracted` (sending it back exactly as read is fine), or sent an `email` that is not an email address, or set none of the fields an edit reads (`{}`: one `field_required` issue at path `\"\"`)."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      summary: Delete lead
      description: "Soft-deletes the lead (sets `deleted_at`). Removed from all list/get results but not permanently destroyed. Its calls answer `lead: null` from then on, and each one's `updated_at` moves."
      operationId: deleteLead
      tags: [Leads]
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }

  /lead-tags:
    get:
      summary: List lead tags
      description: Returns all lead tags for your company, ordered by sort_order.
      operationId: listLeadTags
      tags: [Lead Tags]
      responses:
        "200":
          description: List of tags
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/LeadTag" }

        "400":
          description: "LEAD_TAGS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Create lead tag
      operationId: createLeadTag
      tags: [Lead Tags]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string, example: "VIP"  }
                color: { type: string, nullable: true, example: "#f59e0b"  }
                description: { type: string, nullable: true }
      responses:
        "201":
          description: Tag created
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LeadTag" }
        "400":
          description: "`name` was missing, blank or not a string, or the body did not parse. LEAD_TAG_REQUEST_INVALID: a body field this route does not read. It takes name, description and color; anything else is refused by name rather than dropped."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: A tag with this name already exists
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /lead-tags/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get lead tag
      operationId: getLeadTag
      tags: [Lead Tags]
      responses:
        "200":
          description: Tag
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LeadTag" }
        "400":
          description: "LEAD_TAGS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    patch:
      summary: Update lead tag
      operationId: updateLeadTag
      tags: [Lead Tags]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                color: { type: string, nullable: true }
                description: { type: string, nullable: true }
                sort_order: { type: integer }
      responses:
        "200":
          description: Updated tag
          content:
            application/json:
              schema: { $ref: "#/components/schemas/LeadTag" }
        "400":
          description: "The body parsed but carried none of the updatable fields, or did not parse at all. LEAD_TAG_REQUEST_INVALID: a body field this route does not read. It takes name, description, color and sort_order; anything else is refused by name rather than dropped."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: No tag with that id in this workspace.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: The new name is already taken by another tag. Nothing was changed.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      summary: Delete lead tag
      description: >
        Permanently deletes a lead tag, and takes it off every lead that carries it.


        A tag one or more leads still carry is **refused** with `409 LEAD_TAG_IN_USE`,
        whose body carries `leads_tagged` — the number of leads that would lose it.
        Repeat the call with `?force=true` to delete it anyway. A tag no lead carries
        deletes on the first call. The count is taken before anything is deleted and has
        to succeed: a count that fails answers `503 LEAD_TAG_COUNT_UNAVAILABLE` with the
        tag untouched, never a delete taken as if no lead carried it. Deletion is not reversible and the leads are not
        otherwise changed: they simply stop carrying the tag, so any
        `GET /leads?tag=…` filter or campaign enrolment built on it stops matching.
      operationId: deleteLeadTag
      tags: [Lead Tags]
      parameters:
        - in: query
          name: force
          required: false
          schema: { type: boolean, default: false }
          description: >
            `true` deletes a tag that leads still carry. Omitted or `false`, such a tag
            is refused with `409 LEAD_TAG_IN_USE`. Any other value is `400
            LEAD_TAG_DELETE_INVALID`, as is any other query parameter.
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
        "400":
          description: The query string could not be read — `force` was not `true`/`false`, or an unknown parameter was sent.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: No tag with that id in this workspace.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: Leads still carry this tag. Retag them, or repeat with `?force=true`.
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Error" }
                  - type: object
                    properties:
                      error: { type: string }
                      code: { type: string, enum: [LEAD_TAG_IN_USE] }
                      leads_tagged:
                        type: integer
                        description: How many leads carry this tag right now and would lose it.
        "503":
          description: The count of leads carrying this tag could not be taken. Nothing was deleted; retry, or send `?force=true`.
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Error" }
                  - type: object
                    properties:
                      error: { type: string }
                      code: { type: string, enum: [LEAD_TAG_COUNT_UNAVAILABLE] }


  /shared-links:
    get:
      summary: List shared links
      description: >
        Returns every shared browser-call link for your company, including revoked and expired ones.
        Optionally filter by agent. A shared link is a sanctioned way to take a real call in a browser —
        the calls it places are billed, recorded and listed like any other — not a test-only fixture.
      operationId: listSharedLinks
      tags: [Shared Links]
      parameters:
        - in: query
          name: agent_id
          schema: { type: string, format: uuid }
          description: Filter by agent ID. Anything that is not an id is 400 SHARED_LINKS_QUERY_INVALID; an id that is not an agent in this workspace is 404 AGENT_NOT_FOUND, never an empty list. An archived agent's links are still listed.
      responses:
        "200":
          description: List of shared links
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/SharedLink" }
        "400":
          description: agent_id is not an id (SHARED_LINKS_QUERY_INVALID).
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: AGENT_NOT_FOUND - the agent_id filter names no agent in this workspace. It used to answer 200 with an empty list, which read as an agent with no links.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Create shared link
      description: >
        Generate a shareable URL that lets anyone speak to a voice agent in a browser without logging in.
        Calls placed through it are real: billed to your company, listed by GET /calls with
        direction `web_call`, and recorded and analysed like a phone call.
      operationId: createSharedLink
      tags: [Shared Links]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [agent_id]
              properties:
                agent_id: { type: string, format: uuid, description: "Agent to create a share link for" }
                expires_at: { type: string, format: date-time, nullable: true, description: "When the link expires. Omit or null for never. A value that cannot be read as a timestamp, or one already in the past, is 400 SHARED_LINK_EXPIRY_INVALID and nothing is created." }
      responses:
        "201":
          description: Created shared link
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SharedLink" }
        "400":
          description: "expires_at could not be read as a timestamp or is already in the past (SHARED_LINK_EXPIRY_INVALID), or agent_id is missing SHARED_LINK_REQUEST_INVALID: a body field this route does not read. It takes agent_id and expires_at; anything else is refused by name rather than dropped."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Agent not found
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /shared-links/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get shared link
      operationId: getSharedLink
      tags: [Shared Links]
      responses:
        "200":
          description: Shared link
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SharedLink" }
        "400":
          description: "SHARED_LINKS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    patch:
      summary: Revoke shared link
      description: Revoke a shared link so it can no longer be used. The only editable field is `is_revoked`.
      operationId: revokeSharedLink
      tags: [Shared Links]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [is_revoked]
              properties:
                is_revoked: { type: boolean }
      responses:
        "200":
          description: Updated shared link
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SharedLink" }

        "400":
          description: "SHARED_LINK_REQUEST_INVALID: a body field this route does not read. It takes is_revoked; anything else is refused by name rather than dropped."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
  # ── Flow agents ────────────────────────────────────────────────────────────

  /agents/{id}/flow/versions:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: List flow versions
      description: >
        Returns the immutable flow-version history for a flow agent, newest first. Each successful
        save (POST or PATCH that includes `flow_config`) writes one row, deduplicated by SHA-256
        content hash so re-saving an identical graph is a no-op.
      operationId: listAgentFlowVersions
      tags: [Flow Agents]
      parameters:
        - in: query
          name: limit
          schema: { type: integer, default: 20, maximum: 100 }
        - in: query
          name: cursor
          description: ISO 8601 timestamp from a prior `next_cursor` to page back further in time.
          schema: { type: string, format: date-time }
      responses:
        "200":
          description: Page of flow versions
          content:
            application/json:
              schema:
                type: object
                properties:
                  versions:
                    type: array
                    items: { $ref: "#/components/schemas/FlowVersion" }
                  next_cursor:
                    type: string
                    format: date-time
                    nullable: true
                    description: Pass back as `cursor` to fetch the next page. NULL when no more rows.
        "400":
          description: "AGENTS_QUERY_INVALID: a query parameter this route does not read, one sent twice or with no value, a limit that is not a whole number of at least 1 (above 100 it is clamped to 100), or a cursor that is not a timestamp. It reads limit and cursor; the message names what was refused."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Agent not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agents/{id}/flow/restore:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Restore a previous flow version
      operationId: restoreFlowVersion
      tags: [Agents]
      description: |
        Replaces the agent's current `flow_config` with the contents of a previously-saved
        version. The current state stays in version history (every save creates a snapshot,
        deduped by content hash) so you can always restore back to it later.

        Validation:
        - Agent must be a flow agent (`type='flow'`).
        - `version_id` must reference a row from `GET /agents/:id/flow/versions` for the
          same agent.

        Required scope: `agents:update`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [version_id]
              properties:
                version_id:
                  type: string
                  format: uuid
                  description: Id from `GET /agents/:id/flow/versions[].id`.
      responses:
        "200":
          description: Restored. Returns the updated agent (same shape as `PATCH /agents/:id`).
        "400":
          description: Invalid body, or agent is not a flow agent.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "404":
          description: Agent or version not found (or version doesn't belong to this agent).
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agents/{id}/flow/test:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Test a flow (hermetic simulator)
      description: >
        For agents of the retired flow kind only: a workflow agent is refused with `409`, and
        rehearsing one needs a browser or a Web SDK client. Walks a flow graph against a synthetic transcript without dispatching real tools or writing
        a `call_logs` row. Conversation-node transitions are picked by a deterministic keyword
        heuristic — for true eval-LLM-driven simulation use the in-app test panel. Tool-call nodes
        consume mocked results from the request body. Useful for CI smoke tests and skill
        verification before going live.
      operationId: testAgentFlow
      tags: [Flow Agents]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [transcript]
              properties:
                flow_config:
                  $ref: "#/components/schemas/FlowConfig"
                  description: Optional override. If omitted, uses the agent's saved flow_config.
                transcript:
                  type: array
                  items:
                    type: object
                    required: [role, text]
                    properties:
                      role: { type: string, enum: [user, agent] }
                      text: { type: string }
                mock_tool_results:
                  type: object
                  additionalProperties:
                    type: object
                    properties:
                      result:
                        description: Whatever the tool would have returned.
                        additionalProperties: true
                      error: { type: string, description: "Set to mark the tool as having failed; routes through the error transition." }
                  description: Keyed by tool-call node id.
      responses:
        "200":
          description: Trace of nodes visited and decisions made
          content:
            application/json:
              schema:
                type: object
                properties:
                  trace:
                    type: array
                    items: { $ref: "#/components/schemas/FlowTraceEntry" }
                  named_results:
                    type: object
                    additionalProperties: true
                  slot_values:
                    type: object
                    additionalProperties: true
                  ended_at_step_id: { type: string, nullable: true }
        "400":
          description: Invalid flow_config, transcript, or missing mock results
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "404":
          description: Agent not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "409":
          description: >
            `WORKFLOW_FLOW_TEST_UNSUPPORTED` — the agent runs a workflow. Rehearsing one needs a
            browser or a Web SDK client: there is no text-only rehearsal of a workflow over the API.
            Mint a browser session with `POST /calls` `{"type": "web"}` and connect with
            `@goyappr/client`, or use a shared link; when the call ends, `GET /calls/{id}` shows its
            analysis and follow-ups.
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Error" }
                  - type: object
                    properties:
                      error: { type: string }
                      code: { type: string, enum: [WORKFLOW_FLOW_TEST_UNSUPPORTED] }

  # ── Integrations (third-party OAuth-backed connectors) ─────────────────────
  #
  # The public API exposes list + revoke only. Connecting a credential
  # requires the dashboard's OAuth flow — popup/redirect orchestration is
  # not part of the API contract. Customers connect once via the dashboard
  # and then drive everything else (flows, calls) through this API.

  /tool-connections:
    get:
      operationId: listToolConnections
      summary: List workspace connected accounts
      description: Requires tool-connections:read. Returns at most 50 safe local records. Cursors bind the company and environment. Provider tokens, account IDs and authentication state are never returned. state and toolkit narrow the list; records taken off the list with POST /tool-connections/{id}/remove are excluded unless state=removed asks for exactly those. A filtered page is a page of MATCHES, so it can hold fewer than 50 rows and still carry a next_cursor - page until next_cursor is null rather than until a page looks short.
      tags: [Connected accounts]
      parameters:
        - name: cursor
          in: query
          schema: { type: string, maxLength: 512 }
        - name: state
          in: query
          description: One record state, or removed for the records taken off the list. Any other value is 400 CONNECTION_INVALID.
          schema: { type: string, enum: [disconnected, connecting, verifying, ready, reconnect_required, degraded, removed] }
        - name: toolkit
          in: query
          description: Exact app slug, as GET /tool-apps/connection-options returns it.
          schema: { type: string, pattern: '^[a-z0-9_]{1,100}$' }
      responses:
        '200':
          description: Connection metadata page.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/ToolConnection' } }
                  next_cursor: { type: [string, 'null'] }
        '400': { description: 'CONNECTION_INVALID - a parameter other than cursor, state and toolkit, one sent twice or with no value, a state outside disconnected, connecting, verifying, ready, reconnect_required, degraded, removed, or a toolkit that is not an app slug. CONNECTION_CURSOR_INVALID - a cursor this list did not issue for this workspace. The message says what to send and issues[0].path names the parameter.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'Missing, unknown or expired API key. A key without the scope this operation needs is 403 INSUFFICIENT_SCOPE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection management unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
    post:
      operationId: createToolConnection
      summary: Start a workspace connection
      description: Requires tool-connections:manage. Creates a pending local connection and an expiring human handoff. handoff_url is a link for a person, not a step an integration can complete - opening it without a Yappr session stops at Yappr's own authorization screen. An API key cannot provide OAuth consent. No vendor link is released before a signed-in member of this workspace claims the handoff in a bound browser. Apps whose sign-in Composio hosts are connected by a person at the handoff. Apps that take a credential the customer supplies (an API key, token or password) take credentials in this body and connect in this one request; the credentials are sent to the provider once and are never stored, logged or returned. Credentials are accepted only from a signed-in person in the dashboard. Sent with an API key, the answer is 409 CONNECTION_CREDENTIALS_NEED_PERSON.
      tags: [Connected accounts]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [toolkit, label]
              properties:
                toolkit: { type: string, pattern: '^[a-z0-9_]{1,100}$' }
                label: { type: string, minLength: 1, maxLength: 200 }
                locale: { type: string, enum: [en, he], default: en }
                credentials:
                  type: object
                  maxProperties: 12
                  additionalProperties: { type: string, minLength: 1, maxLength: 2048 }
                  description: 'Only for an app whose connect.kind is credentials: exactly the fields GET /tool-apps/connection-options?toolkit={slug} lists, each text of 1 to 2048 characters. A field the app does not take, a missing required one or an oversize value is 400 CONNECTION_INVALID. The app refusing them is 422 CONNECTION_CREDENTIALS_REJECTED.'
      responses:
        '201':
          description: Pending connection and one-time human handoff. For an app connected with credentials there is no handoff_url - the connection is returned as the sign-in finished.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ToolConnectionHandoff' }
        '400': { description: 'CONNECTION_INVALID: the body is missing toolkit or label, or carries a field this endpoint does not accept. Provider account IDs and tokens are never accepted here.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'Missing, unknown or expired API key. A key without the management scope is 403 INSUFFICIENT_SCOPE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'CONNECTION_APP_UNAVAILABLE when the toolkit is not an app Composio offers, or was switched off for this deployment. CONNECTION_APP_NEEDS_CREDENTIALS when the app needs a registered OAuth app that Yappr has not set up. CONNECTION_APP_NO_DATED_VERSION when the app has no dated version yet, so Yappr cannot use its actions (nothing is created). CONNECTION_CREDENTIALS_REQUIRED when the app takes credentials and none were sent. CONNECTION_CREDENTIALS_NEED_PERSON when credentials were sent with an API key. CONNECTION_CREDENTIALS_REJECTED (422) when the app refused them. An app an operator switched off stays CONNECTION_APP_UNAVAILABLE. Any app GET /tool-apps/connection-options lists connects without setup. Other 409 codes mean another authorization attempt is already active.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '429': { description: 'CONNECTION_RATE_LIMIT: ten authorizations started by this API key are already open. Attempts that expired, were cancelled or were completed do not count, and neither do other callers attempts. A workspace-wide ceiling of 120 starts in ten minutes counts every start whatever became of it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection control unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      operationId: getToolConnection
      summary: Get account readiness
      description: Requires tool-connections:read. Coalesces exact-account status checks for 15 seconds. ACTIVE credentials remain verifying until the approved identity and scope checks pass.
      tags: [Connected accounts]
      responses:
        '200':
          description: Safe connection metadata and current verification state.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ToolConnection' }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE - the key does not hold tool-connections:read, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: Connection is absent or belongs to another workspace., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
    patch:
      operationId: renameToolConnection
      summary: Rename an account
      description: Requires tool-connections:manage. Changes the label the account is shown and picked under - in GET /tool-connections, in a tool's connection and in a call's timeline - and nothing else. The account stays connected (or not) exactly as it was, its binding_revision and authorization_epoch do not move, and no tool, revision or accepted run changes. The label is trimmed, 1 to 200 characters, with no control characters. Sending the label the account already has changes nothing and answers the account. A record taken off the list (POST /tool-connections/{id}/remove) answers 404 CONNECTION_NOT_FOUND.
      tags: [Connected accounts]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [label]
              properties:
                label: { type: string, minLength: 1, maxLength: 200, description: 'The new name, such as "Front desk calendar". Leading and trailing spaces are dropped.' }
            example: { label: Front desk calendar }
      responses:
        '200':
          description: The account under its new label.
          content:
            application/json:
              schema:
                type: object
                properties:
                  connection: { $ref: '#/components/schemas/ToolConnection' }
        '400': { description: 'CONNECTION_INVALID - the body is not {"label": "..."}, or the label is blank, longer than 200 characters or holds a control character. issues[] names the field (/label, or the field to remove).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'Missing, unknown or expired API key. A key without the management scope is 403 INSUFFICIENT_SCOPE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'CONNECTION_NOT_FOUND - the connection is absent, belongs to another workspace, or was taken off the list.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
    delete:
      operationId: disconnectToolConnection
      summary: Disconnect an account
      description: Requires tool-connections:manage. Immediately blocks new dispatch and increments authorization_epoch once for an account that was bound (one that never bound an account stays at "0"). Already sent actions may finish. Provider grant revocation is separate; follow manual_revocation_required in account settings. Historical bindings remain available. Existing DELETE /integrations/{id} retains its separate 204 legacy contract.
      tags: [Connected accounts]
      responses:
        '202':
          description: Local denial committed; upstream removal or manual revocation may remain.
          content:
            application/json:
              schema:
                type: object
                properties:
                  connection: { $ref: '#/components/schemas/ToolConnection' }
        '401': { description: 'Missing, unknown or expired API key. A key without the management scope is 403 INSUFFICIENT_SCOPE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: Connection is absent or belongs to another workspace., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Local denial could not be persisted., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/{id}/remove:
    post:
      operationId: removeToolConnectionRecord
      summary: Take a disconnected account off the list
      description: Requires tool-connections:manage. Takes a record that is already disconnected off GET /tool-connections. Nothing is disconnected, revoked or deleted by this - the record and its history are kept, and state=removed still reads it back. A record that is not disconnected answers 409 CONNECTION_STILL_CONNECTED; disconnect it first. A record somebody is connecting again right now (an authorization started with POST /tool-connections/{id}/reconnect that has not finished, been cancelled or expired) answers 409 CONNECTION_ATTEMPT_OPEN. Repeating the call answers 200 with the same record, so a bulk pass that overlaps another one is safe. A removed record that is reconnected later comes back to the list when that authorization completes.
      tags: [Connected accounts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The record, no longer listed.
          content:
            application/json:
              schema:
                type: object
                properties:
                  connection: { $ref: '#/components/schemas/ToolConnection' }
        '400': { description: 'CONNECTION_INVALID: the id is not a connection id.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'Missing, unknown or expired API key. A key without the management scope is 403 INSUFFICIENT_SCOPE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: Connection is absent or belongs to another workspace., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'CONNECTION_STILL_CONNECTED: the connection has not been disconnected, so it cannot leave the list. Send DELETE /tool-connections/{id} first. CONNECTION_ATTEMPT_OPEN: an authorization for this connection is still in progress. Wait for it to finish or expire (ten minutes), or cancel it with POST /tool-connections/attempts/{id}/cancel, then try again.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection control unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/{id}/actions:
    get:
      operationId: listToolConnectionActions
      summary: What a connected app can do for agents
      description: >
        Requires tool-connections:read. Every action of the account's app at the version its actions are
        built at, the default set first in its own order, then the rest. default marks the actions an
        agent gets when the app is added without a list (a curated set for the most used apps, otherwise
        the provider's important actions without destructive or administrative ones, at most 12). ready
        says the action's tool is built for this account's current sign-in. name_he is a Hebrew name
        and description_he a one-line Hebrew description where one is curated. inputs says how each input
        is set (configuration first, each with its default source), and bindable whether the account's
        tool for the action takes an agent's own calendar yet (false on a tool built before that; the
        first write that fixes a calendar rebuilds it). Takes no query parameters.
      tags: [Connected accounts]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: The account and its actions.
          content:
            application/json:
              schema:
                type: object
                properties:
                  connection:
                    type: object
                    properties:
                      id: { type: string, format: uuid }
                      app: { type: string, example: googlecalendar }
                      app_name: { type: string, example: Google Calendar }
                      app_name_he: { type: [string, 'null'] }
                      label: { type: string, example: Clinic calendar }
                      state: { type: string, example: ready }
                  version: { type: string, example: '20260902_00' }
                  truncated: { type: boolean, description: 'Not every action of the app is listed: its action list is still being read (a large app, the first time it is asked for), or the list stops there for good (over a thousand actions, or a part the catalogue cannot serve). Ask again in a few seconds for the rest. Whether the default set is settled is defaults_final, not this.' }
                  defaults_final: { type: boolean, description: 'The actions marked default are the ones an agent gets with actions "default", now. Always true for a curated app (Google Calendar, Gmail, HubSpot...) and for any app whose list was read before; false only while another app''s list is read the first time, when giving it to an agent with actions "default" answers 503 with Retry-After (named actions still go). A list that stops for good (truncated stays true) has final defaults.' }
                  resource: { type: [string, 'null'], description: 'What the agent''s instructions should name for this app (sheet, board, channel), when it needs one.' }
                  prepared: { type: boolean, description: Every default action is ready. }
                  data:
                    type: array
                    items:
                      allOf:
                        - { $ref: '#/components/schemas/ConnectionAction' }
                        - type: object
                          properties:
                            ready: { type: boolean }
                            bindable: { type: boolean }
        '400': { description: 'TOOL_CONNECTIONS_QUERY_INVALID: a query parameter was sent.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE, or WORKFLOW_ENVIRONMENT_MISMATCH (the account is connected on another plane).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'TOOL_CONNECTION_NOT_FOUND.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: 'WORKFLOW_TOOL_CONTROL_UNAVAILABLE. With Retry-After when the app''s default actions are still being read the first time: send the same request again.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/{id}/actions/prepare:
    post:
      operationId: prepareToolConnectionActions
      summary: Make a connected app's actions ready now
      description: >
        Requires tool-connections:manage. Builds the tools that run the account's default actions (or
        the actions named) so that adding the app to an agent is immediate. Actions already ready are
        left alone, so it is safe to repeat; the dashboard calls it when an app finishes connecting. Waits
        up to about six seconds: an action still being built answers building and finishes on its own.
        An action a voice agent cannot use answers unavailable with a reason (not_eligible, needs_setup,
        or the build's error). A ready action names the revision its tool runs (head_revision_id) and
        whether that revision takes an agent's own calendar (bindable); an action whose tool still fixes
        the calendar itself is rebuilt by this call, so ask again until bindable is true. Send no body,
        {}, or {"actions": [...]}.
      tags: [Connected accounts]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                actions:
                  oneOf:
                    - { type: string, const: default }
                    - { type: array, minItems: 1, maxItems: 24, uniqueItems: true, items: { type: string, pattern: '^[A-Z0-9_]{1,200}$' } }
      responses:
        '200':
          description: Each action's state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  prepared: { type: boolean, description: Every action asked for is ready. }
                  version: { type: string }
                  data:
                    type: array
                    items:
                      type: object
                      required: [action, status]
                      properties:
                        action: { type: string }
                        status: { type: string, enum: [ready, building, unavailable] }
                        reason: { type: string }
                        head_revision_id: { type: string, format: uuid, description: 'Ready actions: the revision a binding to this action runs.' }
                        bindable: { type: boolean, description: 'Ready actions: the revision takes an agent''s own calendar.' }
        '400': { description: 'TOOL_CONNECTION_REQUEST_INVALID: not JSON, or a field other than actions.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE, WORKFLOW_ACTOR_DENIED (the key needs tools:create to build actions), or WORKFLOW_ENVIRONMENT_MISMATCH.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'TOOL_CONNECTION_NOT_FOUND.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'TOOL_CONNECTION_NOT_READY, or INTEGRATION_ACTION_UNKNOWN (each unknown action named in issues).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: 'WORKFLOW_TOOL_CONTROL_UNAVAILABLE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/{id}/options/{resource}:
    get:
      operationId: listToolConnectionOptions
      summary: List the choices an account offers for an action input
      description: >
        Requires tool-connections:read. The values an action input can be fixed to on this connected
        account, so an author picks one instead of typing its id. Today the one resource is calendars:
        the calendars of a Google Calendar account the account can write to, the main one first with the
        value primary (what every Google Calendar action already uses for it). Read live through the
        account's own "List calendars" action, a read with no effect (it is made ready on the first call;
        an API key doing that also needs tools:create and tools:update). Waits up to about ten seconds;
        when the account is still answering then, the answer is 202 with status "loading" and
        Retry-After, and the same listing goes on: ask again after Retry-After and it answers. One caller's
        listings of one account within two minutes share one read, and a listed account is reused for a
        few minutes. 409 RESOURCE_OPTIONS_RECONNECT_REQUIRED means Google refused the account's read:
        reconnect it. Use a value as a Fixed source ({"kind": "literal", "value": ["<value>"]} for items)
        or as a choice of a list. Takes no query parameters.
      tags: [Connected accounts]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: resource, in: path, required: true, schema: { type: string, enum: [calendars] } }
      responses:
        '200':
          description: The account's choices.
          content:
            application/json:
              schema:
                type: object
                required: [resource, data]
                properties:
                  resource: { type: string, enum: [calendars] }
                  data:
                    type: array
                    items:
                      type: object
                      required: [value, label]
                      properties:
                        value: { type: string, description: 'The value to fix the input to; the main calendar is "primary".' }
                        label: { type: string, description: 'The calendar''s name as the account shows it.' }
                        primary: { type: boolean }
                        detail: { type: [string, 'null'], description: 'The account''s access to it: owner or writer.' }
              example: { resource: calendars, data: [{ value: primary, label: Front desk, primary: true, detail: owner }, { value: c_1a2b3c@group.calendar.google.com, label: Clinic, primary: false, detail: writer }] }
        '202':
          description: The account is still answering. The listing goes on; ask again after Retry-After (seconds) and the same listing answers.
          headers:
            Retry-After: { schema: { type: integer }, description: Seconds to wait before asking again. }
          content:
            application/json:
              schema:
                type: object
                required: [resource, data, status, retry_after, message]
                properties:
                  resource: { type: string, enum: [calendars] }
                  data: { type: array, maxItems: 0, items: { type: object } }
                  status: { type: string, enum: [loading] }
                  retry_after: { type: integer, description: Seconds to wait before asking again. }
                  message: { type: string }
              example: { resource: calendars, data: [], status: loading, retry_after: 4, message: 'The calendars are still loading from the account. Ask again in a few seconds; the same listing answers.' }
        '400': { description: 'TOOL_CONNECTIONS_QUERY_INVALID: a query parameter was sent; this read takes none, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE, WORKFLOW_ACTOR_DENIED (the key needs tools:create to make the listing action ready and tools:update to run it), or WORKFLOW_ENVIRONMENT_MISMATCH.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'TOOL_CONNECTION_NOT_FOUND.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'TOOL_CONNECTION_NOT_READY (the account is not signed in), or RESOURCE_OPTIONS_RECONNECT_REQUIRED (Google refused the account''s read: its sign-in expired or lost access). Either way, reconnect the account (POST /tool-connections/{id}/reconnect); meanwhile type the calendar ID.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'RESOURCE_UNSUPPORTED: not a resource this account lists (calendars needs a Google Calendar account).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '429': { description: 'RESOURCE_OPTIONS_BUSY: too many tests are running in this workspace (Retry-After).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: 'RESOURCE_OPTIONS_PROVIDER_UNAVAILABLE (Google Calendar did not answer usefully three times; Retry-After 30), or RESOURCE_OPTIONS_UNAVAILABLE (the listing failed on our side; Retry-After). Type the calendar ID instead, or try again.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/{id}/check:
    post:
      operationId: checkToolConnection
      summary: Check that a connected account actually works
      description: >
        Requires tool-connections:manage. "Connected" (state ready) proves only that the sign-in worked; this
        runs one harmless read through the account and answers what the app said - for example a WhatsApp
        account whose Facebook sign-in has no WhatsApp Business number answers app_reports_problem,
        "Connected, but WhatsApp says no phone numbers are set up.", with Meta's own words in reason. The read
        is never an action that changes, sends or deletes anything: the app's own lookup where Yappr knows one
        (its phone numbers, its calendars, the signed-in profile), else a plain read of who is signed in, else
        none (not_checked, no_probe). It runs as the account's own read action, made ready on the first check
        (an API key doing that also needs tools:create, and tools:update to run it), with no inputs. Waits up
        to about 25 seconds; still running then, the answer is 202 with Retry-After, and sending the same
        request again within two minutes reads the same check. The check is kept on the account for the
        workspace (check on GET /tool-connections/{id}) where the platform keeps checks. Takes no body
        (send none, or {}) and no query parameters.
      tags: [Connected accounts]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: What the read found. ready stays the sign-in fact.
          content:
            application/json:
              schema:
                type: object
                required: [connection_id, ready, check]
                properties:
                  connection_id: { type: string, format: uuid }
                  ready: { type: boolean, enum: [true], description: The account's sign-in is finished (state ready). }
                  check: { $ref: '#/components/schemas/ConnectionCheck' }
              example: { connection_id: 3f9a6c2e-8b1d-4c7a-9e5f-2a6b1c0d4e8f, ready: true, check: { status: app_reports_problem, code: nothing_set_up, reading: 'Connected, but WhatsApp says no phone numbers are set up.', reason: '(#100) Tried accessing nonexisting field (phone_numbers)', action: WHATSAPP_GET_PHONE_NUMBERS, checked_at: '2026-11-02T11:20:41.000Z' } }
        '202':
          description: The read is still running. Send the same request again after Retry-After (seconds); it reads the same check.
          headers:
            Retry-After: { schema: { type: integer }, description: Seconds to wait before asking again. }
          content:
            application/json:
              schema:
                type: object
                required: [connection_id, ready, check, status, retry_after, message]
                properties:
                  connection_id: { type: string, format: uuid }
                  ready: { type: boolean, enum: [true] }
                  check: { type: 'null' }
                  status: { type: string, enum: [checking] }
                  retry_after: { type: integer }
                  message: { type: string }
              example: { connection_id: 3f9a6c2e-8b1d-4c7a-9e5f-2a6b1c0d4e8f, ready: true, check: null, status: checking, retry_after: 4, message: 'The account is still being checked. Send the same request again in a few seconds; it reads the same check.' }
        '400': { description: 'TOOL_CONNECTIONS_QUERY_INVALID (a query parameter was sent) or TOOL_CONNECTION_REQUEST_INVALID (a body with fields: a check takes none).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE, WORKFLOW_ACTOR_DENIED (the key needs tools:create to make the read ready and tools:update to run it), or WORKFLOW_ENVIRONMENT_MISMATCH.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'TOOL_CONNECTION_NOT_FOUND.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409': { description: 'TOOL_CONNECTION_NOT_READY: the account is not signed in, so there is nothing to check yet. Reconnect it (POST /tool-connections/{id}/reconnect), then check again.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '429': { description: 'CONNECTION_CHECK_BUSY: too many tests are running in this workspace (Retry-After).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: 'CONNECTION_CHECK_UNAVAILABLE: the check could not be started on our side; nothing was changed (Retry-After).', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/{id}/agents:
    get:
      operationId: listToolConnectionAgents
      summary: The agents using a connected app
      description: >
        Requires tool-connections:read. Every agent whose draft or published workflow uses the account:
        via integration (the whole app, from the agent's Integrations) or via tools (tools of its own, one
        per action; tools_count says how many). live says the published version uses it. At most 200.
      tags: [Connected accounts]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: The agents.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/ConnectionAgent' } }
        '404': { description: 'TOOL_CONNECTION_NOT_FOUND.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/cleanup:
    post:
      operationId: cleanUpToolConnections
      summary: Clear the connection attempts nobody finished
      description: >
        Requires tool-connections:manage. Every connection in this workspace that never finished
        connecting - it never had an account (connected is false) and is connecting or
        disconnected - and has no authorization open right now leaves GET /tool-connections, in one
        request. Each one is closed the way DELETE closes a connection that never had an account,
        and taken off the list the way POST /tool-connections/{id}/remove takes one off; nothing is
        deleted, and state=removed still reads them back. A connection that was ever connected is
        never touched, whatever its state. The same clean-up runs by itself every hour for attempts
        more than a day old. Takes no input: send no body or an empty object {}, and no query
        parameters; it always covers the whole workspace. Repeating it answers removed 0.
      tags: [Connected accounts]
      responses:
        '200':
          description: How many connections left the list.
          content:
            application/json:
              schema:
                type: object
                properties:
                  removed: { type: integer, minimum: 0, example: 168 }
        '400': { description: 'CONNECTION_INVALID: the body held anything but nothing or an empty object {} (ids, an age, any field, or text that is not JSON), or a query parameter was sent. Nothing was cleared.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'Missing, unknown or expired API key. A key without the management scope is 403 INSUFFICIENT_SCOPE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection control unavailable. Nothing was changed; send it again., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/{id}/reconnect:
    post:
      operationId: reconnectToolConnection
      summary: Authorize a replacement account
      description: 'Requires tool-connections:manage. Explicit replacement mode creates a new human consent attempt. It never changes an already pinned run to a different provider account. Same-account reauthorization is not yet exposed by this route. A connection holds one open sign-in at a time: one nobody has opened yet (status pending_human, its link handed out but unused) is cancelled and replaced by this request; one a person is in the middle of answers 409 CONNECTION_ATTEMPT_OPEN, naming it under attempt. GET /tool-connections/{id} shows the open one as open_attempt. For an app that is connected with a key rather than a sign-in (GET /tool-apps/connection-options shows connect.kind credentials), this is how its key is replaced in place: the handoff_url opens a Yappr page that asks a signed-in person for the new key (a key never travels over the API), and typing it re-points this same connection at a new provider account. The connection keeps its id, label and bindings; binding_revision and authorization_epoch each go up by one, so tools built on the old account stop working until they are rebuilt. Yappr starts rebuilding them the moment the key is replaced, all of the account''s tools together, so an agent that uses several of them switches in one step (usually under a minute, longer when many tools, or many agents sharing them, are involved; a rebuild that fails is tried again by a check every five minutes, waiting longer after each failure; calls in that window can fail, and a call already in progress keeps failing its app tools until it ends). An agent that pins a tool to one exact revision does not follow the account and stays refused until it is pointed at the current revision. The new key takes effect at once for every agent that uses the connection and Yappr cannot put the old one back; entering the old key again is the only undo. The old provider account is not deleted: revoke the old key in the app. For the apps Yappr has checked against a live call (Mapbox today) a key the app itself refuses is rejected on that page and nothing changes; for other apps a wrong key cannot be told apart from a good one until it is used. Sending credentials in this request is 400 CONNECTION_INVALID.'
      tags: [Connected accounts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [mode]
              properties:
                mode: { type: string, const: replace }
                locale: { type: string, enum: [en, he], default: en }
      responses:
        '201':
          description: A one-time replacement handoff; current identity stays fixed until verification commits. For an app connected with a key, the link opens the page that asks for the new key.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ToolConnectionHandoff' }
        '400': { description: Explicit replacement mode required., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'Missing, unknown or expired API key. A key without the management scope is 403 INSUFFICIENT_SCOPE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: Connection is absent or belongs to another workspace., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '409':
          description: 'CONNECTION_ATTEMPT_OPEN - a person is signing in to this connection right now (attempt.status claimed, creating_link, awaiting_consent, verifying or reconciliation_required). The message names the attempt; let it finish, or cancel it with POST /tool-connections/attempts/{attempt.id}/cancel and send the reconnect again. Never retried as an outage. CONNECTION_APP_UNAVAILABLE - the app is no longer open for connection.'
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/Error" }
                  - type: object
                    required: [error, code]
                    properties:
                      error: { type: string }
                      code: { type: string, enum: [CONNECTION_ATTEMPT_OPEN, CONNECTION_APP_UNAVAILABLE] }
                      attempt:
                        type: object
                        description: Present with CONNECTION_ATTEMPT_OPEN.
                        properties:
                          id: { type: string, format: uuid }
                          status: { type: string }
                          expires_at: { type: string, format: date-time }
        '429': { description: Authorization creation rate exceeded., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection control unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/attempts/{id}:
    get:
      operationId: getToolConnectionAuthAttemptByConnectionPath
      summary: Read an authorization attempt where it is cancelled
      description: Requires tool-connections:read. The same read as GET /tool-connection-auth-attempts/{id}, under the path the attempt is cancelled at (POST /tool-connections/attempts/{id}/cancel); both answer the same. A segment that is not an id is 404 RESOURCE_ID_INVALID. Takes no query parameters.
      tags: [Connected accounts]
      parameters:
        - name: id
          in: path
          required: true
          description: The attempt id from POST /tool-connections or POST /tool-connections/{id}/reconnect, not the connection id.
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Exact attempt and safe connection state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  attempt: { $ref: '#/components/schemas/ToolConnectionAuthAttempt' }
                  connection: { $ref: '#/components/schemas/ToolConnection' }
        '400': { description: 'CONNECTION_INVALID - a query parameter was sent; reading an attempt takes none.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE - the key does not hold tool-connections:read, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: 'Attempt is absent or belongs to another workspace; RESOURCE_ID_INVALID when the segment is not an id.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connections/attempts/{id}/cancel:
    post:
      operationId: cancelToolConnectionAuthAttempt
      summary: Cancel an authorization attempt
      description: Requires tool-connections:manage. Closes an authorization nobody finished, which frees the slot this API key holds against the ten-open limit. The connection record itself stays and nothing is revoked at the provider - an attempt cancelled before consent never produced a grant. Already cancelled, completed, failed and expired attempts answer 200 unchanged, so a retry is safe.
      tags: [Connected accounts]
      parameters:
        - name: id
          in: path
          required: true
          description: The attempt id from POST /tool-connections or POST /tool-connections/{id}/reconnect, not the connection id.
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The attempt, in its settled state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  attempt: { $ref: '#/components/schemas/ToolConnectionAuthAttempt' }
        '401': { description: 'Missing, unknown or expired API key. A key without the management scope is 403 INSUFFICIENT_SCOPE.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: Attempt is absent or belongs to another workspace., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-connection-auth-attempts/{id}:
    get:
      operationId: getToolConnectionAuthAttempt
      summary: Read an exact authorization attempt
      description: Requires tool-connections:read. Poll only this returned local ID, using increasing intervals and stopping at expires_at or a terminal status. Browser redirects are hints, not completion evidence. completed means consent was processed; inspect connection.state separately for ready. Unknown redemption requires reconciliation and must never be redeemed again blindly.
      tags: [Connected accounts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Exact attempt and safe connection state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  attempt: { $ref: '#/components/schemas/ToolConnectionAuthAttempt' }
                  connection: { $ref: '#/components/schemas/ToolConnection' }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE - the key does not hold tool-connections:read, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '404': { description: Attempt is absent or belongs to another workspace., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Connection storage unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-apps:
    get:
      operationId: listToolApps
      summary: Discover apps
      description: Requires tools:read. Curated read-only discovery metadata, not account-connection readiness. A toolkit the publisher has not dated is listed with version null instead of failing the page; read toolkit detail before selecting a dated action. Discovery never authenticates accounts or executes actions.
      tags: [Tools]
      parameters:
        - in: query
          name: cursor
          schema: { type: string }
          description: Opaque workspace/environment-scoped continuation, bound to the search it came from.
        - in: query
          name: search
          schema: { type: string, minLength: 1, maxLength: 100 }
          description: >-
            Part of an app's name, slug or description, for example "calendly". The catalogue filters itself
            and answers up to 20 matches per page, in one read instead of paging the whole list.
      responses:
        '200':
          description: A page of discoverable apps.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/ToolApp' } }
                  next_cursor: { type: [string, 'null'] }
                  search: { type: string, description: 'The trimmed search this page was filtered by. Absent when the page is not filtered.' }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE - the key does not hold tools:read, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'WORKFLOW_CATALOG_REQUEST_INVALID (a parameter this catalog does not read, or one sent twice), WORKFLOW_CATALOG_CURSOR_INVALID (a cursor issued for another app, version, search or workspace, or an empty one), WORKFLOW_CATALOG_SEARCH_INVALID or WORKFLOW_DATED_VERSION_REQUIRED_INVALID. Each names the parameter in issues[0].path. WORKFLOW_DATED_VERSION_REQUIRED means the app has no dated version yet, so Yappr cannot use its actions.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Catalog unavailable; no replacement metadata is guessed., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-apps/{slug}:
    get:
      operationId: getToolApp
      summary: Get app versions
      description: Requires tools:read. Returns the authoritative available dated versions for an app; never use latest as a frozen action version.
      tags: [Tools]
      parameters:
        - in: path
          name: slug
          required: true
          schema: { type: string, pattern: '^[a-z0-9_]{1,100}$' }
      responses:
        '200':
          description: App metadata including available_versions.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ToolApp' }
        '404': { description: Invalid app path., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '422': { description: 'The app carries no usable dated version, so no action of it can be pinned. It is listed by GET /tool-apps with version null and cannot be used yet.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Authoritative app metadata is unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-apps/{slug}/actions:
    get:
      operationId: listToolAppActions
      summary: Discover versioned actions
      description: Requires tools:read. Each item carries the resolved dated version; omitting version resolves the app's current metadata version. Use that exact version for action detail and materialization.
      tags: [Tools]
      parameters:
        - in: path
          name: slug
          required: true
          schema: { type: string }
        - in: query
          name: version
          schema: { type: string, pattern: '^\d{8}_\d{2}$' }
        - in: query
          name: cursor
          schema: { type: string }
          description: Opaque continuation bound to workspace, environment, path, requested version and search.
        - in: query
          name: search
          schema: { type: string, minLength: 1, maxLength: 100 }
          description: >-
            Part of an action's name, slug or description, for example "free slots". The catalogue filters
            itself and answers up to 50 matches per page, best match first - the name, then the slug, then the
            description; "availability" also finds free/busy actions, and "availability" and "available" each find
            the other's. The catalogue's own other matches, which
            can match on meaning, follow in its order. Action names are English.
      responses:
        '200':
          description: Dated action metadata page.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/ToolAction' } }
                  next_cursor: { type: [string, 'null'] }
                  search: { type: string, description: 'The trimmed search this page was filtered by. Absent when the page is not filtered.' }
        '422': { description: 'Invalid version or cursor, or WORKFLOW_CATALOG_SEARCH_INVALID - a search that is empty, over 100 characters or spans lines.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Metadata unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-apps/{slug}/actions/{action}:
    get:
      operationId: getToolAppAction
      summary: Get full dated action schemas
      description: Requires tools:read. Returns full authoritative input/output schemas and a local metadata ID. Preserves nested required/default/combinator semantics and exact numbers. Eligibility reflects reviewed supported completion/effect/file semantics; successful responses are not assumed to mean remote work completed. No provider credentials, auth responses or raw execution contracts are exposed.
      tags: [Tools]
      parameters:
        - in: path
          name: slug
          required: true
          schema: { type: string }
        - in: path
          name: action
          required: true
          schema: { type: string, pattern: '^[A-Z0-9_]{1,200}$' }
        - in: query
          name: version
          required: true
          schema: { type: string, pattern: '^\d{8}_\d{2}$' }
      responses:
        '200':
          description: Complete bounded dated schemas, scope alternatives and reviewed fixed-field policy.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ToolActionDetail' }
        '422': { description: 'Missing/invalid dated version, malformed or unsupported metadata.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Catalog unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  /tool-apps/connection-options:
    get:
      operationId: listConnectableApps
      summary: List apps that can be connected
      description: Requires tools:read. Every app Composio hosts the sign-in for (connect.kind oauth) and every app that takes a credential the customer supplies (connect.kind credentials), with no setup by Yappr. Apps that need an OAuth app registered by Yappr are not listed, and neither are apps with no dated version yet (Yappr cannot use their actions) or with no actions at all. An app Yappr already has set up but the catalogue no longer carries (for example one with no dated version yet) is still listed without connect.kind, because the list does not say how it connects, so ask for it with ?toolkit={slug}. With ?toolkit={slug} it returns that one app, and for a credentials app the fields it takes, as Composio names them (label and help text are Composio's); an app with no dated version is still described there, and only POST /tool-connections refuses it. This readiness selection is distinct from GET /tool-apps discovery and cannot authenticate or execute an app.
      tags: [Connected accounts]
      parameters:
        - name: toolkit
          in: query
          required: false
          description: One app slug, as this list gives it. Returns that app with connect.fields.
          schema: { type: string, pattern: '^[a-z0-9_]{1,100}$' }
      responses:
        '200':
          description: Apps with an enabled server-managed authentication configuration. An empty data array means nothing in this workspace can be connected yet, and every POST /tool-connections will answer 409.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        slug: { type: string }
                        name: { type: string }
                        categories: { type: array, items: { type: string }, description: The app's categories, when the catalogue gives any. }
                        logo_url: { type: string, format: uri, description: The app's logo, when the catalogue gives one. }
                        connect:
                          type: object
                          properties:
                            kind: { type: string, enum: [oauth, credentials], description: 'oauth - a person signs in on a hosted page. credentials - the customer supplies the fields below. Absent for an app that is listed but whose way of connecting is not known from the list; ?toolkit={slug} says.' }
                            fields:
                              type: array
                              description: Only with ?toolkit=. Entered as password-type inputs.
                              items:
                                type: object
                                properties:
                                  name: { type: string }
                                  label: { type: string }
                                  help: { type: string }
                                  required: { type: boolean }
        '401': { description: 'MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '403': { description: 'INSUFFICIENT_SCOPE - the key does not hold tools:read, and the message names it.', content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        '503': { description: Catalog unavailable., content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
  # ── Agent Eval ─────────────────────────────────────────────────────────────

  /agent-eval/personas:
    get:
      summary: List personas
      description: Requires agent_eval:read. Returns the workspace's non-deleted personas, newest first.
      operationId: listPersonas
      tags: [Agent Eval]
      parameters:
        - in: query
          name: limit
          schema: { type: integer, default: 20, maximum: 100 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: List of personas
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/EvalPersona" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read, one sent twice or with no value, or a limit / offset that is not a whole number. It reads limit and offset; the message names what was refused."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
    post:
      summary: Create persona
      description: |
        Required scope: `agent_eval:create`.

        Tips for designing a useful persona:
        - Lead the `identity_prompt` with the persona's role and what brought them to the call.
        - Put behaviour knobs (patience, cooperation, verbosity) in `behavior_traits`, not in the prompt — that way you can reuse one identity across friendly + adversarial variants.
        - Keep the prompt under ~120 words. Long prompts make the persona LLM rigid.
      operationId: createPersona
      tags: [Agent Eval]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, identity_prompt]
              properties:
                name: { type: string, example: "Frustrated tenant"  }
                description: { type: string }
                identity_prompt: { type: string }
                behavior_traits:
                  type: object
                  additionalProperties: true
                language: { type: string, enum: [he, en, ar, ru, fr, es, de, it, pt, nl, tr, pl, uk, hi, ja, ko, zh], default: en, description: "The language the test caller speaks: any call language except multi. One persona is one caller; for a multilingual agent, make one persona per language." }
                voice_config:
                  type: object
                  additionalProperties: true
      responses:
        "201":
          description: Persona created
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalPersona" } } }
        "400":
          description: "Validation error (missing required field, invalid language) AGENT_EVAL_REQUEST_INVALID: a body field this route does not read. It takes name, description, identity_prompt, behavior_traits, language and voice_config; anything else is refused by name rather than dropped."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: Insufficient scope
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /agent-eval/personas/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get persona
      operationId: getPersona
      tags: [Agent Eval]
      responses:
        "200":
          description: Persona
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalPersona" } } }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
    patch:
      summary: Update persona
      description: Send only fields you want to change. Required scope `agent_eval:update`.
      operationId: updatePersona
      tags: [Agent Eval]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: { type: string, nullable: true }
                identity_prompt: { type: string }
                behavior_traits: { type: object, additionalProperties: true }
                language: { type: string, enum: [he, en, ar, ru, fr, es, de, it, pt, nl, tr, pl, uk, hi, ja, ko, zh], description: "The language the test caller speaks: any call language except multi. One persona is one caller; for a multilingual agent, make one persona per language." }
                voice_config: { type: object, additionalProperties: true }
      responses:
        "200":
          description: Updated persona
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalPersona" } } }
        "400":
          description: "Validation error (e.g. no updatable fields provided, invalid language) AGENT_EVAL_REQUEST_INVALID: a body field this route does not read. It takes name, description, identity_prompt, behavior_traits, language and voice_config; anything else is refused by name rather than dropped."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    delete:
      summary: Delete persona
      description: Soft-delete (sets `deleted_at`). Required scope `agent_eval:delete`. Existing cases referencing the persona keep working until the next case PATCH.
      operationId: deletePersona
      tags: [Agent Eval]
      responses:
        "200":
          description: Persona deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  id: { type: string, format: uuid }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter. A delete reads only its path, so any parameter is refused by name rather than ignored, and nothing is deleted."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agent-eval/cases:
    get:
      summary: List cases
      description: Returns non-deleted cases. Optional filter by `agent_id` and `suite_id`.
      operationId: listCases
      tags: [Agent Eval]
      parameters:
        - in: query
          name: agent_id
          schema: { type: string, format: uuid }
        - in: query
          name: suite_id
          schema: { type: string, format: uuid }
        - in: query
          name: limit
          schema: { type: integer, default: 20, maximum: 100 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: List of cases. `agent` and `persona` are expanded inline.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/EvalCase" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read, one sent twice or with no value, or a limit / offset that is not a whole number. It reads limit, offset, suite_id and agent_id; the message names what was refused."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Create case
      description: |
        Required scope `agent_eval:create`. The `agent_id` must reference a non-deleted agent in this company; `persona_id` must reference a non-deleted persona. Suites are optional — you can create stand-alone ad-hoc cases.
      operationId: createCase
      tags: [Agent Eval]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, agent_id, persona_id, scenario]
              properties:
                name: { type: string, example: "Yes path — agreement on first ask"  }
                description: { type: string }
                agent_id: { type: string, format: uuid }
                persona_id: { type: string, format: uuid }
                suite_id: { type: string, format: uuid, nullable: true }
                scenario: { type: string }
                success_criteria:
                  type: array
                  items: { $ref: "#/components/schemas/Assertion" }
                  default: []
                max_turns: { type: integer, minimum: 1, maximum: 100, default: 20 }
                pass_threshold: { type: number, minimum: 0, maximum: 100, default: 80 }
                agent_overrides:
                  type: object
                  additionalProperties: true
                  nullable: true
                tool_policy:
                  type: string
                  enum: [mock, real, allowlist]
                  default: mock
                tool_allowlist:
                  type: array
                  items: { type: string }
                  default: []
      responses:
        "201":
          description: Case created
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalCase" } } }
        "400":
          description: "Validation error (e.g. agent_id not found, invalid assertion) AGENT_EVAL_REQUEST_INVALID: a body field this route does not read. It takes agent_id, persona_id, suite_id, name, description, scenario, success_criteria, max_turns, pass_threshold, agent_overrides, tool_policy and tool_allowlist; anything else is refused by name rather than dropped."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
        "403":
          description: Insufficient scope
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agent-eval/cases/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get case
      operationId: getCase
      tags: [Agent Eval]
      responses:
        "200":
          description: Case
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalCase" } } }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    patch:
      summary: Update case
      description: Required scope `agent_eval:update`. Send only the fields you want to change.
      operationId: updateCase
      tags: [Agent Eval]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: { type: string, nullable: true }
                agent_id: { type: string, format: uuid, description: "Repoint the case at another agent in this workspace." }
                persona_id: { type: string, format: uuid }
                suite_id: { type: string, format: uuid, nullable: true }
                scenario: { type: string }
                success_criteria:
                  type: array
                  items: { $ref: "#/components/schemas/Assertion" }
                max_turns: { type: integer, minimum: 1, maximum: 100 }
                pass_threshold: { type: number, minimum: 0, maximum: 100 }
                agent_overrides:
                  type: object
                  additionalProperties: true
                  nullable: true
                tool_policy: { type: string, enum: [mock, real, allowlist] }
                tool_allowlist: { type: array, items: { type: string } }
      responses:
        "200":
          description: Updated case
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalCase" } } }
        "400":
          description: "AGENT_EVAL_REQUEST_INVALID: a body field this route does not read. It takes the fields a case is created with; anything else is refused by name rather than dropped. BAD_REQUEST: an unknown tool_policy, success_criteria that is not an array, a body that is not JSON, or an id that is not a UUID."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "NOT_FOUND: no such case, persona or suite, or a value that cannot be stored (max_turns outside 1 to 100, pass_threshold outside 0 to 100, null where a value is required); nothing is changed. AGENT_NOT_FOUND: agent_id is not an agent of this workspace."
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    delete:
      summary: Delete case
      description: Soft-delete. Required scope `agent_eval:delete`. Existing runs are kept as history.
      operationId: deleteCase
      tags: [Agent Eval]
      responses:
        "200":
          description: Case deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  id: { type: string, format: uuid }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter. A delete reads only its path, so any parameter is refused by name rather than ignored, and nothing is deleted."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agent-eval/cases/{case_id}/run:
    post:
      summary: Run a single case
      description: |
        Trigger one execution of the case. Blocks up to 60 seconds waiting for
        the run to fully finish (worker assertions + billing complete) so simple
        callers don't have to poll for short runs.

        Required scope `agent_eval:run`.

        Response codes:
        - **`200`** — run finished within the 60s window. Body is the full `EvalRun`
          with `case` (and nested `agent` + `persona`) expanded; `score`, `pass_fail`,
          `evaluation`, and the cost columns are final.
        - **`202`** — still running after 60s. Body is the latest non-terminal `EvalRun`.
          Keep polling `GET /agent-eval/runs/{id}` until both `status` is terminal AND
          `queue_status === "done"`.

        There is no synchronous balance check on this endpoint. Insufficient credit
        surfaces asynchronously: the worker sets the run's `status` to `failed` with the
        reason in the run's `error` field — discovered by polling, not via a 402.
      operationId: runCase
      tags: [Agent Eval]
      security: [{ bearerAuth: [] }]
      parameters:
        - in: path
          name: case_id
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                agent_overrides:
                  type: object
                  additionalProperties: true
                  nullable: true
                  description: Optional per-run overrides applied on top of the case's own overrides.
      responses:
        "200":
          description: Run finished within 60s; fully scored.
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalRun" } } }
        "202":
          description: Still running. Keep polling GET /agent-eval/runs/{id}.
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalRun" } } }
        "400":
          description: "AGENT_EVAL_REQUEST_INVALID: a body field this route does not read. It takes agent_overrides; anything else is refused by name rather than dropped."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Case not found
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /agent-eval/suites:
    get:
      summary: List suites
      operationId: listSuites
      tags: [Agent Eval]
      parameters:
        - in: query
          name: limit
          schema: { type: integer, default: 20, maximum: 100 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: List of suites
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/EvalSuite" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read, one sent twice or with no value, or a limit / offset that is not a whole number. It reads limit and offset; the message names what was refused."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Create suite
      description: Required scope `agent_eval:create`. Suites are containers — add cases by setting their `suite_id`.
      operationId: createSuite
      tags: [Agent Eval]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string }
                description: { type: string }
                agent_id: { type: string, format: uuid, nullable: true }
                parallelism: { type: integer, minimum: 1, maximum: 16, default: 1 }
      responses:
        "201":
          description: Suite created
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalSuite" } } }
        "400":
          description: "Validation error AGENT_EVAL_REQUEST_INVALID: a body field this route does not read. It takes name, description, agent_id and parallelism; anything else is refused by name rather than dropped."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /agent-eval/suites/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get suite
      operationId: getSuite
      tags: [Agent Eval]
      responses:
        "200":
          description: Suite
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalSuite" } } }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    patch:
      summary: Update suite
      description: Required scope `agent_eval:update`.
      operationId: updateSuite
      tags: [Agent Eval]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: { type: string, nullable: true }
                agent_id: { type: string, format: uuid, nullable: true, description: "An agent of this workspace, or null to detach the agent." }
                parallelism: { type: integer, minimum: 1, maximum: 16 }
      responses:
        "200":
          description: Updated suite
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalSuite" } } }
        "400":
          description: "AGENT_EVAL_REQUEST_INVALID: a body field this route does not read. It takes name, description, agent_id and parallelism; anything else is refused by name rather than dropped. BAD_REQUEST: parallelism outside 1 to 16, agent_id neither an agent id string nor null, a body that is not JSON, or an id that is not a UUID."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "The suite does not exist, or (code AGENT_NOT_FOUND) agent_id is not an agent of this workspace. GET /agents lists the agents this key can reach."
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    delete:
      summary: Delete suite
      description: Soft-delete. Required scope `agent_eval:delete`. Cases under this suite have their `suite_id` set to null but are not deleted.
      operationId: deleteSuite
      tags: [Agent Eval]
      responses:
        "200":
          description: Suite deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  id: { type: string, format: uuid }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter. A delete reads only its path, so any parameter is refused by name rather than ignored, and nothing is deleted."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agent-eval/suites/{id}/run:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Run a suite
      description: |
        Enqueue every case under the suite as a fresh `eval_runs` row. Returns immediately
        with a synthetic `suite_run_id` that groups the spawned runs. Workers pick up the
        runs and process up to `suite.parallelism` at a time.

        Required scope `agent_eval:run`. The runs are billed to the company's credit balance
        as they finish — see `/billing/consumption?product=eval_run` for an after-the-fact view.

        Suites are always processed asynchronously — poll `GET /agent-eval/suites/{id}/runs/{suite_run_id}`
        until `in_flight === 0` to know the suite settled.

        There is no synchronous balance check. If credit runs out, affected runs come back
        with `status: "failed"` and the reason in each run's `error` field — there is no 402.
      operationId: runSuite
      tags: [Agent Eval]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                mode:
                  type: string
                  enum: [text, voice]
                  default: text
                  description: "`text`, the only mode that runs today. `voice` is reserved for a future loopback mode: it is recorded on the runs, which still run as text."
                agent_overrides:
                  type: object
                  additionalProperties: true
                  nullable: true
                  description: Optional overrides applied to every spawned run on top of each case's `agent_overrides`.
      responses:
        "202":
          description: Suite run queued
          content:
            application/json:
              schema:
                type: object
                required: [suite_run_id, run_ids]
                properties:
                  suite_run_id: { type: string, format: uuid }
                  run_ids:
                    type: array
                    items: { type: string, format: uuid }
        "400":
          description: "Suite has no cases AGENT_EVAL_REQUEST_INVALID: a body field this route does not read. It takes mode and agent_overrides; anything else is refused by name rather than dropped."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: Suite not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agent-eval/suites/{id}/runs:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: List suite executions
      description: |
        List past executions of one suite, newest-first. Each entry is an
        aggregate roll-up — fetch one execution's per-run details with
        `GET /agent-eval/suites/{id}/runs/{suite_run_id}`.
      operationId: listSuiteRuns
      tags: [Agent Eval]
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Past suite executions.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/SuiteRunSummary" }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Suite not found
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /agent-eval/suites/{id}/runs/{suite_run_id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
      - in: path
        name: suite_run_id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get suite execution aggregate
      description: |
        Aggregate view of one suite execution, computed on demand from the runs
        grouped by `suite_run_id`. Poll this every few seconds; once
        `in_flight === 0` the metrics are final.
      operationId: getSuiteRun
      tags: [Agent Eval]
      security: [{ bearerAuth: [] }]
      responses:
        "200":
          description: Suite execution aggregate.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/SuiteRunSummary"
                  - type: object
                    properties:
                      runs:
                        type: array
                        items: { $ref: "#/components/schemas/EvalRun" }
        "400":
          description: "Invalid suite_run_id (not a UUID). AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: No runs found for that suite_run_id
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /agent-eval/runs:
    get:
      summary: List runs
      description: |
        Returns runs for the authenticated company, newest-first. Filterable.
      operationId: listRuns
      tags: [Agent Eval]
      parameters:
        - in: query
          name: case_id
          schema: { type: string, format: uuid }
        - in: query
          name: suite_run_id
          schema: { type: string, format: uuid }
          description: Pass back the value returned by `POST /agent-eval/suites/{id}/run` to fetch only the runs from that suite execution.
        - in: query
          name: suite_id
          schema: { type: string, format: uuid }
          description: Only the runs of this suite's cases, across every execution of it.
        - in: query
          name: status
          schema: { type: string, enum: [queued, running, completed, failed, cancelled] }
        - in: query
          name: limit
          schema: { type: integer, default: 20, maximum: 100 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: List of runs. `case` is expanded inline (which itself expands `agent` and `persona`).
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/EvalRun" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read, one sent twice or with no value, or a limit / offset that is not a whole number. It reads limit, offset, case_id, suite_id, suite_run_id and status; the message names what was refused."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    # POST is gone — to trigger a single case use `POST /agent-eval/cases/{case_id}/run`.

  /agent-eval/runs/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get run
      description: Returns the full run, with `case` (and nested `agent`+`persona`) expanded inline. Use the dedicated sub-routes for turns and evaluation.
      operationId: getRun
      tags: [Agent Eval]
      responses:
        "200":
          description: Run
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalRun" } } }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agent-eval/runs/{id}/turns:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get run turns
      description: Returns every turn from the run, ordered by `turn_number` ascending. Includes persona text, agent text, tool results, and flow events.
      operationId: getRunTurns
      tags: [Agent Eval]
      responses:
        "200":
          description: Ordered list of turns
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/EvalRunTurn" }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agent-eval/runs/{id}/evaluation:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get run evaluation
      description: |
        Returns the run's verdict: `evaluation`, `score`, `pass_fail`, `termination_reason` and `status`, without the rest of the run. Equivalent to `runs/:id` trimmed to the verdict — useful for CI checks where you don't need the transcript. Always returns 200 (404 only when the run id is unknown); `score`, `pass_fail`, and `evaluation` are null until the run reaches a terminal status. Gate CI on `GET /agent-eval/runs/{id}` reaching a terminal `status` AND `queue_status === "done"` rather than on this endpoint's HTTP code.
      operationId: getRunEvaluation
      tags: [Agent Eval]
      responses:
        "200":
          description: Evaluation result. Fields are null until the run is terminal.
          content:
            application/json:
              schema:
                type: object
                required: [id, status, evaluation, score, pass_fail, termination_reason]
                properties:
                  id: { type: string, format: uuid, description: The run id. }
                  status: { type: string, enum: [queued, running, completed, failed, cancelled] }
                  evaluation:
                    description: The assertion roll-up; null until the run is scored.
                    oneOf: [{ type: 'null' }, { $ref: "#/components/schemas/Evaluation" }]
                  score: { type: [number, 'null'] }
                  pass_fail: { type: [boolean, 'null'] }
                  termination_reason: { type: [string, 'null'] }
        "400":
          description: "AGENT_EVAL_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: Run not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  /agent-eval/runs/{id}/cancel:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Cancel a run
      description: |
        Best-effort cancel. If the worker has not yet claimed the run, it transitions
        to `cancelled` immediately and is never executed. If the worker already claimed
        it, the cancellation is signalled and the run terminates at the next turn boundary
        with `termination_reason='cancelled'`. Cancelled runs are still billed for any
        turns already produced. Required scope `agent_eval:run`.
      operationId: cancelRun
      tags: [Agent Eval]
      responses:
        "200":
          description: Cancellation accepted
          content: { application/json: { schema: { $ref: "#/components/schemas/EvalRun" } } }
        "400":
          description: "BAD_REQUEST: the run is already in a terminal state (status not queued/running). AGENT_EVAL_REQUEST_INVALID: a query parameter or a body field. Cancelling reads neither, and anything sent is refused by name rather than ignored."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: Not found
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  # ── Billing consumption ────────────────────────────────────────────────────

  /billing/consumption:
    get:
      summary: Billing consumption
      description: |
        Charges to your account, bucketed by date and product. Useful for usage dashboards,
        monthly invoice reconciliation, and anomaly detection. Required scope `billing:read`.

        Amounts are signed the ledger's way: a charge is positive, credits added are negative.
        By default, credit purchases (top-ups and credits from Yappr) are excluded — pass
        `include_topups=true` to include them as `topup`. For the balance as a statement, signed
        for the account holder, read `GET /billing/transactions`.
      operationId: getBillingConsumption
      tags: [Billing]
      parameters:
        - in: query
          name: from
          schema: { type: string, format: date-time }
          description: >
            Start of the window. Defaults to 30 × 24 hours before now — not the dashboard's
            "Last 30 days", which is 30 whole days on the workspace's clock, today included; send
            `from` as the date 29 days before today to read the same days.
        - in: query
          name: to
          schema: { type: string, format: date-time }
          description: End of the window, inclusive. Defaults to now. A date-only value covers that whole day on the report's clock (`timezone`), up to its last moment; a date-only `from` starts at that day's first moment on the same clock.
        - in: query
          name: timezone
          schema: { type: string, example: Asia/Jerusalem }
          description: >
            The clock days, months and date-only windows are read on, as an IANA name. Defaults to
            the workspace's clock (set with `timezone` on PUT /call-windows); `timezone=UTC` reads
            UTC days. An offset such as `+03:00`, or a name the API does not know, is 400
            CONSUMPTION_QUERY_INVALID. The response names the clock used in `range.timezone`.
        - in: query
          name: group_by
          schema:
            type: string
            enum: [day, month, total, agent, product, disposition, "agent,disposition", source, "agent,source", phone_number, carrier_account]
            default: day
          description: |
            Bucket granularity, `day` when left out. `total` returns one row per product for
            the whole window, with `period: "total"`. `agent` returns one row per agent_id (currently only populated
            for `voice_call`). `disposition` returns one row per outcome, and
            `agent,disposition` one row per agent per outcome — cost and outcomes on the same
            row, which is the whole of a per-client report in one read.

            `source` returns one row per call origin — `test`, `shared_link`, `api`,
            `phone_inbound`, `phone_outbound` — which is what separates a workspace's own
            rehearsals from the calls it was paid for, and `agent,source` answers it per
            agent. The values are the ones `GET /calls` reports and `GET /calls?source=`
            filters by, so the two reads agree call for call.

            An outcome, and an origin, are facts about the CALL a charge belongs to. A charge
            with no call behind it — a number's monthly rent, a top-up, an eval run — buckets
            as `disposition: null` / `source: null`, and so does a call nobody has
            dispositioned; the row's own `agent_id` tells the two apart.

            `phone_number` returns one row per workspace number per product, with `provider`
            saying whose carrier it is: `external` rows are the calls placed on your own
            Telnyx account, whose phone minutes Telnyx billed you for separately; Yappr charges
            no rent for them. A call counts under the workspace number it ran on - the number it
            was placed from, or the workspace number that answered it - so a call your carrier
            number made to one of your Yappr numbers counts under that Yappr number. A charge with no number
            behind it — a browser call, a SIP endpoint call, an eval run, a top-up — buckets as
            `phone_number_id: null`. A number removed since keeps its row and its id.

            `carrier_account` returns one row per carrier account per product - the Telnyx
            account each call ran on, named (`carrier_account`) - so an agency with an account
            per client can rebill each client its carrier calls. Calls on Yappr's carrier and
            their numbers' rent are one row (`carrier_account_id: null`, `provider: telnyx`), and
            charges with no carrier at all - browser and SIP endpoint calls, eval runs - another
            (`provider: null`). A carrier call keeps its account even when its number was removed.

            Anything outside this list is `400`.
        - in: query
          name: product
          schema: { type: string, enum: [voice_call, eval_run, phone_number, topup, refund, adjustment] }
          description: Filter to a single product category. The underlying type names (`voice_usage`, `eval_run_charge`, `phone_number_purchase`, `phone_number_monthly`, `credit_purchase`) are accepted too; anything else is 400.
        - in: query
          name: include_topups
          schema: { type: boolean, default: false }
          description: "`true` or `false`. Any other value is refused with 400 rather than read as false."
        - in: query
          name: sort
          schema: { type: string, enum: [amount, period, name], default: amount }
          description: >
            Row order. `amount` — largest first (the default). `period` — oldest first; only with
            `group_by=day` or `month`. `name` — by agent name, then outcome, then origin, then
            number, then carrier account, then product, A to Z, with the unowned bucket last; not with `day` or `month`. Any other
            value, or one that does not fit the grouping, is 400 CONSUMPTION_QUERY_INVALID.
      responses:
        "200":
          description: Consumption rows
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/BillingConsumption" }
                  range:
                    type: object
                    description: What the rows were read for, as the request resolved it.
                    properties:
                      from: { type: string, format: date-time, description: "The window's first moment, as an instant on every clock (30 × 24 hours before now when left out); a date-only `from` is that day's first moment on `timezone`." }
                      to: { type: string, format: date-time, description: "The window's last moment, as an instant (now when left out); a date-only `to` ends at that day's last microsecond on `timezone` (`.999999Z`), on every clock." }
                      group_by: { type: string }
                      product: { type: string, nullable: true }
                      timezone: { type: string, description: "The clock days, months and date-only windows were read on.", example: Asia/Jerusalem }
                      sort: { type: string, enum: [amount, period, name] }
        "400":
          description: >
            CONSUMPTION_QUERY_INVALID — a parameter other than `from`, `to`, `group_by`, `product`,
            `include_topups`, `timezone` and `sort` (there is no `agent_id` filter: use
            `group_by=agent`), a `timezone` that is not an IANA timezone name, a `sort` outside
            `amount` / `period` / `name` or one that does not fit the grouping, a parameter
            sent twice or with no value, an `include_topups` other than `true` / `false`, a
            `group_by` or `product` outside its list, a `from` / `to` that is not a real ISO 8601
            timestamp (`2026-02-30`, `Aug 2026`), or a `from` after `to`. None of these reaches the
            database, so none of them is a `500`.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "500":
          description: >
            INTERNAL_ERROR — a read the report needs could not be answered. Nothing is left out
            silently: a report that could not read the call or the number behind a charge answers
            this rather than counting the charge under no agent or no number. Retry.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /billing/transactions:
    get:
      summary: Billing transactions
      description: |
        The workspace's billing history as a statement: every change to the credit balance in
        the window, newest first, and the window's opening and closing balance. Required scope
        `billing:read`.

        Top-ups, credits given by Yappr, refunds, adjustments and phone numbers come back one
        by one. Usage comes back as one row per day per product (`voice_call`, `eval_run`),
        with `count` saying how many charges it holds. Days are the workspace's clock (set with
        `timezone` on PUT /call-windows) unless `timezone` names another — the clock
        `GET /billing/consumption` reads by default too, so for the same `from`, `to` and
        `timezone` a month's usage rows add up to its `voice_call` and `eval_run` totals there.

        `summary` always adds up: `opening_balance_cents + credits_in_cents -
        credits_out_cents = closing_balance_cents`. The closing balance of a window that runs
        to now is the balance now. Phone numbers are paid by card, not from the balance: they
        are listed with `affects_balance: false`. `card_charges_cents` is everything charged to
        the card in the window, before VAT - the paid top-ups (`card_top_ups_cents`) and the
        phone numbers (`card_phone_numbers_cents`). A row that did not complete moved nothing either.

        `phone_number_rent` lists each of the workspace's numbers with whether Yappr charges its
        monthly rent (`included`, `reason`) and when it next renews, so a window with no
        `phone_number` row says why.

        Amounts are signed for you, the account holder: positive put credits in, negative took
        them out. That is the opposite sign from `total_amount_cents` in
        `GET /billing/consumption`, which reports charges as positive. All amounts exclude VAT.

        A key limited to agents is refused with `403 API_KEY_AGENT_SCOPED`: the balance is the
        whole workspace's. Its own agents' spend is in `GET /billing/consumption`.

        A top-up row carries `payment`: the invoice number, and what the card was charged with
        VAT, when its payment record holds them. A gift row reads `Credits from Yappr`. Any row
        with an `id` can be read on its own with `GET /billing/transactions/{id}`.

        `format=csv` (or `Accept: text/csv`) answers the window as the dashboard's **Export
        CSV** file: the opening balance, every row oldest first with the balance it left, the
        closing balance and when it was read, up to 1,000 rows. A workspace that has not set a
        clock reads UTC.
      operationId: listBillingTransactions
      tags: [Billing]
      parameters:
        - in: query
          name: from
          schema: { type: string, format: date-time }
          description: >
            Start of the window. Defaults to 30 days before `to` (30 × 24 hours before now when
            `to` is left out as well — not the dashboard's "Last 30 days", which is 30 whole days on
            the workspace's clock). A date-only value starts at that day's first moment on the
            statement's clock. With `to` left out, a `from` after now is 400. A window that starts
            or ends inside a day gives that day's usage row only the charges inside the window;
            send dates to read whole days.
        - in: query
          name: to
          schema: { type: string, format: date-time }
          description: End of the window, inclusive. Defaults to now. A date-only value covers that whole day on the statement's clock, up to its last moment.
        - in: query
          name: timezone
          schema: { type: string, example: Asia/Jerusalem }
          description: >
            The clock days and date-only windows are read on, as an IANA name. Defaults to the
            workspace's clock, like `GET /billing/consumption`; `timezone=UTC` reads UTC days. An
            offset such as `+03:00`, or a name the API does not know, is 400
            TRANSACTIONS_QUERY_INVALID. The response names the clock used in `range.timezone`.
        - in: query
          name: limit
          schema: { type: integer, minimum: 1, maximum: 500, default: 100 }
          description: >
            Most rows to return, newest first. A bigger number is 400 TRANSACTIONS_QUERY_INVALID. `summary` always covers
            the whole window; `has_more` says the list was cut short — over a long window the default
            can end before its older top-ups, so follow `next_cursor` to read them, or ask for
            the file. Not a whole number, or 0,
            is 400. With `format=csv` the default and the maximum are 1,000, as in the dashboard's file;
            above that is 400 too.
        - in: query
          name: cursor
          schema: { type: string }
          description: >
            The `next_cursor` of the page before. Send it with the same `from`, `to`, `timezone` and
            `limit` as that page: every row of the window comes back once, in order, even when a page
            ends inside a day, and every page carries the whole window's `summary`. A cursor sent with
            other parameters, from another workspace, edited or built by hand is 400
            TRANSACTIONS_CURSOR_INVALID. It pages the JSON list; with `format=csv` it is 400
            TRANSACTIONS_QUERY_INVALID.
        - in: query
          name: format
          schema: { type: string, enum: [json, csv], default: json }
          description: >
            `csv` answers the statement as a file, the dashboard's Export CSV (so does `Accept:
            text/csv` with no `format`). Anything else is 400 TRANSACTIONS_QUERY_INVALID.
      responses:
        "200":
          description: The window's rows and its statement — or, with `format=csv`, the same statement as a file
          content:
            text/csv:
              schema:
                type: string
                description: >
                  A byte-order mark, then one quoted line each, every line ending with a newline:
                  `Date,Description,Type,Status,Amount (USD),Credits,Balance after (credits),ID,Balance
                  after (USD),Card charged (USD),VAT (USD),Paid via,Invoice number,Calls`; the opening
                  balance (in the two balance columns, never in Amount, so a sum of Amount is the
                  window's movement); when the window holds more rows than the file, a line saying so -
                  and the first line is then the balance before the first row listed, dated at that row,
                  so the balances chain; every row oldest first with the balance after it (`Credits` empty where the row
                  did not move the balance; `ID` the row's id, or a usage row's day key
                  `<date>:<product>`; a top-up's payment in the four payment columns; a day of calls'
                  `GET /calls/export` link in `Calls`); the closing balance; `Figures as of YYYY-MM-DD
                  HH:MM <clock>`. Served as an attachment named `transactions-<first day>_<last
                  day>-<day read>.csv` (`…-partial.csv` when cut), the name the dashboard's Export CSV
                  gives the same window.
              example: |
                "Date","Description","Type","Status","Amount (USD)","Credits","Balance after (credits)","ID","Balance after (USD)","Card charged (USD)","VAT (USD)","Paid via","Invoice number","Calls"
                "2026-09-01","Opening balance","","","","","1210","","12.10","","","","",""
                "2026-09-21","Credits top-up","Top-up","Completed","50.00","5000","6210","4b1d7c3e-0c1a-4e5f-9a2b-6c7d8e9f0a1b","62.10","59.00","9.00","Checkout","",""
                "2026-09-23","41 charged calls","Usage","Completed","-4.12","-412","5798","2026-09-23:voice_call","57.98","","","","","https://api.goyappr.com/calls/export?from=2026-09-22T21:00:00.000Z&to=2026-09-23T20:59:59.999Z"
                "2026-09-30","Closing balance","","","","","5798","","57.98","","","","",""
                "","Figures as of 2026-09-30 23:59 Asia/Jerusalem","","","","","","","","","","","",""
            application/json:
              schema:
                type: object
                required: [data, summary, balance_cents, has_more, range, phone_number_rent]
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/BillingTransaction" }
                  summary:
                    type: object
                    required: [opening_balance_cents, credits_in_cents, credits_out_cents, closing_balance_cents, card_charges_cents, card_top_ups_cents, card_phone_numbers_cents]
                    properties:
                      opening_balance_cents:
                        type: integer
                        description: The balance at the start of the window, worked back from the balance now.
                      credits_in_cents:
                        type: integer
                        description: Credits the window's completed rows put in (top-ups, credits from Yappr, positive adjustments).
                      credits_out_cents:
                        type: integer
                        description: Credits the window's completed rows took out (usage, refunded top-ups, negative adjustments), as a positive number.
                      closing_balance_cents:
                        type: integer
                        description: The balance at the end of the window. Equals opening + in - out.
                      card_charges_cents:
                        type: integer
                        description: >
                          Everything charged to the card in the window, before VAT: card_top_ups_cents +
                          card_phone_numbers_cents. Until 1 October 2026 it counted the phone numbers only.
                      card_top_ups_cents:
                        type: integer
                        description: The credits the window's paid top-ups bought, before VAT - every one, even when has_more cut rows from data.
                      card_phone_numbers_cents:
                        type: integer
                        description: Phone numbers charged to the card in the window, net of card refunds. Never part of the balance.
                  balance_cents:
                    type: integer
                    description: The credit balance now — the same figure `GET /billing` returns.
                  as_of:
                    type: string
                    format: date-time
                    description: When the statement was read. Today's `in_progress` row, and a closing balance that runs to now, are as of this moment.
                  has_more:
                    type: boolean
                    description: True when the window holds more rows than this page, so its older rows — often its older top-ups — are not in `data` (`summary` still counts them). Follow `next_cursor` to read them.
                  next_cursor:
                    type: string
                    nullable: true
                    description: >
                      Send as `cursor`, with the same `from`, `to`, `timezone` and `limit`, to read the next
                      page; `null` on the window's last page. Opaque and signed with the query it was cut for.
                  range:
                    type: object
                    description: The window that was read — as instants, whatever form `from` and `to` were sent in — and its clock.
                    properties:
                      from: { type: string, format: date-time, description: "The window's first moment." }
                      to: { type: string, format: date-time, description: "The window's last moment." }
                      timezone: { type: string, description: "The clock the days were read on.", example: Asia/Jerusalem }
                  phone_number_rent:
                    type: array
                    description: >
                      Each of the workspace's numbers now, and whether Yappr charges its monthly rent -
                      the `rent` and `next_renewal_at` GET /phone-numbers returns. A number whose rent is
                      included never has a phone_number row. If the rent cannot be read the statement is
                      500, never a number called included.
                    items:
                      allOf:
                        - type: object
                          properties:
                            phone_number_id: { type: string, format: uuid }
                            phone_number: { type: string, nullable: true }
                            provider: { type: string, nullable: true, enum: [telnyx, external] }
                            next_renewal_at: { type: string, format: date-time, nullable: true }
                        - $ref: "#/components/schemas/PhoneNumberRent"
              example:
                data:
                  - id: null
                    type: usage
                    product: voice_call
                    date: "2026-09-23"
                    created_at: "2026-09-23T19:55:12.401+00:00"
                    description: null
                    count: 41
                    status: completed
                    amount_cents: -412
                    affects_balance: true
                    payment: null
                  - id: 4b1d7c3e-0c1a-4e5f-9a2b-6c7d8e9f0a1b
                    type: top_up
                    product: null
                    date: "2026-09-21"
                    created_at: "2026-09-21T08:03:44.120+00:00"
                    description: Credits top-up
                    count: 1
                    status: completed
                    amount_cents: 5000
                    affects_balance: true
                    payment: { channel: checkout, invoice_number: null, receipt_number: null, total_charged_cents: 5900, vat_cents: 900, currency: usd }
                summary:
                  opening_balance_cents: 1210
                  credits_in_cents: 5000
                  credits_out_cents: 3666
                  closing_balance_cents: 2544
                  card_charges_cents: 6000
                  card_top_ups_cents: 5000
                  card_phone_numbers_cents: 1000
                balance_cents: 2544
                as_of: "2026-09-30T23:59:59.999999+00:00"
                has_more: false
                next_cursor: null
                range: { from: "2026-08-31T21:00:00.000Z", to: "2026-09-30T20:59:59.999999Z", timezone: Asia/Jerusalem }
                phone_number_rent:
                  - { phone_number_id: c0ffee00-0000-4000-8000-000000000001, phone_number: "+972501234567", provider: telnyx, included: false, reason: null, monthly_price_cents: 1000, last_charged_at: "2026-09-18T09:31:00Z", next_renewal_at: "2026-10-18T09:30:00.000Z" }
        "400":
          description: >
            TRANSACTIONS_QUERY_INVALID — a parameter other than `from`, `to`, `limit`, `timezone`,
            `format` and `cursor`, a `cursor` with `format=csv`, a parameter sent twice or with no value, a `limit` that is not a whole
            number of at least 1 or is above the maximum (500, or 1,000 for the file), a `timezone` that is not an IANA timezone name, a `format` other
            than `json` or `csv`, a `from` / `to`
            that is not a real ISO 8601 timestamp, a `from` after `to` on the statement's clock (a
            date-only `to` ends that day on it), or a `from` after now with `to` left out. None of these reaches the database.
            TRANSACTIONS_CURSOR_INVALID — a `cursor` this query did not issue: one from a page read with
            another `from`, `to`, `timezone` or `limit`, from another workspace, or edited.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `billing:read`. API_KEY_AGENT_SCOPED — the key is
            limited to agents, and the balance belongs to the whole workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "500":
          description: >
            "Failed to load the transaction history" - the statement, its top-ups' payments, the
            window's top-up total or the numbers' rent could not be read. Retry; nothing was changed.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /billing/transactions/{id}:
    get:
      summary: Get a billing transaction
      description: |
        One row of the statement, by the `id` a row of `GET /billing/transactions` carries — the
        same shape as in the list, plus `timezone`, the clock its `date` is on. Required scope
        `billing:read`.

        A top-up carries `payment`: how it was paid, the invoice and receipt numbers, and what
        the card was charged with VAT, when its payment record holds them. Usage rows fold a day
        of charges and have no id, so one charge's id is not a row here, and neither is a call's
        id (the 404 says which): a call's cost is on `GET /calls/{id}`.

        A key limited to agents is refused with `403 API_KEY_AGENT_SCOPED`: the balance is the
        whole workspace's.
      operationId: getBillingTransaction
      tags: [Billing]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: string, format: uuid }
          description: The row's `id` from `GET /billing/transactions`. Not a UUID is 404 RESOURCE_ID_INVALID.
        - in: query
          name: timezone
          schema: { type: string, example: Asia/Jerusalem }
          description: >
            The clock `date` is read on, as an IANA name. Defaults to the workspace's clock, as the
            list does. Not a timezone name is 400 TRANSACTIONS_QUERY_INVALID.
      responses:
        "200":
          description: The row
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: "#/components/schemas/BillingTransaction" }
                  - type: object
                    required: [timezone]
                    properties:
                      timezone: { type: string, description: "The clock `date` was read on.", example: Asia/Jerusalem }
              example:
                id: 4b1d7c3e-0c1a-4e5f-9a2b-6c7d8e9f0a1b
                type: top_up
                product: null
                date: "2026-09-21"
                created_at: "2026-09-21T08:03:44.120+00:00"
                description: Credits top-up
                count: 1
                status: completed
                amount_cents: 5000
                affects_balance: true
                payment: { channel: checkout, invoice_number: null, receipt_number: null, total_charged_cents: 5900, vat_cents: 900, currency: usd }
                timezone: Asia/Jerusalem
        "400":
          description: >
            TRANSACTIONS_QUERY_INVALID — a query parameter other than `timezone`, sent twice or
            with no value, or a `timezone` that is not an IANA timezone name.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `billing:read`. API_KEY_AGENT_SCOPED — the key is
            limited to agents, and the balance belongs to the whole workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: >
            NOT_FOUND — no row with that id in this workspace, the id is one charge that a
            day's usage row folds, or it is a call's id (the message says so). RESOURCE_ID_INVALID
            — the id is not a UUID.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /billing/rates:
    get:
      summary: Get your workspace's per-minute rates
      description: |
        What a minute of a call costs your workspace. Required scope `billing:read`. Prices are
        per workspace, and these are the ones its calls are charged from, so a price read here is
        the price a call is charged.

        Every price is in credits (cents) per minute. A phone call costs the same on every voice
        model: `default_rate_per_minute_cents`, which each entry of `voice_models` repeats.
        `voice_models` is in a stable order (`gemini-3.1-flash-live`, `gemini-3.8-live`,
        `gpt-live`); `model` is the same id an agent carries as `model`. Browser calls and the part
        of a call after it is passed to a person have prices of their own.

        `ai_training_multiplier` is `2` on a workspace that opted out of AI training and `1` otherwise:
        what the workspace is charged per minute is the price times it, exactly as on its call charges.

        A key limited to agents is refused with `403 API_KEY_AGENT_SCOPED`, as the rest of billing is.
      operationId: getBillingRates
      tags: [Billing]
      responses:
        "200":
          description: The workspace's prices
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BillingRates" }
              example:
                currency: usd
                voice_models:
                  - { model: gemini-3.1-flash-live, name: Gemini 3.1 Flash Live, rate_per_minute_cents: 30, effective_from: null }
                  - { model: gemini-3.8-live, name: Gemini 3.8 Live, rate_per_minute_cents: 30, effective_from: null }
                  - { model: gpt-live, name: GPT Live, rate_per_minute_cents: 30, effective_from: null }
                default_rate_per_minute_cents: 30
                browser_call_rate_per_minute_cents: 10
                after_transfer_rate_per_minute_cents: 25
                ai_training_multiplier: 1
        "400":
          description: "BILLING_QUERY_INVALID: a query parameter. This route reads none, and anything sent is refused by name rather than ignored."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `billing:read`. API_KEY_AGENT_SCOPED — the key is
            limited to agents, and billing belongs to the whole workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /billing/details:
    get:
      summary: Get billing details
      description: |
        What every invoice prints, and where it is emailed: the business name, the address
        invoices are sent to, the postal address, the tax ID (VAT or company number), and the
        invoice language. Required scope `billing:manage`: the full email, the address and the
        tax ID are personal data, so a `billing:read` key that reads the balance and the
        invoices does not read these.

        A workspace that has never paid reads the details its first invoice would use: the
        workspace name, the workspace owner's email, no address, no tax ID, English. Nothing is
        created by reading.

        Invoices are issued in English. A workspace that works in Hebrew (`language: he`) gets
        English invoices with day-first dates.
      operationId: getBillingDetails
      tags: [Billing]
      responses:
        "200":
          description: The billing details
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BillingDetails" }
              example:
                name: Acme Ltd
                email: billing@acme.example
                address: { line1: 1 Example St, line2: null, city: Tel Aviv, state: null, postal_code: "6100000", country: IL }
                tax_id: { type: il_vat, value: "000012345" }
                language: he
        "400":
          description: "BILLING_QUERY_INVALID: a query parameter. This route reads none, and anything sent is refused by name rather than ignored."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `billing:manage`. API_KEY_AGENT_SCOPED — the key is
            limited to agents, and billing belongs to the whole workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "502":
          description: "BILLING_UNAVAILABLE: the details could not be read right now. Try again in a minute."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
    patch:
      summary: Update billing details
      description: |
        Change what invoices print. Send any of `name`, `email`, `address`, `tax_id` and
        `language`; fields left out stay as they are. Required scope `billing:manage`.

        `null` resets: `name` to the workspace name, `email` to the workspace owner's email, and
        removes the address or the tax ID. A workspace keeps one tax ID; sending a new one
        replaces it, and a number that is not valid for its type is refused with
        `TAX_ID_INVALID` and the old one stays.

        A change applies to invoices issued after it. An invoice already issued is never
        changed. Invoices are issued in English; `language: he` gives English invoices with
        day-first dates. The answer is the same body `GET /billing/details` returns.
      operationId: updateBillingDetails
      tags: [Billing]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/BillingDetailsUpdate" }
            examples:
              business:
                summary: Business name, address and Israeli VAT number
                value:
                  name: Acme Ltd
                  address: { line1: 1 Example St, city: Tel Aviv, postal_code: "6100000", country: IL }
                  tax_id: { type: il_vat, value: "000012345" }
              send_elsewhere:
                summary: Send invoices to the bookkeeper
                value: { email: books@acme.example }
              reset:
                summary: Back to the defaults
                value: { name: null, email: null, address: null, tax_id: null }
      responses:
        "200":
          description: The billing details, as saved
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BillingDetails" }
        "400":
          description: |
            One of:
            BILLING_DETAILS_EMPTY — no field was sent, or the body is not a JSON object.
            BILLING_DETAILS_UNKNOWN_FIELD — a field that is not a billing detail, named in the message.
            BILLING_NAME_INVALID — `name` is not 1 to 256 characters.
            BILLING_EMAIL_INVALID — `email` is not a full email address.
            BILLING_ADDRESS_INVALID — `address` lacks `line1` or a two-letter country code, or carries a field it does not take.
            TAX_ID_TYPE_UNSUPPORTED — `tax_id.type` is not one of the listed types.
            TAX_ID_INVALID — the number is not valid for its type; the old tax ID stays.
            BILLING_LANGUAGE_INVALID — `language` is not `en` or `he`.
            BILLING_QUERY_INVALID — a query parameter; this write reads none.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `billing:manage`. API_KEY_AGENT_SCOPED — the key is
            limited to agents, and billing belongs to the whole workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "502":
          description: "BILLING_UNAVAILABLE: the details could not be saved right now. Try again in a minute."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /billing/invoices:
    get:
      summary: List invoices
      description: |
        Every invoice this workspace has been sent, newest first: credit top-ups, automatic
        top-ups and phone-number charges (the first month and every renewal). Each one is
        emailed to the billing email when it is paid. Required scope `billing:read`.

        Paid, open and uncollectible invoices are listed; a draft is not an invoice yet and a
        void one was never owed. `view_url` is the invoice's own page and `pdf_url` downloads
        it. Amounts are in cents: `total_cents` is what was charged, `vat_cents` the VAT in it,
        `net_cents` the rest, and `refunded_cents` whatever was paid back.

        Follow `next_cursor` until it is `null`. A page can hold fewer than `limit` invoices
        while `next_cursor` is still set; keep following it. Invoices are issued in English.
      operationId: listInvoices
      tags: [Billing]
      parameters:
        - in: query
          name: limit
          schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
          description: How many invoices to return, 1 to 100. Default 20.
        - in: query
          name: cursor
          schema: { type: string }
          description: The `next_cursor` of the previous page. Leave it out to start from the newest invoice.
      responses:
        "200":
          description: One page of invoices
          content:
            application/json:
              schema: { $ref: "#/components/schemas/InvoiceList" }
              example:
                invoices:
                  - number: 4F2A9C1B-0007
                    kind: credits_top_up
                    description: Credits top-up
                    phone_number: null
                    status: paid
                    issued_at: "2026-10-21T09:14:02.000Z"
                    paid_at: "2026-10-21T09:14:02.000Z"
                    currency: usd
                    net_cents: 5000
                    vat_cents: 900
                    total_cents: 5900
                    refunded_cents: 0
                    lines:
                      - { description: Credits top-up, quantity: 1, unit_amount_cents: 5000, amount_cents: 5000 }
                      - { description: VAT (18%), quantity: 1, unit_amount_cents: 900, amount_cents: 900 }
                    view_url: https://invoice.stripe.com/i/example
                    pdf_url: https://pay.stripe.com/invoice/example/pdf
                next_cursor: null
        "400":
          description: |
            One of:
            INVOICE_LIMIT_INVALID — `limit` is not a whole number from 1 to 100.
            INVOICE_CURSOR_INVALID — `cursor` is not a `next_cursor` this list returned.
            BILLING_QUERY_INVALID — a query parameter other than `limit` and `cursor`.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            INSUFFICIENT_SCOPE — the key lacks `billing:read`. API_KEY_AGENT_SCOPED — the key is
            limited to agents, and billing belongs to the whole workspace.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "502":
          description: "BILLING_UNAVAILABLE: the invoices could not be read right now. Try again in a minute."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  # ── Deliveries ─────────────────────────────────────────────────────────────

  /deliveries:
    get:
      summary: List webhook deliveries
      description: |
        Every webhook delivery in this workspace, newest first, across calls — settled ones, and
        any still sending (`status: pending`). Required scope
        `calls:read` or `tools:read` — either one (a `calls:read` key already reads these rows
        in every call's timeline).

        A delivery row here is the `delivery` row of a call's timeline
        (`GET /calls/{id}` → `timeline[]`), field for field, plus the `call_id` it happened
        on and its `source`. One parser reads both. It is how you confirm a configured webhook
        actually fired — for one call, for one tool across a week, or for everything that
        failed last night. A retry is a row of its own with `retry_of` set, and the row it
        re-sent carries `retried_by`, so an original and its retry never read alike.

        A rehearsal counts. A `POST /tools/{id}/test` that actually reaches the endpoint
        writes a row here too — a legacy webhook tool's test at once, a workflow tool's real
        test (`policy: allowlist`) once its request settles — with `call_id: null` and
        `source: test`, so "did my test reach the endpoint?" is answered from the same log. A
        delivery sent on a test call placed from the dashboard is `source: test` as well. A
        mock test sends nothing and writes nothing. Left out, `?source=` narrows nothing and
        both kinds are returned.

        Summaries only, exactly as the per-call timeline is. One delivery's request body and
        its endpoint's answer are read with `GET /deliveries/{id}`, with every configured
        header value replaced; no URL or header value leaves the platform here.

        **Paging is by cursor, not by offset.** This log grows while it is being read — a
        running campaign writes to it between two pages — so an offset would silently skip or
        repeat rows. Follow `pagination.next_cursor` until `has_more` is `false`.
      operationId: listDeliveries
      tags: [Deliveries]
      parameters:
        - in: query
          name: tool_id
          schema: { type: string, format: uuid }
          description: >
            Only deliveries sent by this tool's step - a before-call step's included (from 2
            October 2026), and on test calls too.
        - in: query
          name: agent_id
          schema: { type: string, format: uuid }
          description: >
            Deliveries this agent sent, plus deliveries its tools sent on its calls. An agent
            on the workflow engine sends through its tools rather than in its own name, so
            both are answered here — the filter never reads as "this agent sent nothing"
            because of where the agent happens to be configured.
        - in: query
          name: call_id
          schema: { type: string, format: uuid }
          description: Only deliveries on this one call — the same rows its timeline carries.
        - in: query
          name: status
          schema: { type: string, enum: [delivered, failed, pending, unknown] }
          description: >
            `failed` is the delivery-health query; `unknown` lists what to check on your side -
            leaving out a delivery whose chain ended delivered (its retry, or a later retry of
            it, was accepted), which is settled. Anything outside the list is
            400 DELIVERIES_QUERY_INVALID.
        - in: query
          name: retried
          schema: { type: string, enum: ["true", "false"] }
          description: >
            `false` for only the deliveries not yet sent again (`retried_by` null) - what a
            "retry every failure" loop should read - and `true` for only those that were. Left
            out, both. Anything else is 400 DELIVERIES_QUERY_INVALID. With either, a page can
            hold fewer rows than `limit` while `has_more` is true.
        - in: query
          name: source
          schema: { type: string, enum: [live, test] }
          description: >
            `live` for real traffic only (real calls and lead events), `test` for the
            rehearsals — what `POST /tools/{id}/test` sent and what was sent on a test call
            placed from the dashboard. Left out, both are returned. Anything outside the list
            is 400 DELIVERIES_QUERY_INVALID.
        - in: query
          name: from
          schema: { type: string, format: date-time }
          description: >
            Deliveries whose `at` is on or after this timestamp. A value that is not a real date —
            including a month-end its month does not have, like 2026-09-31 — is
            400 DELIVERIES_QUERY_INVALID.
        - in: query
          name: to
          schema: { type: string, format: date-time }
          description: Deliveries whose `at` is on or before this timestamp. Refused the same way from is. A date-only value covers that whole day (UTC).
        - in: query
          name: limit
          schema: { type: integer, default: 50, maximum: 200 }
        - in: query
          name: cursor
          schema: { type: string }
          description: >
            `pagination.next_cursor` from the previous page, sent with the same filters (`limit`
            may change). A cursor this endpoint did not issue, or one cut for other filters, is
            400 DELIVERY_CURSOR_INVALID (`issues[0].code` `cursor_invalid`) rather than a silent
            first page.
      responses:
        "200":
          description: Delivery rows, newest first
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Delivery" }
                  pagination:
                    type: object
                    properties:
                      limit: { type: integer }
                      has_more: { type: boolean }
                      next_cursor:
                        type: string
                        nullable: true
                        description: Pass as `cursor` for the next page. Null on the last one.
        "400":
          description: >
            `DELIVERIES_QUERY_INVALID` — a filter this log does not have, a filter sent with no
            value, a `status` / `retried` / `limit` outside its range, or a `from` / `to` that is not a real
            timestamp. `DELIVERY_CURSOR_INVALID` — the
            `cursor` was not issued by this endpoint, or was cut for a list with other filters
            (the message says which; `issues` names `cursor`).
            A parameter sent twice is refused too (DELIVERIES_QUERY_INVALID), and a cursor is signed: one built by hand or taken from GET /calls is DELIVERY_CURSOR_INVALID.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404": { description: "AGENT_NOT_FOUND, NOT_FOUND or WORKFLOW_NOT_FOUND - agent_id, call_id or tool_id names nothing in this workspace. The message names the filter.", content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
        "401":
          description: "`MISSING_KEY`, `INVALID_KEY` or `EXPIRED_KEY`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: "`INSUFFICIENT_SCOPE` — the key holds neither `calls:read` nor `tools:read`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }


  /deliveries/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get one delivery
      description: |
        One delivery: the list's row, plus the body that was sent, the sender's method and
        header names, and what the endpoint answered — every configured header value, and the
        sender's query values, replaced by `[REDACTED]`. Required scope `calls:read` or `tools:read`. Takes no query
        parameters.

        An id that is not a delivery in this workspace is `404 DELIVERY_NOT_FOUND`, and a
        second path segment that is not an id is `404 RESOURCE_ID_INVALID` — never the list.
      operationId: getDelivery
      tags: [Deliveries]
      responses:
        "200":
          description: The delivery
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeliveryDetail" }
        "400":
          description: "`DELIVERIES_QUERY_INVALID` — a query parameter was sent; this read takes none."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: "`MISSING_KEY`, `INVALID_KEY` or `EXPIRED_KEY`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: "`INSUFFICIENT_SCOPE` — the key holds neither `calls:read` nor `tools:read`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`DELIVERY_NOT_FOUND` or `RESOURCE_ID_INVALID`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "503":
          description: "`WEBHOOK_DELIVERY_UNAVAILABLE` — the request and response could not be read; try again."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /deliveries/{id}/retry:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Retry a failed delivery
      description: |
        Sends a failed delivery again, once, and answers with the new attempt. Required scope
        `tools:update` — the scope that already sends a tool's request on demand
        (`POST /tools/{id}/test`).

        **What is sent.** The body stored with the delivery — exactly what the original
        attempt sent — to where the sender points **now**: its current URL, method, headers
        and timeout. Fix the endpoint or the tool's address, then retry. One attempt, no
        automatic retries. A retried tool test is still a test (`X-Webhook-Test: true`), and
        so is a retry of a delivery made on a dashboard test call.
        It carries `X-Webhook-Delivery-Id` with the chain's first delivery id (the same on
        every retry of it), `X-Webhook-Retry-Of` with the delivery it re-sends, and
        `X-Webhook-Delivery-Attempt` counted across them - a retry of a delivery sent once is
        attempt 2, and its `attempt_count` reads 2.
        `GET /deliveries/{id}` says beforehand where a retry would go (`retry_target`) and
        whether that differs from where the delivery went (`request.destination`); the new
        delivery records the address and the tool revision it was sent with.

        **Linked, and once.** The retry is a new delivery with `retry_of` set to this one, and
        this one's `retried_by` points at it. A delivery is retried at most once — a second
        request, even one racing the first, is `409 DELIVERY_ALREADY_RETRIED` and sends
        nothing. If the retry fails too, retry the retry.

        **Only what failed.** An accepted delivery would be delivered twice, so it is refused
        (`409 DELIVERY_NOT_RETRYABLE`) — including a workflow tool's delivery the endpoint
        answered with a 2xx the tool could not use — as is one still pending. A sender that is
        gone, is not a webhook, or has no usable address is `409 DELIVERY_SENDER_UNAVAILABLE`,
        and a delivery whose tool is archived is `404 WORKFLOW_TOOL_ARCHIVED` (the status a test
        of an archived tool answers) until the tool is restored (`POST /tools/{id}/restore`).

        **Not blindly what nobody knows.** An `unknown` delivery got no answer in time, so the
        endpoint may already have acted on it. It is sent again only with
        `{"acknowledge_unknown": true}`; without it, `409 DELIVERY_OUTCOME_UNKNOWN` and nothing
        is sent. A retry that gets no answer in time reads `unknown` itself.
      operationId: retryDelivery
      tags: [Deliveries]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                acknowledge_unknown:
                  type: boolean
                  description: >
                    Send an `unknown` delivery again, knowing the endpoint may already have acted
                    on it. Changes nothing for a `failed` delivery.
      responses:
        "201":
          description: >
            The retry was sent. The body is the new delivery; its `status` says whether the
            endpoint accepted it this time.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DeliveryDetail" }
        "401":
          description: "`MISSING_KEY`, `INVALID_KEY` or `EXPIRED_KEY`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: "`INSUFFICIENT_SCOPE` — the key lacks `tools:update`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "400":
          description: >
            `DELIVERY_RETRY_INVALID` — the body is not none, `{}` or
            `{"acknowledge_unknown": true|false}`. Nothing was sent.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: >
            `DELIVERY_NOT_FOUND`, `RESOURCE_ID_INVALID`, or `WORKFLOW_TOOL_ARCHIVED` (the tool
            that sent it is archived; restore it first). Nothing was sent.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "409":
          description: >
            `DELIVERY_NOT_RETRYABLE` (accepted — a 2xx the tool could not use included — or
            still pending), `DELIVERY_OUTCOME_UNKNOWN` (no answer came back; send
            `acknowledge_unknown: true` to send it again anyway), `DELIVERY_ALREADY_RETRIED`
            (the body carries `retried_by`), or `DELIVERY_SENDER_UNAVAILABLE`. Nothing was sent.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "503":
          description: "`WEBHOOK_DELIVERY_UNAVAILABLE` — nothing was sent; try again."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
  # ── Campaigns ──────────────────────────────────────────────────────────────

  /campaigns:
    get:
      summary: List campaigns
      description: |
        Newest-first. Required scope `campaigns:read`.
      operationId: listCampaigns
      tags: [Campaigns]
      parameters:
        - in: query
          name: status
          schema: { type: string }
          description: "Comma-separated list of statuses to include, e.g. `running,paused_insufficient_credit`. Omit for every non-archived campaign; `archived` lists the archived ones."
          example: "running,paused"
        - in: query
          name: limit
          schema: { type: integer, default: 50, maximum: 200 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: List of campaigns
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Campaign" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean, description: "Whether another page follows: page with offset += limit while it is true." }
                  company_id: { type: string, format: uuid }
        "400":
          description: "CAMPAIGNS_QUERY_INVALID \u2014 `status` names a campaign status that does not exist. CAMPAIGNS_QUERY_INVALID: a query parameter this route does not read, one sent twice or with no value, or a limit / offset that is not a whole number. It reads limit, offset and status; the message names what was refused."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: Insufficient scope
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

    post:
      summary: Create campaign
      description: |
        Creates the campaign in `draft`. Nothing is dialed until you enroll contacts and
        call `POST /campaigns/{id}/launch`. Required scope `campaigns:manage`.

        Only the fields below may be sent. Any other key — including every engine-owned
        field (`status`, `spent_cents`, `daily_admitted_count`, `last_tick_result`, …) and
        every typo — is rejected with `400` listing the writable set.

        **No configuration field has a default but `stop_disposition_ids`**, which takes the
        suggested stop set when left out. The `example` values show what the dashboard
        prefills, but any other field you omit stays `null` and `launch` refuses with
        `422 CAMPAIGN_NOT_READY` naming it. This is deliberate: how many times to call
        someone, and how often, are decisions the platform will not make on your behalf.
        `GET /campaigns/defaults` returns the dashboard's suggested settings, resolved for
        this workspace, ready to send here. Send every field on create, or fill the gaps
        with `PATCH` before launching.
      operationId: createCampaign
      tags: [Campaigns]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string, example: "July reactivation"  }
                description: { type: string, nullable: true }
                agent_id: { type: string, format: uuid, description: "Required before launch." }
                from_phone_number_id:
                  type: string
                  format: uuid
                  nullable: true
                  description: >
                    The number to call from. Leave it out to call from the agent's own number
                    (`from_number` in the answer says which); `400` with `invalid_from_number` when
                    the agent has no number and none is sent.
                split:
                  nullable: true
                  description: >
                    Optional two-agent A/B test. `percent` is the share of contacts the
                    SECOND agent takes; `agent_id` above takes the rest. Send `null` to
                    turn it off. `422 INVALID_SPLIT` when the object has a key other than
                    those two, the percent is outside 1–99, or the second agent is the same
                    as `agent_id`. An agent that is not in this workspace is 404 AGENT_NOT_FOUND.
                  allOf:
                    - $ref: "#/components/schemas/AgentSplit"
                variables:
                  type: object
                  additionalProperties: { type: string }
                  description: >
                    Values for the agent's `{{placeholders}}` on every call this campaign
                    places. `FirstName` and `FullName` are filled on each call from its
                    contact's own name; the value here is what a contact with no name hears.
                    String values only; the automatically filled names
                    (`CallerPhone`, `CurrentDate`, `CurrentDateTime`, `CurrentTime`,
                    `CallDirection`, `Timezone`) are refused.
                calling_window:
                  type: object
                  additionalProperties: true
                  description: >
                    Optional narrowing of the workspace calling hours. Cannot widen them.
                    `tz` (an IANA zone name) is required whenever `days`, `start` or
                    `end` is present; `{}` inherits the workspace schedule. `days` 0–6,
                    each once, never empty; `start`/`end` as HH:MM, together, `end` later
                    than `start`.
                stop_disposition_ids:
                  type: array
                  items: { type: string, format: uuid }
                  description: >
                    Disposition IDs (never labels) that retire a contact permanently.
                    Interested is accepted like any outcome you name. Do not include
                    `No Answer`, `Failed`, `Voicemail` or `Unclassified` (refused) — use
                    `stop_on_no_answer` / `stop_on_voicemail` / `stop_on_unclassified` instead.
                    Left out, the campaign stops on the set `GET /campaigns/defaults` returns
                    (Interested and the workspace's own outcomes included); `[]` for none.
                stop_on_no_answer: { type: boolean, example: false }
                stop_on_voicemail: { type: boolean, example: false }
                stop_on_unclassified: { type: boolean, example: false }
                max_attempts: { type: integer, minimum: 1, maximum: 999, example: 3 }
                max_infra_retries: { type: integer, minimum: 0, maximum: 20, example: 3 }
                retry_no_answer_seconds: { type: integer, minimum: 30, maximum: 604800, example: 3600 }
                retry_completed_seconds: { type: integer, minimum: 60, maximum: 604800, example: 86400 }
                randomize_retry_time: { type: boolean, example: false, description: "false keeps a retry at the same time of day; true picks another hour inside the calling window." }
                double_dial_enabled: { type: boolean, example: false }
                double_dial_gap_seconds: { type: integer, minimum: 10, maximum: 3600, example: 90 }
                max_calls_per_day: { type: integer, minimum: 1, maximum: 100000, example: 200 }
                min_seconds_between_calls: { type: integer, minimum: 0, maximum: 86400, example: 30 }
                max_in_flight: { type: integer, minimum: 1, maximum: 8, example: 2 }
                budget_cents: { type: integer, minimum: 1, nullable: true, description: "Hard spend cap in credits (a credit is a cent). At least one call's hold once the campaign has an agent. Null for no cap." }
                regulatory_basis:
                  type: string
                  enum: [lawful_basis_confirmed, consent, existing_customer, non_marketing, registry_screened]
                  description: "Required before launch."
                starts_at: { type: string, format: date-time, nullable: true }
                ends_at: { type: string, format: date-time, nullable: true }
      responses:
        "201":
          description: Campaign created in `draft`
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "400":
          description: >
            CAMPAIGN_REQUEST_INVALID — unknown or read-only field, missing `name`, a numeric field
            out of range, a `regulatory_basis` outside the enum, a
            `stop_disposition_ids` entry that isn't one of your company's dispositions — or is not
            an id at all, such as a label — a `calling_window` that cannot open (unknown `tz`,
            empty or impossible `days`, `start`/`end` not HH:MM or `end` not after `start`), an
            `ends_at` already passed or not after `starts_at`, a `calling_window` that never
            opens between `starts_at` and `ends_at`, a platform outcome (`No Answer`,
            `Voicemail`, `Unclassified`, `Failed`) in `stop_disposition_ids`, a
            `budget_cents` below one call's hold, a `from_phone_number_id` that is not an id or not a
            phone number in this workspace, no `from_phone_number_id` for an `agent_id` that has no
            number to call from, an `agent_id` or `split.agent_id` that is not an agent here,
            or a body that is not JSON. Every problem is in the one answer: issues[] names each
            (field_unknown at each unknown field's pointer with the field it was likely meant to be,
            campaign_request_invalid for a value, platform_stop_outcome and outcome_not_found at
            /stop_disposition_ids/<n>, invalid_from_number, agent_not_found) and error is the first
            with a count. Nothing was written.
          content: { application/json: { schema: { $ref: "#/components/schemas/WorkflowError" } } }
        "422":
          description: >
            `INVALID_SPLIT` — the split is not an object or `null`, carries a key
            other than `agent_id` / `percent`, the share is outside 1–99, the second
            agent is the one already on the campaign. An agent field that names no agent
            in this workspace (`agent_id` or `split.agent_id`) is 400 `CAMPAIGN_REQUEST_INVALID`,
            with `agent_not_found` at that field in issues[].
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: >
            Insufficient scope. For a key limited to some agents, also `AGENT_OUTSIDE_KEY_SCOPE`
            (an agent that is not the key's) or `API_KEY_AGENT_SCOPED` (a `from_phone_number_id`
            none of the key's agents answers or calls from).
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /campaigns/defaults:
    get:
      summary: Suggested campaign settings
      description: |
        The settings the dashboard's campaign wizard starts a new campaign from, resolved
        for this workspace. `settings` can be sent to `POST /campaigns` as-is, together
        with `name`, `agent_id`, `from_phone_number_id` and `regulatory_basis`.

        These are suggestions the caller sends, not defaults the API applies: a
        name-only `POST /campaigns` stores every other configuration field `null`.
        The exception is `stop_disposition_ids`, which a create that leaves it out
        takes from here. The set is copied when the campaign is created: an outcome
        added later stops only campaigns created after it; send this list with
        `PATCH /campaigns/{id}` to re-apply it. It includes every outcome the
        workspace added itself, a "call me back" one included. Required scope `campaigns:read`.
      operationId: getCampaignDefaults
      tags: [Campaigns]
      responses:
        "200":
          description: The suggested settings for this workspace
          content:
            application/json:
              schema:
                type: object
                properties:
                  settings:
                    type: object
                    description: >
                      Writable campaign fields with their suggested values.
                      `stop_disposition_ids` holds this workspace's Interested, Appointment
                      Set, Not Interested, Issue Resolved, Transferred to a Person, Wrong Number
                      and Do Not Call outcomes (any the workspace still has) and every outcome
                      the workspace added itself — all but Callback Requested and the four
                      Yappr assigns (No Answer, Voicemail, Unclassified, Failed). `calling_window` is
                      in the workspace timezone and follows the workspace calling hours when
                      it has them: while `outbound_enabled` is true, their days from the earliest
                      opening to the latest close (the hours still trim each day); while it is
                      false, the window that fits inside the hours of every day it offers;
                      without hours it is 09:00–18:00, Sunday–Thursday where that is the working
                      week and Monday–Friday elsewhere. `{}` when the workspace has no timezone.
                    properties:
                      stop_disposition_ids: { type: array, items: { type: string, format: uuid } }
                      calling_window: { type: object, additionalProperties: true }
                      stop_on_no_answer: { type: boolean, example: false }
                      stop_on_voicemail: { type: boolean, example: false }
                      stop_on_unclassified: { type: boolean, example: false }
                      max_attempts: { type: integer, example: 3 }
                      max_infra_retries: { type: integer, example: 3 }
                      retry_no_answer_seconds: { type: integer, example: 3600 }
                      retry_completed_seconds: { type: integer, example: 86400 }
                      randomize_retry_time: { type: boolean, example: false }
                      double_dial_enabled: { type: boolean, example: false }
                      double_dial_gap_seconds: { type: integer, example: 90 }
                      max_calls_per_day: { type: integer, example: 200 }
                      min_seconds_between_calls: { type: integer, example: 30 }
                      max_in_flight: { type: integer, example: 2 }
                  stop_dispositions:
                    type: array
                    description: The full outcome objects behind `settings.stop_disposition_ids`.
                    items: { type: object, additionalProperties: true }
                  timezone: { type: string, nullable: true }
                  window_source:
                    type: string
                    enum: [workspace_hours, suggested]
                    description: Where `settings.calling_window` came from — the workspace calling hours, or the fixed suggestion when the workspace has none.
                  company_id: { type: string, format: uuid }
        "400":
          description: CAMPAIGNS_QUERY_INVALID — a query parameter was sent; this read takes none, and the message names it.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: Insufficient scope
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "405":
          description: "`METHOD_NOT_ALLOWED` — any method but GET. This path never creates a campaign."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "500":
          description: The workspace's timezone or outcomes could not be read.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /campaigns/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get campaign
      description: |
        Returns one campaign with `agent`, `from_phone_number` and `stop_dispositions`
        expanded to the full objects they reference. An archived campaign answers `404`,
        the same as one that never existed. Required scope `campaigns:read`.

        For progress counters (how many contacts are pending, dialing, exhausted) use
        `GET /campaigns/{id}/stats` instead — this endpoint returns configuration and
        engine state, not a per-contact breakdown.
      operationId: getCampaign
      tags: [Campaigns]
      responses:
        "200":
          description: Campaign
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "400":
          description: "CAMPAIGNS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that ID in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back. `RESOURCE_ID_INVALID`: the id in the path is not an id at all."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "500":
          description: The read failed. Safe to retry.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
    patch:
      summary: Update campaign
      description: |
        Send only the fields you want to change. Same writable allowlist as
        `POST /campaigns` — unknown and engine-owned keys are rejected with `400` rather
        than ignored. Required scope `campaigns:manage`.

        Config can be edited while a campaign is `running`; the new pacing and stop rules
        take effect on the next evaluation. A `completed`, `stopped` or `archived`
        campaign can no longer be edited.
      operationId: updateCampaign
      tags: [Campaigns]
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                description: { type: string, nullable: true }
                agent_id: { type: string, format: uuid }
                from_phone_number_id: { type: string, format: uuid }
                variables:
                  type: object
                  additionalProperties: { type: string }
                  description: Replaces the campaign's placeholder values. String values only. `FirstName` and `FullName` are filled on each call from its contact's own name; a value here is what a contact with no name hears.
                calling_window:
                  type: object
                  additionalProperties: true
                  description: >
                    `tz` (an IANA zone name) is required whenever `days`, `start` or
                    `end` is present; `{}` inherits the workspace schedule. `days` 0–6,
                    each once, never empty; `start`/`end` as HH:MM, together, `end` later
                    than `start`.
                split:
                  nullable: true
                  description: >
                    Replaces the campaign's A/B test; `null` turns it off. Contacts
                    already assigned keep the agent they got while the same two agents
                    keep running; a contact held by an agent this campaign no longer
                    runs is assigned again on its next attempt.
                  allOf:
                    - $ref: "#/components/schemas/AgentSplit"
                stop_disposition_ids:
                  type: array
                  items: { type: string, format: uuid }
                  description: "Replaces the whole set. Interested is accepted; No Answer, Voicemail, Unclassified and Failed are refused. Left out, the set is unchanged. To go back to the suggested set after `[]`, send `settings.stop_disposition_ids` from GET /campaigns/defaults; `null` is refused."
                stop_on_no_answer: { type: boolean }
                stop_on_voicemail: { type: boolean }
                stop_on_unclassified: { type: boolean }
                max_attempts: { type: integer, minimum: 1, maximum: 999 }
                max_infra_retries: { type: integer, minimum: 0, maximum: 20 }
                retry_no_answer_seconds: { type: integer, minimum: 30, maximum: 604800 }
                retry_completed_seconds: { type: integer, minimum: 60, maximum: 604800 }
                randomize_retry_time: { type: boolean }
                double_dial_enabled: { type: boolean }
                double_dial_gap_seconds: { type: integer, minimum: 10, maximum: 3600 }
                max_calls_per_day: { type: integer, minimum: 1, maximum: 100000 }
                min_seconds_between_calls: { type: integer, minimum: 0, maximum: 86400 }
                max_in_flight: { type: integer, minimum: 1, maximum: 8 }
                budget_cents: { type: integer, minimum: 1, nullable: true }
                regulatory_basis: { type: string, enum: [lawful_basis_confirmed, consent, existing_customer, non_marketing, registry_screened] }
                starts_at: { type: string, format: date-time, nullable: true }
                ends_at: { type: string, format: date-time, nullable: true }
      responses:
        "200":
          description: Updated campaign
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "400":
          description: >
            CAMPAIGN_REQUEST_INVALID — unknown or read-only field, no writable field supplied, a
            value out of range, a `calling_window` that cannot open, an `ends_at` already passed
            or not after `starts_at`, a `calling_window` that never opens between `starts_at`
            and `ends_at` (the values sent, or the stored ones for what the edit leaves out),
            a platform outcome in `stop_disposition_ids`, a `budget_cents` below one call's
            hold, a `from_phone_number_id` set to `null` (or an `agent_id` changed) leaving an agent
            with no number to call from, or a body that is not JSON. BAD_REQUEST — the campaign is
            `completed` / `stopped` / `archived` and can no longer be edited. A
            `from_phone_number_id` or agent that is not this workspace's is named in the same
            CAMPAIGN_REQUEST_INVALID issues[] (field_unknown, outcome_not_found at
            /stop_disposition_ids/<n>, invalid_from_number, agent_not_found) as on
            POST /campaigns; nothing was written.
          content: { application/json: { schema: { $ref: "#/components/schemas/WorkflowError" } } }
        "403":
          description: >
            A key limited to some agents named an agent that is not its own
            (`AGENT_OUTSIDE_KEY_SCOPE`), or a `from_phone_number_id` none of its agents answers or
            calls from (`API_KEY_AGENT_SCOPED`).
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that ID in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back. `RESOURCE_ID_INVALID`: the id in the path is not an id at all."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "422":
          description: "`INVALID_SPLIT` — see POST /campaigns."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

    delete:
      summary: Archive campaign
      description: |
        Soft-deletes the campaign: the campaign and its history are retained for
        reporting, but it disappears from `GET /campaigns`, stops being returned by
        `GET /campaigns/{id}`, and can never be edited, resumed or re-launched. Its
        `name` is freed for reuse.

        Archiving is also a stop: every contact still `pending`, `scheduled`, `dialing`
        or `awaiting_disposition` is retired to `excluded`, and every call this campaign
        had waiting to be dialed is cancelled on a best-effort basis — a call the
        dispatcher already picked up completes normally. Required scope
        `campaigns:manage`. Not idempotent in its response: calling it again on an
        already-archived campaign answers `404`, the same as one that never existed.
      operationId: archiveCampaign
      tags: [Campaigns]
      responses:
        "200":
          description: Acknowledgement, not the full campaign object — the campaign is no longer readable.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  status: { type: string, enum: [archived] }
                  company_id: { type: string, format: uuid }
        "401":
          description: Unauthorized
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that ID in this workspace. `CAMPAIGN_ARCHIVED`: it is already archived; the message names `POST /campaigns/{id}/restore`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "500":
          description: The archive write failed. The campaign is unchanged; safe to retry.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /campaigns/{id}/stats:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get campaign stats
      description: |
        Progress counters plus `last_tick_result` — the engine's own account of what it
        last did with this campaign, and the field to read when a `running` campaign looks
        idle. Required scope `campaigns:read`.
      operationId: getCampaignStats
      tags: [Campaigns]
      responses:
        "200":
          description: Campaign stats
          content:
            application/json:
              schema: { $ref: "#/components/schemas/CampaignStats" }
        "400":
          description: "CAMPAIGNS_QUERY_INVALID: a query parameter this route does not read. It reads none, and anything sent is refused by name rather than ignored."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: "`NOT_FOUND`: no campaign with that id in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /campaigns/{id}/leads:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: List campaign contacts
      description: |
        Enrolled contacts and their per-contact state, oldest enrollment first. Required
        scope `campaigns:read`. Each contact's `lead` is the full Lead only for a key that
        also holds `leads:read`; without it `lead` is `{id}`, as on `GET /calls`.
      operationId: listCampaignContacts
      tags: [Campaigns]
      parameters:
        - in: query
          name: status
          schema: { type: string }
          description: "Comma-separated list of contact statuses to include. A status that does not exist is 400 CAMPAIGNS_QUERY_INVALID."
          example: "pending,awaiting_disposition"
        - in: query
          name: phone
          schema: { type: string }
          description: >
            Find a contact by its number in any format — `0509107302`, `050-910-7302` and
            `+972509107302` find the same contact — or by part of it (at least 3 digits).
            Text that is not a number is 400 CAMPAIGNS_QUERY_INVALID.
          example: "050-910-7302"
        - in: query
          name: limit
          schema: { type: integer, default: 50, maximum: 200 }
        - in: query
          name: offset
          schema: { type: integer, default: 0 }
      responses:
        "200":
          description: Enrolled contacts
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/CampaignContact" }
                  pagination:
                    type: object
                    properties:
                      total: { type: integer }
                      limit: { type: integer }
                      offset: { type: integer }
                      has_more: { type: boolean, description: "Whether another page follows: page with offset += limit while it is true." }
                  campaign_id: { type: string, format: uuid }
                  company_id: { type: string, format: uuid }
        "400":
          description: CAMPAIGNS_QUERY_INVALID — `status` names a contact status that does not exist, or `phone` is not a phone number.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that id in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

    post:
      summary: Enroll contacts
      description: |
        Enroll existing leads by `lead_ids`, raw numbers via `phone_numbers`, or both in
        one request. Raw numbers are normalized to E.164 and matched against your existing
        leads; a lead is created only when there is no match. Required scope
        `campaigns:manage`. A key limited to some agents enrolls into its own campaigns
        the same way: leads belong to the whole workspace, so this is the one way such a
        key creates or reuses one.

        Enrollment is per-row and idempotent: unparseable numbers, numbers on the
        do-not-call list, numbers another live campaign is calling, and unknown lead IDs
        are reported in the response instead of failing the batch, and re-enrolling an
        existing contact is a no-op. At most 1,000
        contacts per request — send several requests for larger lists.

        You can enroll into a `running` campaign; new contacts join the pacing queue. A
        `completed`, `stopped` or `archived` campaign rejects enrollment.
      operationId: enrollCampaignContacts
      tags: [Campaigns]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: "Supply `lead_ids`, `phone_numbers`, or both — at least one must be non-empty."
              properties:
                lead_ids:
                  type: array
                  description: "IDs of leads that already exist in this workspace."
                  items: { type: string, format: uuid }
                phone_numbers:
                  type: array
                  description: >
                    Numbers to enroll. Each entry is either a bare phone string or an object.
                    Any format is accepted and normalized to E.164.
                  items:
                    oneOf:
                      - type: string
                        example: "+972501234567"
                      - type: object
                        required: [phone]
                        properties:
                          phone: { type: string, example: "0501234567"  }
                          name: { type: string, nullable: true }
                          email: { type: string, format: email, nullable: true }
                          notes:
                            type: string
                            nullable: true
                            description: "Becomes the lead's AI memory (`long_term_context`), capped at 2,000 characters."
      responses:
        "200":
          description: >
            Enrollment report. Returned even when nothing was enrolled — read the counters
            and the rejection arrays to see why.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/EnrollmentReport" }
        "400":
          description: >
            `CAMPAIGN_REQUEST_INVALID` with `issues[]`: a field the request or an entry does
            not read — each one named at once with `code: field_unknown`, its `path`
            (`/phone_numbers/0/emial`) and, when one is close, the field it was likely meant
            to be ("Did you mean email?"). Nothing is enrolled. `BAD_REQUEST`: a body that is
            not a JSON object, neither `lead_ids` nor `phone_numbers` supplied, more than
            1,000 contacts in one request, or the campaign is `completed` / `stopped`.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: >
            `NOT_FOUND`: no campaign with that id in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back.
            `RESOURCE_ID_INVALID`: the id in the path is not an id.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "500":
          description: The check for numbers already on a campaign, or the write, failed. Safe to retry — enrolment is idempotent.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /campaigns/{id}/leads/{lead_id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
      - in: path
        name: lead_id
        required: true
        schema: { type: string, format: uuid }
        description: "Lead ID (not the `CampaignContact.id`)."
    delete:
      summary: Exclude contact
      description: |
        Retires one contact for this campaign with status `excluded`. Terminal — the
        contact is never dialed by this campaign again, and re-enrolling does not revive
        it. The underlying lead is untouched. Required scope `campaigns:manage`.
      operationId: excludeCampaignContact
      tags: [Campaigns]
      responses:
        "200":
          description: Contact excluded
          content:
            application/json:
              schema:
                type: object
                properties:
                  campaign_id: { type: string, format: uuid }
                  lead_id: { type: string, format: uuid }
                  status: { type: string, example: excluded  }
                  company_id: { type: string, format: uuid }
        "400":
          description: No lead ID in the path
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that id in this workspace, or that lead is not enrolled in it. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /campaigns/{id}/launch:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Launch campaign
      description: |
        Moves the campaign to `running`. Required scope `campaigns:manage`.

        Preflight — all of these must hold, or the call returns `422 CAMPAIGN_NOT_READY`
        with the one thing to fix:

        - an `agent_id` is assigned, and that agent still exists
        - that agent has a positive `max_call_duration_secs`, so the cost ceiling is bounded
        - there is a number to call from: `from_phone_number_id`, still active (and, on your own
          Telnyx account, connected to a working account), or with none named the agent's own number
        - `regulatory_basis` is set
        - a stored `calling_window` can open: a real `tz`, days from `0` to `6`, `start`
          and `end` as `HH:MM`, and not a window of zero minutes. A stored window that
          passes midnight wraps, `days: []` means every day, half a window is ignored, a
          day stored as text (`"1"`) is that day, a time stored as `HH:MM:SS` opens at its
          `HH:MM` and a `null` `tz` is the workspace's, exactly as the dialler reads them,
          so none of those is refused here
        - `ends_at` has not passed — otherwise the campaign would complete without
          calling anyone
        - the stored `calling_window` opens at least once between now (or `starts_at`,
          if later) and `ends_at`, read the way the dialler reads it
        - `budget_cents`, when set, is at least one call's hold, so the first call can be
          placed
        - the assigned agent is switched on (`is_active`), and a workflow agent has a
          published version

        `?dry_run=true` runs this preflight and changes nothing: `200` with
        `ready: true` when every check passes, or the same `422` a launch would give.
        - every configuration field is set — none but `stop_disposition_ids` has a default,
          so a field never sent is still `null`: `max_attempts`, `max_infra_retries`,
          `retry_no_answer_seconds`, `retry_completed_seconds`, `randomize_retry_time`,
          `stop_on_no_answer`, `stop_on_voicemail`, `stop_on_unclassified`,
          `double_dial_enabled`, `double_dial_gap_seconds`, `max_calls_per_day`,
          `min_seconds_between_calls`, `max_in_flight`
        - at least one stop rule is configured (`stop_disposition_ids`, `stop_on_no_answer`,
          `stop_on_voicemail`) — otherwise the campaign would
          call every contact until the attempt cap
        - the workspace has an upcoming calling window
        - at least one contact is enrolled and eligible

        Launching is also how you leave any of the `paused_*` states. Launching an
        already-`running` campaign is a no-op and returns `200`.
      operationId: launchCampaign
      tags: [Campaigns]
      parameters:
        - in: query
          name: dry_run
          schema: { type: boolean }
          description: >
            `true` runs the preflight and changes nothing — `200` with `ready: true`, or
            the `422` a launch would give. Any value other than `true`/`false` is
            `400 CAMPAIGNS_QUERY_INVALID`.
      responses:
        "200":
          description: >
            Campaign is running — or, with `dry_run=true`, `{ ready: true, campaign_id,
            status, message, company_id }` and nothing changed.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Campaign"
                  - type: object
                    properties:
                      message: { type: string, description: "Present when there was nothing to do, such as `Already running`." }
        "400":
          description: The campaign is in a status it cannot be launched from (e.g. `completed`, `stopped`, `archived`).
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that id in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "409":
          description: "`CONFLICT` — Launching a draft: another campaign started calling one of its contacts at the same instant. Nothing changed; launch again, and that contact is skipped with `stop_reason: in_another_campaign`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "422":
          description: "`CAMPAIGN_NOT_READY` — preflight failed; `message` names the single thing to fix."
          content: { application/json: { schema: { $ref: "#/components/schemas/CampaignError" } } }

  /campaigns/{id}/pause:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Pause campaign
      description: |
        Moves the campaign to `paused` and stops admitting new calls; calls already
        connected finish normally. Required scope `campaigns:manage`.

        A manual pause is **never** lifted automatically — unlike
        `paused_insufficient_credit`, it survives a top-up. Resume it yourself with
        `POST /campaigns/{id}/resume`.
      operationId: pauseCampaign
      tags: [Campaigns]
      responses:
        "200":
          description: Campaign paused
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "400":
          description: The campaign is in a status it cannot be paused from (e.g. `draft`, `completed`, `stopped`, `archived`).
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that id in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /campaigns/{id}/resume:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Resume campaign
      description: |
        Returns a paused campaign to `running`. Runs the same preflight as
        `POST /campaigns/{id}/launch`, so a campaign that was paused because its number
        was released or its calling window disappeared reports `422 CAMPAIGN_NOT_READY`
        instead of silently failing to dial. Resuming an already-`running` campaign is a
        no-op. Required scope `campaigns:manage`.
      operationId: resumeCampaign
      tags: [Campaigns]
      parameters:
        - in: query
          name: dry_run
          schema: { type: boolean }
          description: "`true` runs the preflight and changes nothing, as on launch."
      responses:
        "200":
          description: Campaign is running
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "400":
          description: The campaign is in a status it cannot be resumed from (e.g. `completed`, `stopped`, `archived`).
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that id in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "409":
          description: "`CONFLICT` — Resuming a `draft`: another campaign started calling one of its contacts at the same instant. Nothing changed; send it again, and that contact is skipped with `stop_reason: in_another_campaign`."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "422":
          description: "`CAMPAIGN_NOT_READY` — preflight failed; `message` names the single thing to fix."
          content: { application/json: { schema: { $ref: "#/components/schemas/CampaignError" } } }

  /campaigns/{id}/stop:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Stop campaign
      description: |
        Moves the campaign to `stopped` and retires every contact still waiting to be
        dialed. **Terminal** — a stopped campaign cannot be relaunched; create a new one
        instead. Use `POST /campaigns/{id}/pause` if you want to continue later. Calls
        already connected finish normally. Required scope `campaigns:manage`.
      operationId: stopCampaign
      tags: [Campaigns]
      responses:
        "200":
          description: Campaign stopped
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "400":
          description: The campaign is already `completed`, `stopped` or `archived`.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that id in this workspace. `CAMPAIGN_ARCHIVED`: it is archived; the message names `POST /campaigns/{id}/restore`, which brings it back."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "409":
          description: >
            CAMPAIGN_NOT_STOPPABLE — the campaign is a draft whose settings are not complete, so
            it cannot be recorded as stopped; the message names the settings that are not set.
            It never dialled anyone: archive it with
            `DELETE /campaigns/{id}`, or complete it and launch it. Nothing changed.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /campaigns/{id}/restore:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    post:
      summary: Restore campaign
      description: |
        Brings an archived campaign back. One that never launched (`started_at` null) is a
        `draft` again, and every contact the archive retired (`excluded`, `stop_reason:
        campaign_archived`) is `pending` again; one excluded by hand stays excluded. One that
        had launched comes back `stopped`, its contacts as they are. Archived campaigns are
        listed with `GET /campaigns?status=archived`. Required scope `campaigns:manage`.
      operationId: restoreCampaign
      tags: [Campaigns]
      responses:
        "200":
          description: The campaign, now `draft` or `stopped`.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Campaign" }
        "400":
          description: "CAMPAIGN_REQUEST_INVALID: a body field (each in issues[] as field_unknown at its pointer, /status), or a body that is not a JSON object. Restoring takes no body. Nothing changed."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "404":
          description: "`NOT_FOUND`: no campaign with that id in this workspace. `RESOURCE_ID_INVALID`: the id is not an id."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "409":
          description: >
            CAMPAIGN_NOT_ARCHIVED — the campaign is not archived (the message names its status).
            CAMPAIGN_STOP_RULE_REQUIRED — it had launched and its last stop outcome was deleted while it
            was archived, so it cannot come back as stopped; create a new campaign. Nothing changed.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  # ── Affiliates ─────────────────────────────────────────────────────────────
  #
  # Both endpoints are scoped to the API key's own workspace and take no company
  # identifier of any kind. Passing `company_id` is a 400, not a cross-workspace
  # read.

  /api-keys:
    get:
      summary: List API keys
      description: |
        Every active API key in your workspace, newest first. The secret is
        never returned — only `prefix`, which is its first 16 characters.
        `?revoked=true` lists the keys this workspace has revoked instead, newest
        revocation first, each with `revoked_at` and who revoked it (`revoked_by`,
        a person; `revoked_by_key`, a key): a revoked key stays on record and
        never works again. `revoked_since` and `revoked_until` narrow that list
        to a range, and `pagination.next_cursor` continues it. Revocations are on
        record from 22 September 2026, and who revoked a key from 28 September 2026.
        Without `limit` the answer holds every key,
        as it always has; `limit` and `offset` page it like any other list.

        Requires `api_keys:read`, or `api_keys:manage`, which reads the list
        as well. `api_keys:read` is read-only: a key holding it can audit the
        inventory and can neither issue nor revoke anything.
      operationId: listApiKeys
      tags: [API Keys]
      parameters:
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 100 }, description: "How many keys to answer with. Leave it out for every key." }
        - { in: query, name: offset, schema: { type: integer, minimum: 0, default: 0 }, description: "How many of the newest keys to skip." }
        - { in: query, name: revoked, schema: { type: boolean, default: false }, description: "`true` lists the revoked keys, each with `revoked_at`, `revoked_by` and `revoked_by_key`; `false` (the default) the live ones." }
        - { in: query, name: revoked_since, schema: { type: string }, description: "With `revoked=true`: keys revoked at or after this moment. An ISO 8601 date-time with a time zone (`Z` or an offset), or a date (the start of that UTC day). A time with no zone is refused." }
        - { in: query, name: revoked_until, schema: { type: string }, description: "With `revoked=true`: keys revoked at or before this moment. A date-time with a time zone, or a bare date, which covers that whole UTC day. A time with no zone is refused." }
        - { in: query, name: cursor, schema: { type: string }, description: "With `revoked=true`: `pagination.next_cursor` from the previous page, sent with the same `revoked_since` / `revoked_until`. Not with `offset`." }
      responses:
        "200":
          description: The workspace's active keys, or its revoked keys with `revoked=true`
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    description: "`ApiKey` rows on the live list; `RevokedApiKey` rows, which carry every `ApiKey` field, on `revoked=true`."
                    items:
                      anyOf:
                        - $ref: "#/components/schemas/ApiKey"
                        - $ref: "#/components/schemas/RevokedApiKey"
                  pagination:
                    type: object
                    properties:
                      total: { type: integer, description: "How many keys the list holds - on `revoked=true`, within the range." }
                      limit: { type: integer, description: "The `limit` sent, or the number of keys when none was." }
                      offset: { type: integer }
                      has_more: { type: boolean }
                      next_cursor: { type: string, nullable: true, description: "On `revoked=true` only: send it as `cursor` for the next page; null on the last." }
        "400":
          description: API_KEY_REQUEST_INVALID - a query parameter other than `limit`, `offset`, `revoked`, `revoked_since`, `revoked_until` and `cursor`, one sent twice or with no value, a `limit` outside 1-100, an `offset` that is not a whole number, a `revoked` other than `true` / `false`, a range or cursor without `revoked=true`, a `revoked_since` / `revoked_until` that is not a real date, has a time of day with no time zone (`query_param_invalid` in `issues[]`), or ends before it starts, a `cursor` this list did not hand out for this workspace and range, or `cursor` with `offset`. The message names it.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: INSUFFICIENT_SCOPE - the key is valid for this workspace but holds neither api_keys:read nor api_keys:manage. Nothing was read. A workspace owner or admin can tick API keys -> Read on this key in Settings -> API keys; a key cannot obtain it through the API, because issuing a key needs api_keys:manage, which reads the list itself.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: The key store could not be read. Retry.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    post:
      summary: Issue an API key
      description: |
        Issues a new key and returns its secret **once**. There is no way to read
        it again.

        Two rules decide what the new key may hold:

        - **Subset.** You can only grant scopes the calling key itself holds.
          Asking for anything more answers `403 API_KEY_SCOPE_ESCALATION`, naming
          the scopes that went beyond. `api_keys:manage` includes
          `api_keys:read`: a key holding manage can grant read even when read is
          not ticked on it, because it already reads the list.
        - **`api_keys:manage` is never granted here.** A key issued through the
          API cannot issue keys of its own, even when the calling key can. Ask
          for it and the answer is `403 API_KEY_MANAGE_NOT_DELEGABLE`. Grant it
          in the dashboard, under Settings → API keys.

        `scopes` is required and has no default: a key gets exactly what you ask
        for. Requires `api_keys:manage`, which only a key created in the
        dashboard can hold: there is no bootstrap endpoint, so the first key of
        a workspace is always made by a person under Settings → API Keys.
      operationId: createApiKey
      tags: [API Keys]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, scopes]
              additionalProperties: false
              properties:
                name:
                  type: string
                  maxLength: 100
                  description: Unique among this workspace's active keys, compared without regard to case (`Client-A` is taken while `client-a` is live). The only handle you have on the key afterwards.
                  example: "Nightly lead sync"
                scopes:
                  type: array
                  minItems: 1
                  items: { type: string }
                  description: A subset of the calling key's own scopes (`api_keys:read` counts as held by a key with `api_keys:manage`). `api_keys:manage` is not accepted.
                  example: ["leads:read", "leads:manage"]
                agent_ids:
                  type: array
                  nullable: true
                  minItems: 1
                  maxItems: 100
                  items: { type: string, format: uuid }
                  description: |
                    Limit the key to these agents — live agents in this workspace.
                    Leave it out or send `null` for a key that reaches the whole
                    workspace. An unknown id answers `400 API_KEY_AGENT_UNKNOWN`
                    and an empty list `400 API_KEY_REQUEST_INVALID`.
                expires_at:
                  type: string
                  format: date-time
                  nullable: true
                  description: |
                    When the key stops working: an ISO 8601 date-time with a time
                    zone, in the future. Leave it out or send `null` for a key that
                    works until it is revoked. A past moment or a date without a
                    time zone answers `400 API_KEY_REQUEST_INVALID`.
                  example: "2026-12-31T23:59:59Z"
      responses:
        "201":
          description: Key issued. The only response that contains the secret.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApiKeyCreated" }
        "400":
          description: API_KEY_REQUEST_INVALID - missing name, missing or empty scopes, an expires_at that is not a future date-time with a time zone, scopes a key limited by agent_ids could never use (agents:create, tools:create and the other workspace-wide scopes, each named), or a field this endpoint does not take (the message names it; no key is issued). API_KEY_SCOPE_UNKNOWN - a scope that does not exist. API_KEY_AGENT_UNKNOWN - an agent_ids entry that is not a live agent here.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "403":
          description: A requested scope is beyond the calling key, or is `api_keys:manage`
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: API_KEY_NAME_TAKEN - an active key of that name, compared without regard to case, already exists in this workspace; the message names it as it is spelled. Two creates sent at once under one spelling get one key and one 409.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: The key store could not be written. No key was created — retry.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /api-keys/{id}:
    parameters:
      - in: path
        name: id
        required: true
        schema: { type: string, format: uuid }
    get:
      summary: Get an API key
      description: |
        One active key, by id. Never returns the secret. For a key limited to
        some agents, `agents` names each one. Requires `api_keys:read`, or
        `api_keys:manage`, which reads a key as well.
      operationId: getApiKey
      tags: [API Keys]
      responses:
        "200":
          description: The key
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ApiKey" }
        "403":
          description: INSUFFICIENT_SCOPE - the key is valid for this workspace but holds neither api_keys:read nor api_keys:manage. Nothing was read. A workspace owner or admin can tick API keys -> Read on this key in Settings -> API keys; a key cannot obtain it through the API, because issuing a key needs api_keys:manage, which reads the list itself.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "404":
          description: No such key here, or it has been revoked
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: The key store could not be read. Retry.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
    delete:
      summary: Revoke an API key
      description: |
        Revokes the key immediately — every request it makes from then on is
        refused, and it drops out of the list. This cannot be undone; issue a new
        key instead.

        A key cannot revoke itself through the API: nothing would be left able to
        issue or revoke keys for the workspace. Revoke the calling key from the
        dashboard. Requires `api_keys:manage`.

        The calling key is recorded as the one that revoked it:
        `GET /api-keys?revoked=true` shows it as `revoked_by_key`.
      operationId: revokeApiKey
      tags: [API Keys]
      responses:
        "200":
          description: Revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  id: { type: string, format: uuid }
        "404":
          description: No such key here, or it was already revoked
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "409":
          description: That id is the calling key
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "503":
          description: The key store could not be written. Retry.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /affiliates/stats:
    get:
      summary: Get affiliate stats
      description: |
        Your referral code, your commission rates, lifetime totals, and a trailing
        month-by-month breakdown. Always scoped to the API key's own workspace —
        there is no path, query or body parameter for a company id, and supplying
        `company_id` returns `400`. Required scope `affiliates:read`.

        **Money is integer US cents.** Every `*_cents` field, including
        `payout_sent_cents`, is denominated in US cents no matter which currency a
        payout was actually wired in. Divide by 100 for dollars.

        **Earned vs payable.** `earned_cents` is everything you have accrued.
        `payable_cents` is the part that has aged past `hold_days` and is claimable
        now; it is the number payouts are drawn from. `outstanding_cents` is
        `payable_cents - paid_cents` and **may be negative** when you have been paid
        ahead of the hold window — that is a real state, not an error.

        **Reconciliation.** `earned_before_window_cents` plus the sum of
        `months[].commission_cents` equals `summary.earned_cents` exactly, so the
        table on screen can always be made to add up to the lifetime total.
      operationId: getAffiliateStats
      tags: [Affiliates]
      parameters:
        - in: query
          name: months
          schema: { type: integer, minimum: 1, maximum: 60, default: 12 }
          description: How many trailing months `months[]` should cover. Does not affect `summary`, which is lifetime.
      responses:
        "200":
          description: Affiliate stats
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AffiliateStats" }
        "400":
          description: "`AFFILIATES_QUERY_INVALID` — `months` is out of range, or a parameter other than `months` (such as `company_id`) was sent, or one was sent twice or with no value. The message names it."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: "`INSUFFICIENT_SCOPE` — the key does not hold `affiliates:read`, and the message names it. `AFFILIATE_FORBIDDEN` — affiliate data is not readable for this workspace."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /affiliates/downline:
    get:
      summary: List sub-affiliates
      description: |
        The partners enrolled beneath you, and the tier-2 override you have earned
        through each. Driven from the referral graph rather than from revenue, so a
        partner enrolled yesterday with no customers yet is a row of zeros rather
        than a missing row. Required scope `affiliates:read`.

        Enrolment is an explicit act by Yappr — a customer who happens to share
        their own referral link never appears here, and their name and revenue are
        never disclosed to you. Most workspaces get an empty list.

        All amounts are integer US cents. `downline_revenue_cents` is paid customer
        service revenue, excluding gifts and taxes. `override_basis` on GET /affiliates/stats
        says whether your tier-2 rate applies to that revenue or to your partner's earned
        direct commission. Their full commission is unchanged and yours is paid on top.
        `my_override_cents` is what you earned; `my_override_payable_cents` is the part
        past the hold window. Refunds reduce earnings at the original payment's rates.
      operationId: listAffiliateDownline
      tags: [Affiliates]
      responses:
        "200":
          description: Sub-affiliates
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/AffiliateDownlineRow" }
        "400":
          description: "`AFFILIATES_QUERY_INVALID` — a query parameter (such as `company_id`) was sent; this read takes none, and the message names it."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "403":
          description: "`INSUFFICIENT_SCOPE` — the key does not hold `affiliates:read`, and the message names it. `AFFILIATE_FORBIDDEN` — affiliate data is not readable for this workspace."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }

  /report-issue:
    post:
      summary: Report an issue
      description: |
        Files a bug or a feature request with the Yappr team, attributed to the
        workspace that issued the key. Any valid key may call it: no scope is
        needed. Reports whose titles closely match one already open are added
        to that one, and the answer is `created` either way.
      operationId: reportIssue
      tags: [Support]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title, description, type]
              properties:
                title: { type: string, minLength: 5, description: "At least 5 characters. Longer is accepted and cut at 200." }
                description: { type: string, minLength: 10, description: "At least 10 characters. Longer is accepted and cut at 5000." }
                type: { type: string, enum: [bug, feature] }
                source: { type: string, description: "Where the report comes from, e.g. `yappr-skill`. Defaults to `yappr-api`. Longer is accepted and cut at 100." }
                steps_to_reproduce: { type: string, description: "Longer is accepted and cut at 2000." }
                error_message: { type: string, description: "Longer is accepted and cut at 2000." }
                call_ids: { type: array, items: { type: string }, description: "Calls that show the problem. More are accepted and cut at 20." }
                reporter_email: { type: string, description: "Longer is accepted and cut at 200." }
                reporter_context: { type: string, description: "Longer is accepted and cut at 500." }
      responses:
        "200":
          description: The report was filed.
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: { type: string, enum: [created] }
        "400":
          description: "`BAD_REQUEST` — the body is not JSON, `title` is under 5 characters, `description` is under 10, or `type` is not `bug` or `feature`. The message says which."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "401":
          description: MISSING_KEY, INVALID_KEY or EXPIRED_KEY - the key was not accepted.
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "502":
          description: "`UPSTREAM_ERROR` — the report could not be filed. Try again, or write to support."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
        "503":
          description: "`SERVICE_UNAVAILABLE` — reporting is not available right now. Write to support instead."
          content: { application/json: { schema: { $ref: "#/components/schemas/Error" } } }
